72 lines
2.3 KiB
Bash
Executable File
72 lines
2.3 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
|
|
PATH="/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:${PATH:-}"
|
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
ROOT_DIR="$(cd "${SCRIPT_DIR}/../.." && pwd)"
|
|
ENV_FILE="${ROOT_DIR}/.env"
|
|
BACKUP_DIR="${BACKUP_DIR:-/volume1/naurua_db_backups/dev}"
|
|
FILE_PREFIX="${FILE_PREFIX:-erpnaurua_dev}"
|
|
PG_DUMP_BIN="${PG_DUMP_BIN:-$(command -v pg_dump || true)}"
|
|
PSQL_BIN="${PSQL_BIN:-$(command -v psql || true)}"
|
|
|
|
if [[ ! -f "${ENV_FILE}" ]]; then
|
|
echo "Missing environment file: ${ENV_FILE}" >&2
|
|
exit 1
|
|
fi
|
|
|
|
set -a
|
|
# shellcheck disable=SC1090
|
|
. "${ENV_FILE}"
|
|
set +a
|
|
|
|
for required_var in DB_HOST DB_PORT DB_NAME DB_USER DB_PASSWORD; do
|
|
if [[ -z "${!required_var:-}" ]]; then
|
|
echo "Missing required database setting: ${required_var}" >&2
|
|
exit 1
|
|
fi
|
|
done
|
|
|
|
if [[ -z "${PG_DUMP_BIN}" || ! -x "${PG_DUMP_BIN}" ]]; then
|
|
echo "Compatible pg_dump is required. Set PG_DUMP_BIN to a PostgreSQL client binary." >&2
|
|
exit 1
|
|
fi
|
|
if [[ -z "${PSQL_BIN}" || ! -x "${PSQL_BIN}" ]]; then
|
|
echo "psql is required." >&2
|
|
exit 1
|
|
fi
|
|
|
|
export PGPASSWORD="${DB_PASSWORD}"
|
|
server_version_num="$("${PSQL_BIN}" -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" -X -Atqc 'SHOW server_version_num')"
|
|
client_version="$("${PG_DUMP_BIN}" --version | sed -E 's/.*PostgreSQL\)?[[:space:]]+([0-9]+).*/\1/')"
|
|
server_major="${server_version_num:0:${#server_version_num}-4}"
|
|
|
|
if [[ -z "${server_major}" || -z "${client_version}" || "${server_major}" != "${client_version}" ]]; then
|
|
echo "pg_dump major version mismatch: server=${server_major:-unknown}, client=${client_version:-unknown}" >&2
|
|
exit 1
|
|
fi
|
|
|
|
mkdir -p "${BACKUP_DIR}"
|
|
timestamp="$(date +%Y%m%d_%H%M%S)"
|
|
output_file="${BACKUP_DIR}/${FILE_PREFIX}_${DB_NAME}_${timestamp}.dump"
|
|
temporary_file="${output_file}.tmp"
|
|
|
|
cleanup() { rm -f "${temporary_file}"; }
|
|
trap cleanup EXIT
|
|
|
|
"${PG_DUMP_BIN}" -h "${DB_HOST}" -p "${DB_PORT}" -U "${DB_USER}" -d "${DB_NAME}" \
|
|
--format=custom --no-owner --no-privileges > "${temporary_file}"
|
|
|
|
if [[ ! -s "${temporary_file}" ]]; then
|
|
echo "Backup failed: dump file is empty." >&2
|
|
exit 1
|
|
fi
|
|
|
|
mv -f "${temporary_file}" "${output_file}"
|
|
trap - EXIT
|
|
|
|
find "${BACKUP_DIR}" -maxdepth 1 -type f -name "${FILE_PREFIX}_${DB_NAME}_*.dump" \
|
|
-printf '%T@ %p\n' | sort -nr | tail -n +21 | cut -d' ' -f2- | xargs -r rm -f
|
|
|
|
printf '%s\n' "Backup created: ${output_file}"
|