instance-sqlite 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #!/usr/bin/env bash
  2. set -eu
  3. script_name=$0
  4. DB_BACKEND=$(echo $script_name | cut -d- -f2)
  5. export DB_BACKEND
  6. die() {
  7. echo >&2 "$@"
  8. exit 1
  9. }
  10. about() {
  11. die "usage: $script_name [ config-yaml | setup | dump <backup_file> | restore <backup_file> ]"
  12. }
  13. #shellcheck disable=SC1007
  14. THIS_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
  15. cd "${THIS_DIR}"/../../
  16. #shellcheck disable=SC1091
  17. . ./.environment.sh
  18. exec_sql() {
  19. cmd="${1?Missing required sql command}"
  20. sqlite3 "${DB_FILE}" "$@"
  21. }
  22. setup() {
  23. :
  24. }
  25. dump() {
  26. backup_file="${1?Missing file to backup database to}"
  27. # dirty fast cp. nothing should be accessing it right now, anyway.
  28. [ -f "${DB_FILE}" ] || die "missing file ${DB_FILE}"
  29. cp "${DB_FILE}" "$backup_file"
  30. }
  31. restore() {
  32. backup_file="${1?missing file to restore database from}"
  33. [ -f "$backup_file" ] || die "Backup file $backup_file doesn't exist"
  34. cp "$backup_file" "${DB_FILE}"
  35. }
  36. # you have not removed set -u above, have you?
  37. [ -z "${CONFIG_YAML-}" ] && die "\$CONFIG_YAML must be defined."
  38. # ---------------------------
  39. # In most cases this is called with setup argument, and it shouldn't fail for missing config file.
  40. if [ -f "${CONFIG_YAML}" ] ; then
  41. DATA_DIR=$(yq e '.config_paths.data_dir' - <"${CONFIG_YAML}")
  42. DB_FILE="${DATA_DIR}/crowdsec.db"
  43. fi
  44. config_yaml() {
  45. yq e '
  46. .db_config.type=strenv(DB_BACKEND) |
  47. .db_config.db_path="${DB_FILE}"
  48. ' -i "${CONFIG_YAML}"
  49. }
  50. [ $# -lt 1 ] && about
  51. case "$1" in
  52. config-yaml)
  53. ;;
  54. setup)
  55. ;;
  56. dump)
  57. shift
  58. dump "$@"
  59. ;;
  60. restore)
  61. shift
  62. restore "$@"
  63. ;;
  64. exec_sql)
  65. shift
  66. exec_sql "$@"
  67. ;;
  68. *)
  69. about
  70. ;;
  71. esac;