#!/usr/bin/env python3
import sys
from pathlib import Path
if len(sys.argv) != 3:
    raise SystemExit('usage: patch_caddy <in> <out>')
p = Path(sys.argv[1])
s = p.read_text()
site = 'sub-lb.tap365.org {'
start = s.find(site)
if start < 0:
    raise SystemExit('site block not found')
# brace-aware block scan from site opening brace
brace_start = s.find('{', start)
if brace_start < 0:
    raise SystemExit('site opening brace not found')
depth = 0
end = None
for i in range(brace_start, len(s)):
    ch = s[i]
    if ch == '{':
        depth += 1
    elif ch == '}':
        depth -= 1
        if depth == 0:
            end = i + 1
            if end < len(s) and s[end:end+1] == '\n':
                end += 1
            break
if end is None:
    raise SystemExit('site block end not found')
block = s[start:end]
old = 'reverse_proxy http://127.0.0.1:8090 http://74.48.114.71:48090 http://103.114.163.226:48090 {'
new = 'reverse_proxy http://127.0.0.1:8090 http://127.0.0.1:6013 http://103.114.163.226:48090 {'
cnt = block.count(old)
if cnt != 1:
    raise SystemExit(f'expected one target reverse_proxy line in sub-lb block, got {cnt}')
block2 = block.replace(old, new, 1)
out = s[:start] + block2 + s[end:]
Path(sys.argv[2]).write_text(out)
