#!/bin/bash
# One-shot installer for the /sharedtodo/ STATIC location block.
# The initial install of /sharedtodo/api/ was correct, but the landing
# page + SharedTodo.js were being served from the catch-all `location /`
# which does NOT set Cache-Control: no-store. Cloudflare cached a 200
# response for /sharedtodo/SharedTodo.js and began serving it without
# auth-gating. This adds an explicit static block matching the pattern
# used by /todos/, /remote/, /petfeed/, etc.
#
# 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
TAG='Shared Todo landing page'
# Insert right after the /sharedtodo/api/ block closes. We key off that
# block's trailing Cache-Control line since it's unique.
MARKER='^    # ===== 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-static.$STAMP"
cp "$AVAILABLE" "/root/nginx-backups/adampowell.pro.sites-available.pre-sharedtodo-static.$STAMP"
echo "backup: pre-sharedtodo-static.$STAMP"

BLOCK_FILE=$(mktemp)
cat > "$BLOCK_FILE" <<'NGX'
    # ===== Shared Todo landing page (static, session-gated) =====
    # Explicit block (not just catch-all) so we set Cache-Control: no-store —
    # otherwise Cloudflare caches /sharedtodo/SharedTodo.js and starts serving
    # it without auth-gating. Same pattern as /todos/, /remote/, /petfeed/.
    # The script source is not secret (credentials go into iOS Keychain at
    # first run), but the landing page must stay behind /login regardless.
    location /sharedtodo/ {
        auth_request     /_auth_check;
        error_page 401 = @login_redirect;
        try_files $uri $uri/ =404;
        add_header Cache-Control "no-store, no-cache, must-revalidate, private" always;
    }

NGX

inject() {
    local src="$1"
    local dst
    dst=$(mktemp)
    # Walk the file. When we see the "Shared Todo API" marker comment, we
    # know the API block is the next multi-line chunk. Print through the
    # closing `}` + its following blank line, then emit the new block.
    awk -v blockfile="$BLOCK_FILE" -v marker="Shared Todo API" '
        BEGIN {
            block = ""
            while ((getline line < blockfile) > 0) block = block line "\n"
            close(blockfile)
            state = "before"
        }
        {
            print
        }
        state == "in-api-block" && /^    }/ {
            # closing brace of the /sharedtodo/api/ block — the next line
            # should be blank; we insert our block immediately after it
            state = "after-closing"
            next
        }
        state == "after-closing" {
            # first line after closing brace (usually blank)
            if ($0 == "") { printf "%s", block; state = "done" }
            next
        }
        state == "before" && $0 ~ marker {
            state = "in-api-block"
        }
        END {
            if (state != "done") 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-static.$STAMP"   "$ENABLED"
    cp "/root/nginx-backups/adampowell.pro.sites-available.pre-sharedtodo-static.$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-static.$STAMP"   "$ENABLED"
    cp "/root/nginx-backups/adampowell.pro.sites-available.pre-sharedtodo-static.$STAMP" "$AVAILABLE"
    nginx -t
    exit 1
fi

systemctl reload nginx
echo "reloaded"

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