#!/bin/bash
# deploy-marketing.sh -- Local-Build + rsync der Marketing-SPA nach staging.rebreak.org
#
# Pattern: Nuxt generate -> .output/public/ -> rsync auf Hetzner -> /var/www/marketing-staging
#
# Usage:
#   ./scripts/deploy-marketing.sh           # build + deploy staging
#   DRY_RUN=1 ./scripts/deploy-marketing.sh # nur rsync-dry-run, kein write
#
# Voraussetzungen auf Server (einmalig):
#   sudo mkdir -p /var/www/marketing-staging
#   sudo chown -R $USER:www-data /var/www/marketing-staging
#   sudo cp ops/nginx/staging.rebreak.org.conf /etc/nginx/sites-available/
#   sudo nginx -t && sudo systemctl reload nginx

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
MARKETING_DIR="$REPO_ROOT/apps/marketing"

# Server-Settings (anpassen wenn anderer Host/User)
# 2026-06-06: Default auf Clone (91.99.225.223) umgestellt -- ALT-Box 49.13.55.22 ist migriert/abgeschaltet
SSH_HOST="${MARKETING_SSH_HOST:-root@91.99.225.223}"
REMOTE_DIR="${MARKETING_REMOTE_DIR:-/var/www/marketing-staging}"

log() { echo "[deploy-marketing] $(date '+%H:%M:%S') $*"; }

log "=== Marketing Deploy gestartet ==="
log "Repo:    $REPO_ROOT"
log "Source:  $MARKETING_DIR"
log "Target:  $SSH_HOST:$REMOTE_DIR"

# 1. Build (statische Generierung)
log "Step 1: nuxt generate..."
cd "$MARKETING_DIR"
pnpm install --frozen-lockfile
pnpm generate

PUBLIC_DIR="$MARKETING_DIR/.output/public"
[[ -d "$PUBLIC_DIR" ]] || {
    echo "FEHLER: $PUBLIC_DIR existiert nicht nach generate" >&2
    exit 1
}
[[ -f "$PUBLIC_DIR/index.html" ]] || {
    echo "FEHLER: $PUBLIC_DIR/index.html fehlt" >&2
    exit 1
}

log "Build ok ($(du -sh "$PUBLIC_DIR" | cut -f1))"

# 2. rsync nach Server
# --progress statt --info=progress2: macOS' System-rsync (2.6.9 / openrsync)
# kennt --info nicht. --progress läuft auf alt + neu.
RSYNC_FLAGS=(-az --delete --progress)
if [[ "${DRY_RUN:-0}" == "1" ]]; then
    RSYNC_FLAGS+=(--dry-run)
    log "DRY_RUN aktiv -- nur Simulation"
fi

log "Step 2: rsync nach $SSH_HOST:$REMOTE_DIR ..."
SSH_KEY="${MARKETING_SSH_KEY:-$HOME/.ssh/id_ed25519}"
rsync "${RSYNC_FLAGS[@]}" \
    -e "ssh -i $SSH_KEY" \
    "$PUBLIC_DIR/" \
    "$SSH_HOST:$REMOTE_DIR/"

log "=== Marketing Deploy erfolgreich ==="
log "Test: curl -I https://staging.rebreak.org/"
