#!/usr/bin/env bash
# wakelai-restore — restore the wakelai.com platform from a backup bundle
# produced by wakelai-backup.sh. Safe to run on a fresh server after the code
# has been cloned from GitHub. See DISASTER_RECOVERY.md for the full runbook.
#
# Usage:
#   wakelai-restore.sh <bundle.tar.gz>            restore everything in the bundle
#   wakelai-restore.sh <bundle.tar.gz> --db-only  restore only the database
#   wakelai-restore.sh <bundle.tar.gz> --dry-run  show what it would do
#
# By design this does NOT auto-start containers or overwrite a live database
# without asking — it restores files/DB/volumes and prints the remaining steps.
set -euo pipefail

REPO="/home/ashraffarid2010/wakelai.com"
PG_CONTAINER="wakelaicom-postgres"
PG_USER="wakelai"
PG_DB="wakelai"
PG_HOST="127.0.0.1"
PG_PORT="55433"

BUNDLE="${1:-}"; MODE="all"; DRY=0
[[ -z "$BUNDLE" || ! -f "$BUNDLE" ]] && { echo "usage: $0 <bundle.tar.gz> [--db-only|--dry-run]"; exit 2; }
shift || true
for a in "$@"; do case "$a" in --db-only) MODE="db";; --dry-run) DRY=1;; esac; done

run() { echo "+ $*"; [[ "$DRY" == "1" ]] || "$@"; }
say() { echo -e "\n\033[1;36m== $* ==\033[0m"; }

WORK="$(mktemp -d)"; trap 'rm -rf "$WORK"' EXIT
say "extracting bundle"
tar -C "$WORK" -xzf "$BUNDLE"
SRC="$(find "$WORK" -maxdepth 1 -type d -name 'wakelai-*' | head -1)"
[[ -z "$SRC" ]] && { echo "ERROR: unexpected bundle layout"; exit 1; }
echo "bundle contents: $SRC"; cat "$SRC/meta/manifest.txt" 2>/dev/null || true

# ---- database ---------------------------------------------------------------
say "restore database"
if [[ -f "$SRC/db/$PG_DB.sql.gz" ]]; then
  if ! docker inspect "$PG_CONTAINER" >/dev/null 2>&1; then
    echo "postgres container '$PG_CONTAINER' not running. Start it first, e.g.:"
    echo "  docker run -d --name $PG_CONTAINER --restart unless-stopped --network host \\"
    echo "    -e POSTGRES_DB=$PG_DB -e POSTGRES_USER=$PG_USER -e POSTGRES_PASSWORD=<pw> \\"
    echo "    -v wakelaicom_postgres-local-data:/var/lib/postgresql/data \\"
    echo "    postgres:16-alpine postgres -c listen_addresses=127.0.0.1 -p 55433"
    [[ "$DRY" == "1" ]] || { echo "aborting DB restore until container exists"; }
  else
    echo "restoring dump into $PG_CONTAINER:$PG_DB (existing data will be replaced)"
    if [[ "$DRY" == "0" ]]; then
      gunzip -c "$SRC/db/$PG_DB.sql.gz" | docker exec -i "$PG_CONTAINER" psql -U "$PG_USER" -d "$PG_DB" -h "$PG_HOST" -p "$PG_PORT" >/dev/null
      echo "DB restored. Row check:"
      docker exec "$PG_CONTAINER" psql -U "$PG_USER" -d "$PG_DB" -h "$PG_HOST" -p "$PG_PORT" -Atc 'select count(*) from users'
    fi
  fi
else
  echo "no DB dump in bundle — skipping"
fi
[[ "$MODE" == "db" ]] && { say "db-only done"; exit 0; }

# ---- config + secrets -------------------------------------------------------
say "restore config + secrets -> $REPO"
if [[ -d "$SRC/config" ]]; then
  ( cd "$SRC/config" && find . -type f -print0 | while IFS= read -r -d '' f; do
      run mkdir -p "$REPO/$(dirname "$f")"; run cp -a "$f" "$REPO/$f"
    done )
fi

# ---- runtime modules --------------------------------------------------------
say "restore .runtime modules"
[[ -f "$SRC/runtime/runtime.tar.gz" ]] && run tar -C "$REPO" -xzf "$SRC/runtime/runtime.tar.gz"

# ---- nginx vhosts -----------------------------------------------------------
say "restore nginx vhosts"
if [[ -d "$SRC/nginx" ]]; then
  for f in "$SRC/nginx"/*.conf; do [[ -e "$f" ]] || continue
    bn="$(basename "$f")"; [[ "$bn" == "nginx.conf" ]] && continue
    run cp -a "$f" "/etc/nginx/conf.d/$bn"
  done
  echo "nginx main config preserved at $SRC/nginx/nginx.conf (review before overwriting /etc/nginx/nginx.conf)"
  [[ "$DRY" == "0" ]] && nginx -t 2>&1 | tail -3 || true
fi

# ---- volumes (full bundles) -------------------------------------------------
say "restore Hermes / data volumes"
if [[ -d "$SRC/volumes" ]]; then
  for arc in "$SRC/volumes"/*.tar.gz; do [[ -e "$arc" ]] || continue
    vol="$(basename "$arc" .tar.gz)"
    run docker volume create "$vol" >/dev/null
    run docker run --rm -v "$vol":/dst -v "$SRC/volumes":/src:ro alpine \
        sh -c "rm -rf /dst/* && tar -C /dst -xzf /src/$(basename "$arc")"
    echo "restored volume: $vol"
  done
else
  echo "no volumes in this bundle (core backup) — agent memories come from a --full bundle"
fi

# ---- ops tooling ------------------------------------------------------------
say "ops tooling (systemd units + scripts) available at: $SRC/ops"
echo "install with: cp $SRC/ops/systemd/* /etc/systemd/system/ && cp $SRC/ops/*.sh /usr/local/bin/ && systemctl daemon-reload"

cat <<EOF

$([ "$DRY" = 1 ] && echo "[DRY-RUN — nothing was changed]")
== remaining manual steps ==
  1. cd $REPO && npm ci && NEXT_DIST_DIR=.next node node_modules/next/dist/bin/next build
  2. systemctl restart wakelai-nextjs.service && curl -sI http://127.0.0.1:9100/
  3. re-provision per-tenant containers from .runtime compose files as needed
  4. reload nginx: nginx -t && nginx -s reload
Restore complete.
EOF
