#!/bin/bash
# One-shot installer for the /ekg-tutor/api/ nginx location block.
# Idempotent: does nothing if the block is already present.
# Run as root on the droplet.
#
# Same pattern as apps/server/sharedtodo/install-nginx-block.sh — backs up,
# injects above the gated catch-all, validates with nginx -t, reloads.

set -euo pipefail

STAMP=$(date +%Y%m%d_%H%M%S)
ENABLED=/etc/nginx/sites-enabled/adampowell.pro
AVAILABLE=/etc/nginx/sites-available/adampowell.pro
MARKER='^    # ===== Gated static root'
TAG='EKG Tutor API'

if grep -q "$TAG" "$ENABLED" && grep -q "$TAG" "$AVAILABLE"; then
    echo "already installed in both files — nothing to do"
    exit 0
fi

mkdir -p /root/nginx-backups
cp "$ENABLED"   "/root/nginx-backups/adampowell.pro.sites-enabled.pre-ekg-tutor.$STAMP"
cp "$AVAILABLE" "/root/nginx-backups/adampowell.pro.sites-available.pre-ekg-tutor.$STAMP"
echo "backup: pre-ekg-tutor.$STAMP"

BLOCK_FILE=/var/www/adampowell.pro/apps/ekg-tutor/infra/nginx/ekg-tutor.conf.snippet

inject() {
    local src="$1"
    local dst
    dst=$(mktemp)
    awk -v blockfile="$BLOCK_FILE" -v marker="$MARKER" '
        BEGIN {
            block = ""
            while ((getline line < blockfile) > 0) block = block line "\n"
            close(blockfile)
            block = block "\n"
            inserted = 0
        }
        !inserted && $0 ~ marker {
            printf "%s", block
            inserted = 1
        }
        { print }
        END { if (!inserted) exit 2 }
    ' "$src" > "$dst"
    mv "$dst" "$src"
}

inject "$ENABLED"
inject "$AVAILABLE"

count_e=$(grep -c "$TAG" "$ENABLED")
count_a=$(grep -c "$TAG" "$AVAILABLE")
echo "occurrences — enabled: $count_e  available: $count_a"
if [ "$count_e" != "1" ] || [ "$count_a" != "1" ]; then
    echo "!!! unexpected occurrence count — reverting"
    cp "/root/nginx-backups/adampowell.pro.sites-enabled.pre-ekg-tutor.$STAMP"   "$ENABLED"
    cp "/root/nginx-backups/adampowell.pro.sites-available.pre-ekg-tutor.$STAMP" "$AVAILABLE"
    exit 1
fi

echo "=== nginx -t ==="
if ! nginx -t 2>&1; then
    echo "!!! nginx -t FAILED — reverting"
    cp "/root/nginx-backups/adampowell.pro.sites-enabled.pre-ekg-tutor.$STAMP"   "$ENABLED"
    cp "/root/nginx-backups/adampowell.pro.sites-available.pre-ekg-tutor.$STAMP" "$AVAILABLE"
    nginx -t
    exit 1
fi

echo "=== reload ==="
systemctl reload nginx
echo "reloaded"
