#!/bin/bash
# One-shot installer for the /sharedtodo/api/ nginx location block.
# Idempotent: does nothing if the block is already present.
# Run as root on the droplet.

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='Shared Todo 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-sharedtodo.$STAMP"
cp "$AVAILABLE" "/root/nginx-backups/adampowell.pro.sites-available.pre-sharedtodo.$STAMP"
echo "backup: pre-sharedtodo.$STAMP"

BLOCK_FILE=$(mktemp)
cat > "$BLOCK_FILE" <<'NGX'
    # ===== Shared Todo API — bearer token, NO auth_request =====
    # Same pattern as /remote/api/daemon/: phones run Scriptable widgets and
    # cannot hold a login session cookie. The Node app validates the
    # Authorization: Bearer <SHAREDTODO_BEARER_TOKEN> header itself. Static
    # /sharedtodo/ (landing page + SharedTodo.js) stays behind the main
    # auth_request via the catch-all `location /` below.
    location /sharedtodo/api/ {
        proxy_pass         http://127.0.0.1:3014/;
        proxy_http_version 1.1;
        proxy_set_header   Host $host;
        proxy_set_header   X-Real-IP $remote_addr;
        proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header   X-Forwarded-Proto https;
        proxy_set_header   Authorization $http_authorization;
        proxy_read_timeout 30s;
        client_max_body_size 256k;
        add_header Cache-Control "no-store, no-cache, must-revalidate, private" always;
    }

NGX

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)
            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"

rm -f "$BLOCK_FILE"

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-sharedtodo.$STAMP"   "$ENABLED"
    cp "/root/nginx-backups/adampowell.pro.sites-available.pre-sharedtodo.$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-sharedtodo.$STAMP"   "$ENABLED"
    cp "/root/nginx-backups/adampowell.pro.sites-available.pre-sharedtodo.$STAMP" "$AVAILABLE"
    nginx -t
    exit 1
fi

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

echo
echo "=== diff ==="
if diff -q "$ENABLED" "$AVAILABLE" > /dev/null; then
    echo "sites-enabled and sites-available are identical"
else
    echo "!!! WARNING: sites-enabled and sites-available diverged"
    diff "$ENABLED" "$AVAILABLE"
fi
