#!/usr/bin/env bash
# Back up Postgres DB "KVIEW" every run, keep last 8 files,
# and (via sudo) run pg_dump/psql as the 'postgres' user.
# Default backup dir: /home/adminkview/db.bak

set -euo pipefail
umask 077

DB_NAME="${DB_NAME:-kviewdb}"
BACKUP_DIR="${BACKUP_DIR:-/home/adminkview/db.bak}"
TIMESTAMP="$(date +'%Y-%m-%d_%H-%M-%S')"
BACKUP_FILE="${BACKUP_DIR}/${DB_NAME}_${TIMESTAMP}.dump"
PSQL_LOG="${BACKUP_DIR}/backup_kview.psql.log"

# Set to 1 to run commands via sudo -u postgres (recommended to avoid password prompts)
SUDO_POSTGRES="${SUDO_POSTGRES:-1}"

log() { printf '[%s] %s\n' "$(date -Iseconds)" "$*"; }
trap 'rc=$?; log "ERROR: backup failed (exit $rc)"; exit $rc' ERR

as_postgres() {
  if [[ "${SUDO_POSTGRES}" == "1" ]]; then
    sudo -H -u postgres "$@"
  else
    "$@"
  fi
}

# Ensure tools exist (we'll call them through sudo if needed)
command -v pg_dump >/dev/null || { echo "pg_dump not found. Install postgresql-client."; exit 1; }
command -v psql >/dev/null || { echo "psql not found. Install postgresql-client."; exit 1; }

mkdir -p "$BACKUP_DIR"

log "Starting backup of database '${DB_NAME}' to '${BACKUP_FILE}'"
as_postgres pg_dump -F c -Z 9 -d "$DB_NAME" -f "$BACKUP_FILE"
# Grab size for the log (works on GNU coreutils)
SIZE_BYTES="$(stat -c %s "$BACKUP_FILE" 2>/dev/null || wc -c <"$BACKUP_FILE")"
log "Backup complete: $(basename "$BACKUP_FILE") (${SIZE_BYTES} bytes)."

# Append a concise line from psql to show connectivity, user, and server version
# Example output (one line): backup_kview | 2025-10-13 00:00:01+02 | postgres | PostgreSQL 16.3 ...
as_postgres psql -Atqc "SELECT 'backup_kview', current_timestamp, current_user, version();" "$DB_NAME" \
  | sed 's/|/ | /g' >> "$PSQL_LOG" || log "WARNING: psql connectivity log failed."

# Keep the psql log reasonably small (last 2000 lines)
if [[ -f "$PSQL_LOG" ]]; then
  tmp="${PSQL_LOG}.tmp.$$"
  tail -n 2000 "$PSQL_LOG" > "$tmp" && mv "$tmp" "$PSQL_LOG"
fi

# Retention: keep only the 8 most recent dumps for this DB
if ls -1t "${BACKUP_DIR}/${DB_NAME}_"*.dump >/dev/null 2>&1; then
  ls -1t "${BACKUP_DIR}/${DB_NAME}_"*.dump | tail -n +9 | xargs -r rm --
  log "Retention: kept last 8 backups; older ones removed."
else
  log "Retention: no older backups to prune."
fi

log "All done."