#!/usr/bin/env bash
# Runs on the production server (docs/deploy/reliable-deploys.md).
#
#   activate-release.sh <release.tgz> <release-id>    deploy a release built on GitHub
#   activate-release.sh --rollback [<release-id>]     switch back (default: the one before current)
#   activate-release.sh --list                        show the releases on this server
#
# Nothing is compiled here. A deploy unpacks a release built on GitHub into its
# own folder, migrates the database, points `current` at it, restarts pm2 and
# checks health. If the new release is not healthy, it switches straight back
# to the previous one. The old release is never touched while the new one is
# prepared, so a failure at any step leaves the running API as it was.
set -euo pipefail

APP_DIR="${APP_DIR:-/home/ubuntu/hostelcare-app}"
# The original checkout. It keeps the one `.env` the owner edits, and its dist/
# is the fallback for the very first switch to release folders.
SHARED_DIR="${SHARED_DIR:-/home/ubuntu/hostelcare-backend}"
PM2="${PM2:-sudo pm2}"
APP_NAME="${APP_NAME:-hostelcare-api}"
HEALTH_URL="${HEALTH_URL:-http://localhost:3003/api/health}"
HEALTH_TRIES="${HEALTH_TRIES:-15}"
KEEP="${KEEP:-5}"
MIN_DISK_MB="${MIN_DISK_MB:-1024}"
MIN_MEM_MB="${MIN_MEM_MB:-200}"
# pending: back up only when migrations are about to run (default);
# always: before every deploy; never: skip (not recommended).
BACKUP_ON_DEPLOY="${BACKUP_ON_DEPLOY:-pending}"

RELEASES="$APP_DIR/releases"
CURRENT="$APP_DIR/current"
FAILED="$APP_DIR/failed"

log() { printf '▶ %s\n' "$*"; }
fail() { summary result "failed: $*"; printf '❌ %s\n' "$*" >&2; exit 1; }
# One "SUMMARY|key|value" line per fact; the workflow turns them into the run's
# summary table.
summary() { printf 'SUMMARY|%s|%s\n' "$1" "$2"; }

precheck() {
  local disk mem
  disk=$(df -Pm "$APP_DIR" | awk 'NR==2 {print $4}')
  [ "${disk:-0}" -ge "$MIN_DISK_MB" ] || fail "Only ${disk} MB free on disk; need ${MIN_DISK_MB} MB."
  if [ -r /proc/meminfo ]; then
    mem=$(awk '/MemAvailable/ {a=$2} /SwapFree/ {s=$2} END {print int((a+s)/1024)}' /proc/meminfo)
    [ "${mem:-0}" -ge "$MIN_MEM_MB" ] || fail "Only ${mem} MB of memory free; need ${MIN_MEM_MB} MB."
    log "Disk ${disk} MB free, memory ${mem} MB available."
  fi
  summary "disk free before" "${disk} MB"
}

# The release is built for the Node major in its .nvmrc. A mismatch rarely
# breaks anything, so it's a warning, not a stop.
check_node() {
  local rel="$1" want have
  want="$(tr -dc '0-9' < "$rel/.nvmrc" 2>/dev/null || true)"
  have="$(node -v 2>/dev/null | sed -E 's/^v([0-9]+).*/\1/')"
  if [ -n "$want" ] && [ "$want" != "$have" ]; then
    log "⚠️ The release was built for Node $want; this server runs Node ${have:-unknown}."
    summary "node" "⚠️ built for $want, server runs ${have:-unknown}"
  fi
}

# Before migrating: a clear message if the database can't be reached at all.
check_database() {
  local rel="$1"
  (cd "$rel" && echo 'SELECT 1' | ./node_modules/.bin/prisma db execute --stdin --schema prisma/schema.prisma >/dev/null 2>&1)
}

# A backup before the schema changes. Ordinary deploys (nothing to migrate)
# skip it and stay quick; the nightly backup covers the rest.
backup_before_migrating() {
  local rel="$1" id="$2" status rc=0
  case "$BACKUP_ON_DEPLOY" in
    never) summary backup "skipped (BACKUP_ON_DEPLOY=never)"; return 0 ;;
    always) ;;
    *)
      status="$(cd "$rel" && ./node_modules/.bin/prisma migrate status 2>&1 || true)"
      if printf '%s' "$status" | grep -q "Database schema is up to date"; then
        summary backup "skipped: no migrations pending"
        return 0
      fi ;;
  esac
  ENV_FILE="$SHARED_DIR/.env" bash "$rel/scripts/deploy/backup-db.sh" "before-$id" || rc=$?
  case "$rc" in
    0) return 0 ;;
    3) log "⚠️ Backed up on this server, but the copy to S3 failed; the deploy carries on." ;;
    *) return 1 ;;
  esac
}

# Uploads a failed run left behind in /tmp.
clean_tmp() {
  find /tmp -maxdepth 1 \( -name 'hostelcare-release-*.tgz' -o -name 'hostelcare-activate-*.sh' \) -mmin +60 -delete 2>/dev/null || true
}

# pm2's own logs grow without limit; on a small server they fill the disk.
# Installed once; later deploys see it and do nothing.
ensure_logrotate() {
  if $PM2 jlist 2>/dev/null | grep -q '"name":"pm2-logrotate"'; then return 0; fi
  log "Setting up pm2 log rotation (one-time)."
  if $PM2 install pm2-logrotate >/dev/null 2>&1; then
    $PM2 set pm2-logrotate:max_size 20M >/dev/null 2>&1 || true
    $PM2 set pm2-logrotate:retain 14 >/dev/null 2>&1 || true
    $PM2 set pm2-logrotate:compress true >/dev/null 2>&1 || true
    summary "log rotation" "set up: 20 MB per file, 14 kept, compressed"
  else
    log "⚠️ Could not install pm2-logrotate; the deploy carries on."
    summary "log rotation" "⚠️ not installed"
  fi
}

# Every release reads the same settings, so editing .env keeps working as before.
link_shared() {
  local rel="$1" value
  [ -f "$SHARED_DIR/.env" ] || fail "No $SHARED_DIR/.env to link."
  ln -sfn "$SHARED_DIR/.env" "$rel/.env"
  # A relative Firebase key path was relative to the old checkout.
  value=$(grep -E '^FIREBASE_SERVICE_ACCOUNT_FILE=' "$SHARED_DIR/.env" | tail -n1 | cut -d= -f2- | tr -d "\"'" || true)
  if [ -n "$value" ] && [ "${value#/}" = "$value" ] && [ -f "$SHARED_DIR/$value" ]; then
    mkdir -p "$rel/$(dirname "$value")"
    ln -sfn "$SHARED_DIR/$value" "$rel/$value"
  fi
}

# Atomic on Linux (rename over the old link); plain replace elsewhere.
point_current_at() {
  ln -sfn "$1" "$APP_DIR/current.next"
  mv -Tf "$APP_DIR/current.next" "$CURRENT" 2>/dev/null || { rm -f "$APP_DIR/current.next"; ln -sfn "$1" "$CURRENT"; }
}

running_script() {
  $PM2 jlist 2>/dev/null | node -e '
    let s = ""; process.stdin.on("data", (d) => (s += d)).on("end", () => {
      try {
        const p = JSON.parse(s).find((x) => x.name === process.argv[1]);
        process.stdout.write(p ? p.pm2_env.pm_exec_path : "");
      } catch { process.stdout.write(""); }
    });' "$APP_NAME"
}

restart_app() {
  if [ "$(running_script)" = "$CURRENT/dist/server.js" ]; then
    # `current` is resolved again on restart, so this starts the new release.
    $PM2 restart "$APP_NAME" --update-env >/dev/null
  else
    # First run with release folders: move pm2 from the old checkout to `current`.
    log "Moving pm2 to $CURRENT (one-time)."
    $PM2 delete "$APP_NAME" >/dev/null 2>&1 || true
    APP_DIR="$APP_DIR" $PM2 start "$CURRENT/ecosystem.config.js" >/dev/null
  fi
}

# Up, reaching the database, and (when given) running the expected commit, so
# another process on the port can't pass for the new release.
healthy() {
  local want="${1:-}" i body
  for i in $(seq 1 "$HEALTH_TRIES"); do
    body="$(curl -fsS "$HEALTH_URL" 2>/dev/null || true)"
    if [ -n "$body" ] && { [ -z "$want" ] || printf '%s' "$body" | grep -q "\"revision\":\"$want\""; } \
      && curl -fsS "$HEALTH_URL/db" >/dev/null 2>&1; then
      return 0
    fi
    sleep 2
  done
  return 1
}

# Back to the old checkout's dist/, for a failure on the very first switch.
restore_old_checkout() {
  log "Restoring pm2 to the old checkout at $SHARED_DIR."
  $PM2 delete "$APP_NAME" >/dev/null 2>&1 || true
  $PM2 start "$SHARED_DIR/dist/server.js" --name "$APP_NAME" --cwd "$SHARED_DIR" >/dev/null
}

# Releases, newest first. Names start with a UTC timestamp, so name order is
# deploy order (folder dates change when a release is unpacked or copied).
releases_newest_first() {
  { ls -1d "$RELEASES"/*/ 2>/dev/null || true; } | sed 's#/$##' | sort -r
}

prune() {
  local keep_now
  keep_now="$(readlink "$CURRENT" || true)"
  # Newest first; keep $KEEP, and never the one `current` points at.
  releases_newest_first | tail -n +"$((KEEP + 1))" | while read -r old; do
    [ "$old" = "$keep_now" ] || rm -rf "$old"
  done
}

# Out of releases/, so a later rollback or clean-up never picks it. The last
# failed release stays in failed/ for a look.
park_failed() {
  mkdir -p "$FAILED"
  rm -rf "${FAILED:?}"/*
  mv "$1" "$FAILED/"
}

deploy() {
  local tarball="$1" id="$2" rel prev rev out applied started="$SECONDS"
  [ -f "$tarball" ] || fail "No release file at $tarball."
  mkdir -p "$RELEASES"
  precheck
  rel="$RELEASES/$id"
  [ ! -e "$rel" ] || fail "Release $id is already on this server."
  prev="$(readlink "$CURRENT" || true)"

  summary "release" "$id"
  summary "previous" "$( [ -n "$prev" ] && basename "$prev" || echo "the old checkout")"
  clean_tmp

  log "Unpacking $id."
  mkdir -p "$rel"
  tar -xzf "$tarball" -C "$rel"
  rm -f "$tarball"
  link_shared "$rel"
  check_node "$rel"
  rev="$(cut -c1-7 "$rel/REVISION" 2>/dev/null || true)"
  summary "revision" "${rev:-unknown}"

  if ! check_database "$rel"; then
    park_failed "$rel"
    fail "The database can't be reached; nothing was changed. Check DATABASE_URL in $SHARED_DIR/.env and the database itself."
  fi

  if ! backup_before_migrating "$rel" "$id"; then
    park_failed "$rel"
    fail "The backup before migrating failed; nothing was changed."
  fi

  # Before the switch: if a migration fails, the running release is untouched.
  log "Migrating the database."
  out="$(mktemp)"
  if ! (cd "$rel" && ./node_modules/.bin/prisma migrate deploy) 2>&1 | tee "$out"; then
    summary "migrations" "failed (see the log)"
    rm -f "$out"
    park_failed "$rel"
    fail "A migration failed; nothing was switched and the running release is untouched. Fix the migration, then clear Prisma's record of it: cd $FAILED/$id && ./node_modules/.bin/prisma migrate resolve --rolled-back <migration_name>"
  fi
  applied="$(sed -nE 's/.*Applying migration `([^`]+)`.*/\1/p' "$out" | paste -sd ' ' - || true)"
  rm -f "$out"
  summary "migrations" "${applied:-none pending}"

  log "Switching to $id (was: ${prev:-the old checkout})."
  point_current_at "$rel"
  restart_app

  if healthy "$rev"; then
    log "✅ $id is healthy (revision ${rev:-unknown}, $((SECONDS - started)) s)."
    $PM2 save >/dev/null
    prune
    ensure_logrotate
    summary "health" "ok: up, database reachable, serving ${rev:-unknown}"
    summary "result" "deployed in $((SECONDS - started)) s"
    return 0
  fi

  printf '❌ %s is not healthy. Recent logs:\n' "$id" >&2
  $PM2 logs "$APP_NAME" --lines 40 --nostream 2>&1 | tail -n 40 >&2 || true
  summary "health" "❌ not healthy after the switch"
  park_failed "$rel"
  if [ -n "$prev" ]; then
    log "Rolling back to $(basename "$prev")."
    point_current_at "$prev"
    restart_app
  else
    rm -f "$CURRENT"
    restore_old_checkout
  fi
  if healthy; then
    $PM2 save >/dev/null
    summary "rolled back to" "$( [ -n "$prev" ] && basename "$prev" || echo "the old checkout") (healthy)"
    fail "Deploy failed; the previous version is back and healthy. Migrations already applied stay applied."
  fi
  fail "Deploy failed and the previous version is not healthy either. Check: $PM2 logs $APP_NAME"
}

rollback() {
  local want="${1:-}" target now
  now="$(readlink "$CURRENT" || true)"
  [ -n "$now" ] || fail "No release is active yet; nothing to roll back to."
  if [ -n "$want" ]; then
    target="$RELEASES/$want"
  else
    # The release deployed before the current one.
    target="$(releases_newest_first | awk -v now="$now" '$0 < now' | head -n1)"
  fi
  [ -n "$target" ] && [ -d "$target" ] || fail "No release to roll back to (asked for: ${want:-the previous one})."
  [ "$target" != "$now" ] || fail "$(basename "$target") is already running."
  log "Switching back to $(basename "$target") (was $(basename "$now"))."
  point_current_at "$target"
  restart_app
  if healthy; then
    $PM2 save >/dev/null
    log "✅ Now running $(basename "$target")."
    summary "rolled back to" "$(basename "$target")"
    summary "was" "$(basename "$now")"
    summary "result" "rollback done"
    return 0
  fi
  log "$(basename "$target") is not healthy; returning to $(basename "$now")."
  point_current_at "$now"
  restart_app
  healthy || fail "Neither release is healthy. Check: $PM2 logs $APP_NAME"
  fail "Rollback to $(basename "$target") failed; still running $(basename "$now")."
}

list() {
  local now
  now="$(readlink "$CURRENT" || true)"
  releases_newest_first | while read -r r; do
    printf '%s %s  %s\n' "$([ "$r" = "$now" ] && echo '*' || echo ' ')" "$(basename "$r")" "$(cat "$r/REVISION" 2>/dev/null)"
  done
}

case "${1:-}" in
  --rollback) rollback "${2:-}" ;;
  --list) list ;;
  ""|-h|--help) sed -n '2,12p' "$0" ;;
  *) [ $# -eq 2 ] || fail "Usage: $0 <release.tgz> <release-id>"; deploy "$1" "$2" ;;
esac
