123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- #!/usr/bin/env bash
- set -eu
- script_name=$0
- DB_BACKEND=$(echo $script_name | cut -d- -f2)
- export DB_BACKEND
- die() {
- echo >&2 "$@"
- exit 1
- }
- PGHOST=${PGHOST:-127.0.0.1}
- PGPORT=${PGPORT:-5432}
- PGPASSWORD=${PGPASSWORD:-postgres}
- PGUSER=${PGUSER:-postgres}
- export PGHOST
- export PGPORT
- export PGPASSWORD
- export PGUSER
- about() {
- die "usage: $script_name [ config_yaml | setup | dump <backup_file> | restore <backup_file> ]"
- }
- check_postgres_client() {
- if ! command -v psql --version >/dev/null; then
- die "missing required program 'psql' as a postgres client (package postgres-client-13 on debian like system)"
- fi
- }
- exec_sql() {
- cmd="${1?Missing required sql command}"
- psql <<< "$cmd"
- }
- requirements() {
- check_mysql_client
- }
- setup() {
- exec_sql "DROP DATABASE IF EXISTS crowdsec_test;"
- exec_sql "CREATE DATABASE crowdsec_test;"
- exec_sql "DROP USER IF EXISTS crowdsec_test;"
- exec_sql "CREATE USER crowdsec_test WITH ENCRYPTED PASSWORD 'crowdsec_test';"
- exec_sql "GRANT ALL PRIVILEGES ON DATABASE crowdsec_test TO crowdsec_test;"
- # exec_sql "SET log_statement='all';"
- # exec_sql "SELECT pg_reload_conf();"
- }
- dump() {
- backup_file="${1?Missing file to backup database to}"
- pg_dump -Ft --dbname crowdsec_test > "$backup_file"
- }
- restore() {
- backup_file="${1?missing file to restore database from}"
- [ -f "$backup_file" ] || die "Backup file $backup_file doesn't exist"
- pg_restore --dbname crowdsec_test --clean < "$backup_file"
- }
- config_yaml() {
- yq '
- .db_config.type=strenv(DB_BACKEND)|
- .db_config.user="crowdsec_test" |
- .db_config.password="crowdsec_test" |
- .db_config.db_name="crowdsec_test" |
- .db_config.host=strenv(PGHOST) |
- .db_config.port=env(PGPORT) |
- .db_config.sslmode="disable" |
- del(.db_config.db_path)
- ' -i "${CONFIG_YAML}"
- }
- [ $# -lt 1 ] && about
- case "$1" in
- setup)
- setup
- ;;
- config-yaml)
- config_yaml
- ;;
- dump)
- shift
- dump "$@"
- ;;
- restore)
- shift
- restore "$@"
- ;;
- exec_sql)
- shift
- exec_sql "$@"
- ;;
- *)
- about
- ;;
- esac;
|