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

TARGET="${1:-/var/www/app.yachtmemory.net}"
PKG="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
STAMP="$(date +%Y%m%d-%H%M%S)"
BACKUP="${TARGET}/backup/derived-writers-2B1-${STAMP}"

FILES=(
  "shared_dashboard/scripts/rebuild_anchorages.php"
  "shared_dashboard/scripts/update_anchorages_incremental.php"
  "shared_dashboard/api/rebuild_anchorages.php"
  "shared_dashboard/api/anchorages_refresh.php"
  "vessels/silent_sea/api/rebuild_anchorages.php"
  "vessels/silent_sea/api/anchorages_refresh.php"
)

echo "YachtMemory Derived Writers - Phase 2B.1"
echo "Ziel:   ${TARGET}"
echo "Backup: ${BACKUP}"
echo

test -f "${TARGET}/src/lib/DerivedDb.php" || {
  echo "FEHLER: Phase 2A / DerivedDb.php fehlt." >&2
  exit 1
}

test -f "${TARGET}/src/services/TelemetryDbRouter.php" || {
  echo "FEHLER: TelemetryDbRouter.php fehlt." >&2
  exit 1
}

mkdir -p "${BACKUP}"

echo "1/4 Backup"
for rel in "${FILES[@]}"; do
  if [ -f "${TARGET}/${rel}" ]; then
    mkdir -p "${BACKUP}/$(dirname "${rel}")"
    cp -a "${TARGET}/${rel}" "${BACKUP}/${rel}"
  fi
done

echo "2/4 Paketprüfung"
php "${PKG}/scripts/verify_phase2b.php"

for rel in "${FILES[@]}"; do
  php -l "${PKG}/${rel}"
done

echo "3/4 Installation"
for rel in "${FILES[@]}"; do
  mkdir -p "${TARGET}/$(dirname "${rel}")"
  install -m 0644 "${PKG}/${rel}" "${TARGET}/${rel}"
done

echo "4/4 Installationsprüfung"
for rel in "${FILES[@]}"; do
  php -l "${TARGET}/${rel}"
done

echo
echo "Phase 2B.1 installiert."
echo "WICHTIG: Der Installer führt keinen Rebuild aus."
echo "Produktive Writer sind jetzt auf Telemetry -> Derived geroutet."
echo "Backup: ${BACKUP}"
