instance-sqlite 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. # you have not removed set -u above, have you?
  23. [ -z "${CONFIG_YAML-}" ] && die "\$CONFIG_YAML must be defined."
  24. # ---------------------------
  25. # In most cases this is called with setup argument, and it shouldn't fail for missing config file.
  26. if [ -f "${CONFIG_YAML}" ] ; then
  27. DATA_DIR=$(yq '.config_paths.data_dir' <"${CONFIG_YAML}")
  28. DB_FILE="${DATA_DIR}/crowdsec.db"
  29. fi
  30. config_yaml() {
  31. yq '
  32. .db_config.type=strenv(DB_BACKEND) |
  33. .db_config.db_path="${DB_FILE}"
  34. ' -i "${CONFIG_YAML}"
  35. }
  36. [ $# -lt 1 ] && about
  37. case "$1" in
  38. config-yaml)
  39. ;;
  40. setup)
  41. ;;
  42. dump)
  43. [ $# -lt 2 ] && about
  44. backup_file="$2"
  45. # dirty fast cp. nothing should be accessing it right now, anyway.
  46. [ -f "${DB_FILE}" ] || die "missing file ${DB_FILE}"
  47. cp "${DB_FILE}" "$backup_file"
  48. ;;
  49. restore)
  50. [ $# -lt 2 ] && about
  51. backup_file="$2"
  52. [ -f "$backup_file" ] || die "missing file $backup_file"
  53. cp "$backup_file" "${DB_FILE}"
  54. ;;
  55. exec_sql)
  56. shift
  57. exec_sql "$@"
  58. ;;
  59. *)
  60. about
  61. ;;
  62. esac;