instance-postgres 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. PGHOST=${PGHOST:-127.0.0.1}
  11. PGPORT=${PGPORT:-5432}
  12. PGPASSWORD=${PGPASSWORD:-postgres}
  13. PGUSER=${PGUSER:-postgres}
  14. export PGHOST
  15. export PGPORT
  16. export PGPASSWORD
  17. export PGUSER
  18. about() {
  19. die "usage: $script_name [ config_yaml | setup | dump <backup_file> | restore <backup_file> ]"
  20. }
  21. check_postgres_client() {
  22. if ! command -v psql --version >/dev/null; then
  23. die "missing required program 'psql' as a postgres client (package postgres-client-13 on debian like system)"
  24. fi
  25. }
  26. exec_sql() {
  27. cmd="${1?Missing required sql command}"
  28. psql <<< "$cmd"
  29. }
  30. requirements() {
  31. check_mysql_client
  32. }
  33. setup() {
  34. exec_sql "DROP DATABASE IF EXISTS crowdsec_test;"
  35. exec_sql "CREATE DATABASE crowdsec_test;"
  36. exec_sql "DROP USER IF EXISTS crowdsec_test;"
  37. exec_sql "CREATE USER crowdsec_test WITH ENCRYPTED PASSWORD 'crowdsec_test';"
  38. exec_sql "GRANT ALL PRIVILEGES ON DATABASE crowdsec_test TO crowdsec_test;"
  39. # exec_sql "SET log_statement='all';"
  40. # exec_sql "SELECT pg_reload_conf();"
  41. }
  42. dump() {
  43. backup_file="${1?Missing file to backup database to}"
  44. pg_dump -Ft --dbname crowdsec_test > "$backup_file"
  45. }
  46. restore() {
  47. backup_file="${1?missing file to restore database from}"
  48. [ -f "$backup_file" ] || die "Backup file $backup_file doesn't exist"
  49. pg_restore --dbname crowdsec_test --clean < "$backup_file"
  50. }
  51. config_yaml() {
  52. yq '
  53. .db_config.type="$DB_BACKEND"|
  54. .db_config.user="crowdsec_test" |
  55. .db_config.password="crowdsec_test" |
  56. .db_config.db_name="crowdsec_test" |
  57. .db_config.host=strenv(PGHOST) |
  58. .db_config.port=env(PGPORT) |
  59. .db_config.sslmode="disable" |
  60. del(.db_config.db_path)
  61. ' -i "${CONFIG_YAML}"
  62. }
  63. [ $# -lt 1 ] && about
  64. case "$1" in
  65. setup)
  66. setup
  67. ;;
  68. config-yaml)
  69. config_yaml
  70. ;;
  71. dump)
  72. shift
  73. dump "$@"
  74. ;;
  75. restore)
  76. shift
  77. restore "$@"
  78. ;;
  79. *)
  80. about
  81. ;;
  82. esac;