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

# Erstellt ein lokales Backup der Persistenzdaten.
# Ziel: data/prod.db + public/uploads

APP_DIR="${APP_DIR:-$(pwd)}"
BACKUP_DIR="${BACKUP_DIR:-$APP_DIR/backups/persistence}"
TIMESTAMP="$(date +%Y%m%d_%H%M%S)"
OUT_DIR="$BACKUP_DIR/$TIMESTAMP"

cd "$APP_DIR"

mkdir -p "$OUT_DIR"

echo "== Hördle Persistenz-Backup =="
echo "Quelle: $APP_DIR"
echo "Ziel:   $OUT_DIR"

if [ -f "data/prod.db" ]; then
  if command -v sqlite3 >/dev/null 2>&1; then
    sqlite3 "data/prod.db" ".timeout 5000" ".backup '$OUT_DIR/prod.db'"
  else
    cp "data/prod.db" "$OUT_DIR/prod.db"
  fi
  sha256sum "$OUT_DIR/prod.db" > "$OUT_DIR/prod.db.sha256"
else
  echo "Warnung: data/prod.db fehlt."
fi

if [ -d "public/uploads" ]; then
  tar -C "public" -czf "$OUT_DIR/uploads.tar.gz" "uploads"
  sha256sum "$OUT_DIR/uploads.tar.gz" > "$OUT_DIR/uploads.tar.gz.sha256"
else
  echo "Warnung: public/uploads fehlt."
fi

echo "$TIMESTAMP" > "$BACKUP_DIR/latest"
echo "Backup abgeschlossen: $OUT_DIR"
