#!/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/adr-library-2B-${STAMP}"

echo "YachtMemory Paket 2B - ADR-Bibliothek"
echo "Ziel:   ${TARGET}"
echo "Backup: ${BACKUP}"
echo

test -d "${TARGET}" || {
    echo "FEHLER: Zielverzeichnis existiert nicht: ${TARGET}" >&2
    exit 1
}

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

grep -q "function require_permission" "${TARGET}/src/lib/auth.php" || {
    echo "FEHLER: Permission-Fundament 2A ist nicht installiert." >&2
    exit 1
}

mkdir -p "${BACKUP}/public"

cp -a "${TARGET}/public/dashboard.php" "${BACKUP}/public/dashboard.php"

if [ -f "${TARGET}/public/architecture.php" ]; then
    cp -a "${TARGET}/public/architecture.php" "${BACKUP}/public/architecture.php"
fi

if [ -f "${TARGET}/public/architecture_pdf.php" ]; then
    cp -a "${TARGET}/public/architecture_pdf.php" "${BACKUP}/public/architecture_pdf.php"
fi

echo "1/3 Dateien installieren"

install -m 0644 "${PKG}/public/dashboard.php" \
    "${TARGET}/public/dashboard.php"

install -m 0644 "${PKG}/public/architecture.php" \
    "${TARGET}/public/architecture.php"

install -m 0644 "${PKG}/public/architecture_pdf.php" \
    "${TARGET}/public/architecture_pdf.php"

echo
echo "2/3 PHP-Syntaxprüfung"

php -l "${TARGET}/public/dashboard.php"
php -l "${TARGET}/public/architecture.php"
php -l "${TARGET}/public/architecture_pdf.php"

echo
echo "3/3 ADR-Repository prüfen"

php "${PKG}/scripts/check_adr_repository.php"

echo
echo "Installation abgeschlossen."
echo "Backup: ${BACKUP}"
echo
echo "Browser-Test:"
echo "  https://app.yachtmemory.net/dashboard.php"
echo "  https://app.yachtmemory.net/architecture.php"
