#!/usr/bin/env python3
"""Add/remove the temporary /stage/ location block in the robblake.cloud nginx vhost.

Used by the Drive delivery route: stage file -> upload via GOOGLEDRIVE_UPLOAD_FROM_URL
-> remove block. Lives at /tmp/nginx-stage-block.py on the VPS (recreate there if wiped).

Usage:
    python3 nginx-stage-block.py add      # insert block before "location / {" in 443 vhost
    python3 nginx-stage-block.py remove   # delete block + trailing blank line

Always follow with: nginx -t && systemctl reload nginx
Verify after add:    staged file returns 200
Verify after remove: staged file 404 AND https://robblake.cloud/ still 200 (dashboard intact)

Why a script: doing this edit with inline python -c broke the vhost twice on 2026-08-07
(shell escaping mangled the block; an off-by-one line-skip on removal ate the
"location / {" opener -> nginx -t failed, dashboard down until repaired).
Marker-line based, refuses double-add, fails loudly if the vhost shape changed.
"""
import sys

VHOST = '/etc/nginx/sites-enabled/robblake.cloud'
MARKER = '    location /stage/ {'

def main(action):
    lines = open(VHOST).readlines()
    has_block = any(l.rstrip() == MARKER for l in lines)

    if action == 'add':
        if has_block:
            print("already present — no change"); return
        block = [MARKER + '\n',
                 '        alias /var/www/html/stage/;\n',
                 '    }\n',
                 '\n']
        for i, l in enumerate(lines):
            if l.rstrip() == '    location / {':
                lines[i:i] = block
                break
        else:
            print("ERROR: '    location / {' not found — vhost shape changed, edit manually")
            sys.exit(1)
    elif action == 'remove':
        if not has_block:
            print("not present — no change"); return
        out, i = [], 0
        while i < len(lines):
            if lines[i].rstrip() == MARKER:
                i += 3  # skip marker, alias line, closing brace
                if i < len(lines) and lines[i].strip() == '':
                    i += 1  # skip ONE trailing blank line only
                continue
            out.append(lines[i])
            i += 1
        lines = out
    else:
        print(__doc__); sys.exit(1)

    open(VHOST, 'w').writelines(lines)
    print(f"{action} done")

if __name__ == '__main__':
    main(sys.argv[1] if len(sys.argv) > 1 else '')
