import sys, os

path = "/etc/caddy/Caddyfile"
backup = "/etc/caddy/Caddyfile.bak-ota-raw-20260808-111437"
assert os.path.exists(backup), f"backup missing: {backup}"

with open(path) as f:
    content = f.read()

# Fix: move header_up OUT of transport, into reverse_proxy body (correct Caddy syntax)
old_rp = """\treverse_proxy 127.0.0.1:4300 {
\t\ttransport http {
\t\t\tread_timeout 600s
\t\t\twrite_timeout 600s
\t\t\theader_up - Accept-Encoding
\t\t}
\t}"""
new_rp = """\treverse_proxy 127.0.0.1:4300 {
\t\ttransport http {
\t\t\tread_timeout 600s
\t\t\twrite_timeout 600s
\t\t}
\t\theader_up - Accept-Encoding
\t}"""
if old_rp not in content:
    print("REVERSE_PROXY BLOCK NOT FOUND — aborting, nothing changed")
    sys.exit(2)
content = content.replace(old_rp, new_rp, 1)
print("moved 'header_up - Accept-Encoding' to reverse_proxy body")

with open(path, "w") as f:
    f.write(content)
print("Caddyfile updated")
