#!/usr/bin/env bash
# Backs up the HostelCare database (docs/deploy/reliable-deploys.md, Phase 3).
#
#   backup-db.sh [label]          dump, check it reads back, keep the newest $KEEP_BACKUPS here,
#                                 and copy it to S3 (s3://eia-postgres-backups/hostelcare)
#   backup-db.sh --check [file]   restore a dump (default: the newest) into a scratch database,
#                                 count what came back, then drop the scratch database
#   backup-db.sh --list           the dumps on this server
#   backup-db.sh --install-cron   add the nightly backup to this user's crontab (once)
#
# The database runs on this server, so a dump kept only here is lost with the
# server: every dump is also copied to S3 with the app's AWS keys from .env.
# BACKUP_S3_URI in .env overrides the location. Exit codes: 0 done, 3 dumped
# here but the S3 copy failed, anything else failed.
set -euo pipefail

HERE="$(cd "$(dirname "$0")" && pwd)"
REL="$(cd "$HERE/../.." && pwd)"
ENV_FILE="${ENV_FILE:-/home/ubuntu/hostelcare-backend/.env}"
BACKUP_DIR="${BACKUP_DIR:-/home/ubuntu/hostelcare-app/hostelcare-backups}"
DEFAULT_S3_URI="s3://eia-postgres-backups/hostelcare"
KEEP_BACKUPS="${KEEP_BACKUPS:-5}"
APP_DIR="${APP_DIR:-/home/ubuntu/hostelcare-app}"
# For --check only: creates and drops the scratch database.
PG_ADMIN="${PG_ADMIN-sudo -u postgres}"
SCRATCH_DB="${SCRATCH_DB:-hostelcare_restore_check}"

log() { printf '▶ %s\n' "$*"; }
summary() { printf 'SUMMARY|%s|%s\n' "$1" "$2"; }
fail() { summary backup "❌ $*"; printf '❌ %s\n' "$*" >&2; exit 1; }

# Connection details from DATABASE_URL, plus the backup and AWS settings, read
# with dotenv rather than by sourcing .env, so its quoting can't break bash.
load_env() {
  [ -f "$ENV_FILE" ] || fail "No settings file at $ENV_FILE."
  local line key value
  while IFS=$'\t' read -r key value; do
    [ -n "$key" ] && export "$key=$value"
  done < <(NODE_PATH="$REL/node_modules" node -e '
    const env = require("dotenv").parse(require("fs").readFileSync(process.argv[1]));
    const out = (k, v) => v !== undefined && v !== "" && console.log(`${k}\t${String(v).replace(/[\t\n]/g, " ")}`);
    if (!env.DATABASE_URL) { console.error("DATABASE_URL is not set"); process.exit(1); }
    const u = new URL(env.DATABASE_URL);
    out("PGHOST", u.hostname); out("PGPORT", u.port || "5432");
    out("PGUSER", decodeURIComponent(u.username)); out("PGPASSWORD", decodeURIComponent(u.password));
    out("PGDATABASE", decodeURIComponent(u.pathname.slice(1)));
    out("DB_SCHEMA", u.searchParams.get("schema") || "public");
    for (const k of ["BACKUP_S3_URI", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_REGION"]) out(k, env[k]);
  ' "$ENV_FILE")
  [ -n "${PGDATABASE:-}" ] || fail "Could not read DATABASE_URL from $ENV_FILE."
}

newest_dump() { { ls -1 "$BACKUP_DIR"/hostelcare-*.dump 2>/dev/null || true; } | sort -r | head -n1; }

# Low CPU and disk priority, so the live API keeps its share of the server.
quietly() {
  if command -v ionice >/dev/null 2>&1; then nice -n 19 ionice -c3 "$@"; else nice -n 19 "$@"; fi
}

backup() {
  local label="${1:-manual}" name tmp last need avail size
  load_env
  label="$(printf '%s' "$label" | tr -c 'A-Za-z0-9._-' '-' | cut -c1-60)"
  mkdir -p "$BACKUP_DIR" && chmod 700 "$BACKUP_DIR"

  # Room for another dump: three times the last one, and at least 100 MB.
  last="$(newest_dump)"
  need=100
  if [ -n "$last" ]; then need=$(( $(du -m "$last" | cut -f1) * 3 )); [ "$need" -ge 100 ] || need=100; fi
  avail="$(df -Pm "$BACKUP_DIR" | awk 'NR==2 {print $4}')"
  [ "${avail:-0}" -ge "$need" ] || fail "Only ${avail} MB free in $BACKUP_DIR; a backup needs about ${need} MB."

  name="$BACKUP_DIR/hostelcare-$(date -u +%Y%m%d%H%M%S)-$label.dump"
  tmp="$name.partial"
  log "Backing up $PGDATABASE (schema $DB_SCHEMA)."
  if ! quietly pg_dump --format=custom --no-owner --no-privileges --schema="$DB_SCHEMA" --file="$tmp"; then
    rm -f "$tmp"
    fail "pg_dump failed; nothing was changed."
  fi
  # A dump that can't be listed back can't be restored either.
  if ! pg_restore --list "$tmp" >/dev/null 2>&1; then
    rm -f "$tmp"
    fail "The dump didn't read back; nothing was changed."
  fi
  mv "$tmp" "$name" && chmod 600 "$name"
  size="$(du -h "$name" | cut -f1)"
  log "Saved $(basename "$name") ($size)."
  summary backup "$(basename "$name") ($size)"

  { ls -1 "$BACKUP_DIR"/hostelcare-*.dump 2>/dev/null || true; } | sort -r | tail -n +"$((KEEP_BACKUPS + 1))" | while read -r old; do
    rm -f -- "$old"
  done

  local where target="${BACKUP_S3_URI:-$DEFAULT_S3_URI}"
  if [ "$target" = "none" ]; then
    log "⚠️ BACKUP_S3_URI=none, so this backup stays on this server only."
    summary "backup copy" "⚠️ on this server only (BACKUP_S3_URI=none)"
    return 0
  fi
  if where="$(NODE_PATH="$REL/node_modules" node "$HERE/upload-backup.mjs" "$name" "$target")"; then
    log "Copied to $where."
    summary "backup copy" "$where"
    return 0
  fi
  summary "backup copy" "⚠️ S3 upload failed; the backup is on this server"
  return 3
}

check() {
  local file="${1:-}" tables migrations
  load_env
  [ -n "$file" ] || file="$(newest_dump)"
  [ -n "$file" ] && [ -f "$file" ] || fail "No backup to check in $BACKUP_DIR."
  log "Restoring $(basename "$file") into the scratch database $SCRATCH_DB."
  $PG_ADMIN dropdb --if-exists "$SCRATCH_DB"
  $PG_ADMIN createdb "$SCRATCH_DB"
  # A new database already has an empty `public` schema, and a dump of
  # `public` starts by creating it, so drop it here first. Only the scratch
  # database is touched.
  $PG_ADMIN psql -q -v ON_ERROR_STOP=1 -d "$SCRATCH_DB" -c "DROP SCHEMA IF EXISTS \"$DB_SCHEMA\" CASCADE" >/dev/null
  # Read from stdin, so the postgres user needn't read files in this folder.
  if ! pg_restore --no-owner --no-privileges --exit-on-error -f - < "$file" | $PG_ADMIN psql -q -v ON_ERROR_STOP=1 -d "$SCRATCH_DB" >/dev/null; then
    $PG_ADMIN dropdb --if-exists "$SCRATCH_DB"
    fail "$(basename "$file") did not restore cleanly."
  fi
  tables="$($PG_ADMIN psql -Atc "select count(*) from information_schema.tables where table_schema = '$DB_SCHEMA'" -d "$SCRATCH_DB")"
  migrations="$($PG_ADMIN psql -Atc "select count(*) from \"$DB_SCHEMA\"._prisma_migrations where finished_at is not null" -d "$SCRATCH_DB" 2>/dev/null || echo "?")"
  $PG_ADMIN dropdb --if-exists "$SCRATCH_DB"
  log "✅ $(basename "$file") restores: $tables tables, $migrations migrations applied."
  summary "restore check" "$(basename "$file"): $tables tables, $migrations migrations"
}

list() {
  { ls -1 "$BACKUP_DIR"/hostelcare-*.dump 2>/dev/null || true; } | sort -r | while read -r f; do
    printf '%s  %s\n' "$(du -h "$f" | cut -f1)" "$(basename "$f")"
  done
}

# 21:30 UTC is 03:00 in India. Runs the script of whichever release is live.
install_cron() {
  local marker="# hostelcare-nightly-backup" line
  line="30 21 * * * ENV_FILE=$ENV_FILE BACKUP_DIR=$BACKUP_DIR bash $APP_DIR/current/scripts/deploy/backup-db.sh nightly >> $BACKUP_DIR/backup.log 2>&1 $marker"
  mkdir -p "$BACKUP_DIR" && chmod 700 "$BACKUP_DIR"
  if crontab -l 2>/dev/null | grep -qF "$marker"; then
    log "The nightly backup is already in crontab."
    return 0
  fi
  { crontab -l 2>/dev/null || true; echo "$line"; } | crontab -
  log "✅ Nightly backup added: every day at 21:30 UTC (03:00 IST), log in $BACKUP_DIR/backup.log."
}

case "${1:-}" in
  --check) check "${2:-}" ;;
  --list) list ;;
  --install-cron) install_cron ;;
  -h|--help) sed -n '2,16p' "$0" ;;
  *) backup "${1:-manual}" ;;
esac
