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

# Inventarisiert Persistenz und laufzeitrelevante Variablen für die Migration.
# Das Skript verändert keine Daten.

ROOT_DIR="${1:-$(pwd)}"
cd "$ROOT_DIR"

count_files_recursive() {
  local dir="$1"
  find "$dir" -type f 2>/dev/null | wc -l
}

echo "== Hördle Migrations-Inventur =="
echo "Projektpfad: $(pwd)"
echo

required_paths=(
  "data"
  "data/prod.db"
  "public/uploads"
  "docker-compose.yml"
  ".env"
)

echo "-- Existenzcheck --"
for path in "${required_paths[@]}"; do
  if [ -e "$path" ]; then
    echo "[OK] $path"
  else
    echo "[FEHLT] $path"
  fi
done
echo

echo "-- Groesse und Dateizaehlung --"
if [ -d "data" ]; then
  du -sh "data"
  DATA_FILE_COUNT="$(count_files_recursive "data")"
  echo "Dateien in data/: $DATA_FILE_COUNT"
fi

if [ -d "public/uploads" ]; then
  du -sh "public/uploads"
  UPLOAD_FILE_COUNT="$(count_files_recursive "public/uploads")"
  echo "Dateien in public/uploads/: $UPLOAD_FILE_COUNT"
fi
echo

echo "-- DB Hash (Integritaetsreferenz) --"
if [ -f "data/prod.db" ]; then
  sha256sum "data/prod.db"
else
  echo "data/prod.db nicht gefunden."
fi
echo

echo "-- Compose Persistenz-Mounts --"
grep -E "^[[:space:]]*-[[:space:]]+\./(data|public/uploads):" "docker-compose.yml" || true
echo

echo "-- Runtime Variablen in Compose --"
grep -E "^[[:space:]]*-[[:space:]]+(DATABASE_URL|ADMIN_PASSWORD|TZ|GOTIFY_URL|GOTIFY_APP_TOKEN|OPENROUTER_API_KEY)=" "docker-compose.yml" || true
echo

echo "-- Hinweise --"
echo "1) Stelle sicher, dass .env nicht aus Versehen in Transfers/Backups an Dritte gelangt."
echo "2) Fuer den Cutover muss die Quell-App vor Final-Sync gestoppt werden."
echo "3) Nutze danach scripts/migration-precopy.sh und scripts/migration-cutover.sh."
