#!/bin/bash
# deploy-admin-from-artifact.sh -- Server-side Deploy fuer rebreak-admin-staging.
#
# Wird via SSH von .github/workflows/deploy-admin-staging.yml aufgerufen.
# Erwartet: /srv/rebreak/apps/admin/.output-incoming.tar.gz (via scp vom GA-Runner).
#
# Kein Build-Schritt (laeuft auf GA-Runner), kein prisma-migrate (admin hat kein DB-Schema).
# Atomic mv Pattern identisch zu deploy-from-artifact.sh.

set -euo pipefail

REPO_ROOT="/srv/rebreak"
ADMIN_DIR="${REPO_ROOT}/apps/admin"
ARTIFACT="${ADMIN_DIR}/.output-incoming.tar.gz"
PM2_BIN="/root/.nvm/versions/node/v24.11.1/bin/pm2"

log() { echo "[deploy-admin] $(date '+%H:%M:%S') $*"; }
log_err() { echo "[deploy-admin:err] $(date '+%H:%M:%S') $*" >&2; }

log "=== Rebreak Admin Deploy-from-Artifact gestartet ==="

export PATH="/root/.nvm/versions/node/v24.11.1/bin:$PATH"

# 0. Sanity-Check: Artifact muss da sein
[[ -f "$ARTIFACT" ]] || { log_err "Artifact $ARTIFACT fehlt -- abort"; exit 1; }

# 1. Ziel-Verzeichnis sicherstellen
mkdir -p "${ADMIN_DIR}"

# 2. Artifact extrahieren -- atomisches mv
log "Step 1: Artifact extrahieren..."
rm -rf "${ADMIN_DIR}/.output-staging-new"
mkdir -p "${ADMIN_DIR}/.output-staging-new"
tar xzf "$ARTIFACT" -C "${ADMIN_DIR}/.output-staging-new"

# Sanity-Check: Nuxt-SSR-Server muss vorhanden sein
[[ -f "${ADMIN_DIR}/.output-staging-new/server/index.mjs" ]] || {
  log_err "Ungueltiges Artifact -- server/index.mjs fehlt"
  rm -rf "${ADMIN_DIR}/.output-staging-new"
  exit 1
}

rm -rf "${ADMIN_DIR}/.output-staging"
mv "${ADMIN_DIR}/.output-staging-new" "${ADMIN_DIR}/.output-staging"
rm -f "$ARTIFACT"
log ".output-staging aktualisiert"

# 3. pm2 restart (oder erstmaliger Start via ecosystem)
log "Step 2: pm2 restart rebreak-admin-staging..."
"${PM2_BIN}" restart rebreak-admin-staging --update-env 2>/dev/null || \
  "${PM2_BIN}" start "${REPO_ROOT}/ecosystem.config.js" --only rebreak-admin-staging

log "rebreak-admin-staging restarted"

# 4. pm2 save
"${PM2_BIN}" save 2>/dev/null || true

log "=== Admin Deploy erfolgreich ==="
