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

SERVICE_FILE="/etc/systemd/system/durakometr-api.service"
BACKUP_FILE="/etc/systemd/system/durakometr-api.service.bak-v110"

echo "=== DURAKOMETR V1.10 VPS FINALIZE ==="

cp "$SERVICE_FILE" "$BACKUP_FILE"

# Old Firebase credential environment variable is now dead and should not
# reference a key that has already been removed.
sed -i \
    '/GOOGLE_APPLICATION_CREDENTIALS=.*firebase-service-account\.json/d' \
    "$SERVICE_FILE"

systemctl daemon-reload
systemctl restart durakometr-api
sleep 2

echo
echo "=== HEALTH ==="
curl -fsS https://5.188.21.226/health
echo

echo
echo "=== ZERO FIREBASE SERVER CHECK ==="

if /opt/durakometr/venv/bin/pip show firebase-admin >/dev/null 2>&1; then
    echo "FAIL: firebase-admin package is still installed"
    exit 1
else
    echo "firebase-admin: REMOVED"
fi

if /opt/durakometr/venv/bin/pip show google-cloud-firestore >/dev/null 2>&1; then
    echo "FAIL: google-cloud-firestore package is still installed"
    exit 1
else
    echo "google-cloud-firestore: REMOVED"
fi

if [[ -e /opt/durakometr/secrets/firebase-service-account.json ]]; then
    echo "FAIL: Firebase service-account key still exists"
    exit 1
else
    echo "Firebase service-account key: REMOVED"
fi

if grep -nEi \
    'firebase_admin|from firebase_admin|google\.cloud\.firestore|FirebaseFirestore' \
    /opt/durakometr/backend/main.py
then
    echo "FAIL: Firebase backend code remains"
    exit 1
else
    echo "Firebase backend code: NONE"
fi

if grep -q 'GOOGLE_APPLICATION_CREDENTIALS' "$SERVICE_FILE"; then
    echo "FAIL: stale GOOGLE_APPLICATION_CREDENTIALS remains in systemd unit"
    exit 1
else
    echo "systemd Firebase credential env: REMOVED"
fi

echo
echo "=== DATABASE BASELINE ==="

sudo -u postgres psql \
    -d durakometr \
    -P pager=off \
    -c "
SELECT
    (SELECT COUNT(*) FROM app_auth_credentials) AS auth_accounts,
    (SELECT COUNT(*) FROM app_games WHERE group_id='main') AS games;

SELECT player_id, losses
FROM app_scores
WHERE group_id='main'
ORDER BY player_id;
"

echo
echo "=== UPDATER HTTPS ==="

curl -fsS https://5.188.21.226/updates/latest.json
echo

if grep -q \
    'http://5\.188\.21\.226' \
    /usr/local/bin/durak-release
then
    echo "FAIL: durak-release still contains HTTP base URL"
    exit 1
else
    echo "durak-release HTTPS: OK"
fi

echo
echo "VPS FINALIZE PASS"
