#!/usr/bin/env python3
import sys
from pathlib import Path
if len(sys.argv) != 3:
    raise SystemExit('usage: patch_caddy <in> <out>')
s = Path(sys.argv[1]).read_text()
site = 'sub-lb.tap365.org {'
start = s.find(site)
if start < 0:
    raise SystemExit('site block not found')
brace_start = s.find('{', start)
depth = 0
end = None
for i in range(brace_start, len(s)):
    if s[i] == '{':
        depth += 1
    elif s[i] == '}':
        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_proxy = 'reverse_proxy http://127.0.0.1:8090 http://103.114.163.226:48090 {'
new_proxy = 'reverse_proxy http://127.0.0.1:8090 http://127.0.0.1:6013 http://103.114.163.226:48090 {'
old_policy = 'lb_policy weighted_round_robin 10 4'
new_policy = 'lb_policy weighted_round_robin 10 4 4'
if block.count(old_proxy) != 1:
    raise SystemExit(f'expected one current proxy line in sub-lb block, got {block.count(old_proxy)}')
if block.count(old_policy) != 1:
    raise SystemExit(f'expected one current lb_policy line in sub-lb block, got {block.count(old_policy)}')
block = block.replace(old_proxy, new_proxy, 1).replace(old_policy, new_policy, 1)
Path(sys.argv[2]).write_text(s[:start] + block + s[end:])
