#!/usr/bin/env bash
set -euo pipefail

# Cutover-Skript fuer kurzes Wartungsfenster.
# Auf QUELLSYSTEM ausfuehren:
# 1) stoppt lokale Hördle-App
# 2) finaler Delta-Sync data/ + uploads/
# 3) startet Ziel-App im Proxmox-LXC

TARGET_HOST="${TARGET_HOST:-root@10.0.0.19}"
TARGET_APP_DIR="${TARGET_APP_DIR:-/opt/hoerdle}"
SOURCE_APP_DIR="${SOURCE_APP_DIR:-$(pwd)}"
SOURCE_COMPOSE_FILE="${SOURCE_COMPOSE_FILE:-docker-compose.yml}"
TARGET_COMPOSE_FILE="${TARGET_COMPOSE_FILE:-docker-compose.yml}"
SSH_OPTS="${SSH_OPTS:-}"

cd "$SOURCE_APP_DIR"

require_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    echo "Fehlend: $1"
    exit 1
  fi
}

require_cmd docker
require_cmd rsync
require_cmd ssh
require_cmd sha256sum

echo "== Hördle Cutover =="
echo "Quelle: $(pwd)"
echo "Ziel: $TARGET_HOST:$TARGET_APP_DIR"
echo

echo "Wartungsfenster starten. Enter zum Fortfahren, Ctrl+C zum Abbruch."
read -r

echo "-- Quelle stoppen --"
docker compose -f "$SOURCE_COMPOSE_FILE" down
echo

echo "-- Finaler Delta-Sync data/ --"
rsync -aHAX --numeric-ids --delete \
  -e "ssh $SSH_OPTS" \
  "./data/" "$TARGET_HOST:$TARGET_APP_DIR/data/"
echo

echo "-- Finaler Delta-Sync public/uploads/ --"
rsync -aHAX --numeric-ids --delete \
  -e "ssh $SSH_OPTS" \
  "./public/uploads/" "$TARGET_HOST:$TARGET_APP_DIR/public/uploads/"
echo

if [ -f "./data/prod.db" ]; then
  echo "-- Konsistenzcheck DB --"
  LOCAL_HASH="$(sha256sum ./data/prod.db | awk '{print $1}')"
  REMOTE_HASH="$(ssh $SSH_OPTS "$TARGET_HOST" "sha256sum '$TARGET_APP_DIR/data/prod.db' | awk '{print \$1}'")"
  echo "local  prod.db sha256: $LOCAL_HASH"
  echo "remote prod.db sha256: $REMOTE_HASH"

  if [ "$LOCAL_HASH" != "$REMOTE_HASH" ]; then
    echo "DB Hash mismatch. Abbruch vor Start auf Ziel."
    exit 1
  fi
fi
echo

echo "-- Ziel-App starten --"
ssh $SSH_OPTS "$TARGET_HOST" "cd '$TARGET_APP_DIR' && docker compose -f '$TARGET_COMPOSE_FILE' up -d --build"
echo

echo "Cutover abgeschlossen. Bitte jetzt scripts/migration-smoke-test.sh ausfuehren."
