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

Usage: python3 nginx-stage-block.py add|remove
Then: mkdir -p /var/www/html/stage && cp files in, systemctl reload nginx.
Always remove the block + delete staged files after the Drive upload (confirm 404).

Written 2026-08-07 after an inline-sed approach corrupted the vhost once.
The composio-mcp-ops skill references this helper; canonical copy lived at
/tmp/nginx-stage-block.py (volatile) — this copy is the durable one.
"""
import sys

path = '/etc/nginx/sites-enabled/robblake.cloud'
lines = open(path).readlines()

if sys.argv[1] == 'add':
    block = ['    location /stage/ {\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"); sys.exit(1)
elif sys.argv[1] == 'remove':
    out = []
    i = 0
    while i < len(lines):
        if lines[i].rstrip() == '    location /stage/ {':
            i += 4  # skip block + trailing blank line
            continue
        out.append(lines[i])
        i += 1
    lines = out

open(path, 'w').writelines(lines)
print(f"{sys.argv[1]} done")
