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. sqlite3 "${DB_FILE}" "$@"
  20. }
  21. setup() {
  22. :
  23. }
  24. dump() {
  25. backup_file="${1?Missing file to backup database to}"
  26. # dirty fast cp. nothing should be accessing it right now, anyway.
  27. [[ -f "${DB_FILE}" ]] || die "missing file ${DB_FILE}"
  28. cp "${DB_FILE}" "${backup_file}"
  29. }
  30. restore() {
  31. backup_file="${1?missing file to restore database from}"
  32. [[ -f "${backup_file}" ]] || die "Backup file ${backup_file} doesn't exist"
  33. cp "${backup_file}" "${DB_FILE}"
  34. }
  35. # you have not removed set -u above, have you?
  36. [[ -z "${CONFIG_YAML-}" ]] && die "\$CONFIG_YAML must be defined."
  37. # ---------------------------
  38. # In most cases this is called with setup argument, and it shouldn't fail for missing config file.
  39. if [[ -f "${CONFIG_YAML}" ]]; then
  40. DATA_DIR=$(yq e '.config_paths.data_dir' "${CONFIG_YAML}")
  41. DB_FILE="${DATA_DIR}/crowdsec.db"
  42. export DB_FILE
  43. fi
  44. config_yaml() {
  45. yq e '
  46. .db_config.type=strenv(DB_BACKEND) |
  47. .db_config.db_path=strenv(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;