#!/usr/bin/env bash
# Backup the Bousla database (custom format, verified, retention-trimmed).
# Usage: bash scripts/backup.sh [backup_dir]
# Env (or defaults): PGHOST/PGPORT/PGDATABASE/PGUSER/PGPASSWORD — read from apps/api/.env when unset.
# Produces: <dir>/bousla_ops-YYYYMMDD-HHMMSS.dump + .sha256
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
BACKUP_DIR="${1:-$ROOT/backups}"
mkdir -p "$BACKUP_DIR"

# Load DB settings from the API env file when not provided by the caller
if [ -z "${PGPASSWORD:-}" ] && [ -f "$ROOT/apps/api/.env" ]; then
  while IFS='=' read -r k v; do
    case "$k" in
      PGHOST|PGPORT|PGDATABASE|PGUSER|PGPASSWORD) export "$k=$v" ;;
    esac
  done < <(grep -E '^(PGHOST|PGPORT|PGDATABASE|PGUSER|PGPASSWORD)=' "$ROOT/apps/api/.env" || true)
fi
: "${PGHOST:=127.0.0.1}" "${PGPORT:=5433}" "${PGDATABASE:=bousla_ops}" "${PGUSER:=bousla_app}"
export PGHOST PGPORT PGDATABASE PGUSER

STAMP="$(date +%Y%m%d-%H%M%S)"
OUT="$BACKUP_DIR/bousla_ops-$STAMP.dump"
LOG="$BACKUP_DIR/backup.log"

echo "[$(date '+%F %T')] dumping ${PGDATABASE}@${PGHOST}:${PGPORT} -> $OUT" | tee -a "$LOG"

# Dump WITHOUT credentials on the command line (PGPASSWORD env is used by pg_dump)
if ! pg_dump -Fc -f "$OUT" 2>>"$LOG"; then
  echo "BACKUP FAILED — see $LOG" >&2
  rm -f "$OUT"
  exit 1
fi

# Verify the archive is readable and count objects as an integrity smoke check
VERIFY="$(pg_restore -l "$OUT" 2>/dev/null | wc -l)"
if [ "$VERIFY" -lt 30 ]; then
  echo "BACKUP SUSPECT: only $VERIFY catalog entries — refusing to trust $OUT" >&2
  exit 1
fi

sha256sum "$OUT" > "$OUT.sha256"
echo "[$(date '+%F %T')] OK ($VERIFY catalog entries, $(du -h "$OUT" | cut -f1)) — checksum written" | tee -a "$LOG"

# Retention: keep the newest 30 dumps (the rest are pruned)
ls -1t "$BACKUP_DIR"/bousla_ops-*.dump 2>/dev/null | tail -n +31 | while read -r old; do
  rm -f "$old" "$old.sha256"
  echo "[$(date '+%F %T')] pruned $(basename "$old")" | tee -a "$LOG"
done
