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