#!/bin/bash
# /mnt/backup-usb/runbooks/promote-backup-server.sh

set -Eeuo pipefail

BACKUP_MOUNT="${BACKUP_MOUNT:-/mnt/backup-usb}"
BACKUP_LABEL="${BACKUP_LABEL:-BACKUP_USB}"
SNAPSHOT_NAME="${SNAPSHOT_NAME:-${1:-latest}}"
DRY_RUN="${DRY_RUN:-0}"
FILES_SOURCE=""
DB_DUMP_SOURCE=""

log() {
  printf '%s %s\n' "$(date -Iseconds)" "$1"
}

ensure_backup_mounted() {
  if findmnt -n "${BACKUP_MOUNT}" >/dev/null 2>&1; then
    return
  fi

  local dev
  dev="$(blkid -L "${BACKUP_LABEL}" || true)"
  if [ -z "${dev}" ]; then
    log "ERROR: Could not locate backup volume label ${BACKUP_LABEL}."
    exit 1
  fi

  mkdir -p "${BACKUP_MOUNT}"
  mount "${dev}" "${BACKUP_MOUNT}"
  log "Mounted ${dev} at ${BACKUP_MOUNT}"
}

resolve_sources() {
  local snapshot_root="${BACKUP_MOUNT}/snapshots"
  local db_root="${BACKUP_MOUNT}/database"

  if [ "${SNAPSHOT_NAME}" = "latest" ]; then
    FILES_SOURCE="${snapshot_root}/latest/files"
  else
    FILES_SOURCE="${snapshot_root}/${SNAPSHOT_NAME}/files"
  fi

  DB_DUMP_SOURCE="${db_root}/latest-all-databases.sql.gz"

  if [ ! -d "${FILES_SOURCE}" ]; then
    log "ERROR: Files source not found: ${FILES_SOURCE}"
    exit 1
  fi

  if [ ! -f "${DB_DUMP_SOURCE}" ]; then
    log "ERROR: Database dump not found: ${DB_DUMP_SOURCE}"
    exit 1
  fi
}

restore_files() {
  local rsync_args=(-aHAX --numeric-ids)
  if [ "${DRY_RUN}" = "1" ]; then
    rsync_args+=(--dry-run --itemize-changes)
    log "DRY_RUN enabled: filesystem restore will not write changes"
  fi

  log "Restoring filesystem payload from ${FILES_SOURCE}"
  rsync "${rsync_args[@]}" "${FILES_SOURCE}/" /
}

restore_database() {
  if ! command -v mysql >/dev/null 2>&1; then
    log "WARNING: mysql client missing, skipping DB restore."
    return
  fi

  if [ "${DRY_RUN}" = "1" ]; then
    log "DRY_RUN enabled: skipping MariaDB import"
    return
  fi

  log "Importing MariaDB dump ${DB_DUMP_SOURCE}"
  systemctl start mariadb
  gunzip -c "${DB_DUMP_SOURCE}" | mysql
}

restart_services() {
  if [ "${DRY_RUN}" = "1" ]; then
    log "DRY_RUN enabled: skipping service restarts"
    return
  fi

  log "Restarting core services"
  systemctl daemon-reload
  systemctl restart mariadb
  systemctl restart php8.3-fpm
  nginx -t
  systemctl restart nginx
}

post_checks() {
  log "Service health checks"
  systemctl is-active mariadb || true
  systemctl is-active php8.3-fpm || true
  systemctl is-active nginx || true

  log "HTTP check"
  curl -k -I https://127.0.0.1 || true

  if [ "${DRY_RUN}" = "1" ]; then
    log "DRY_RUN complete: no changes were applied"
  else
    log "Recovery run complete"
    log "Next step: repoint DNS/public IP to this host and validate external HTTPS."
  fi
}

main() {
  if [ "$(id -u)" -ne 0 ]; then
    log "ERROR: run as root"
    exit 1
  fi

  ensure_backup_mounted
  resolve_sources
  restore_files
  restore_database
  restart_services
  post_checks
}

main "$@"
