from pathlib import Path
import shutil, subprocess, datetime
p = Path('/etc/caddy/Caddyfile')
text = p.read_text()
ts = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
trash = Path('/etc/caddy/.trash')
trash.mkdir(parents=True, exist_ok=True)
backup = trash / f'Caddyfile_{ts}_detach_82_bad_api.bak'
shutil.copy2(p, backup)
old_service = '''\t@service_status_api path /api/v1/settings/service-status\n\thandle @service_status_api {\n\t\treverse_proxy http://82.29.54.80:48090 {\n\t\t\timport sub2api_proxy_common\n\t\t}\n\t}\n'''
new_service = '''\t@service_status_api path /api/v1/settings/service-status\n\thandle @service_status_api {\n\t\treverse_proxy http://103.114.163.226:48090 http://74.48.114.71:48090 {\n\t\t\tlb_policy weighted_round_robin 4 1\n\t\t\thealth_uri /health\n\t\t\thealth_interval 10s\n\t\t\thealth_timeout 5s\n\t\t\tfail_duration 30s\n\t\t\tmax_fails 1\n\t\t\theader_up Host {upstream_hostport}\n\t\t\timport sub2api_proxy_common\n\t\t}\n\t}\n'''
if old_service not in text:
    raise SystemExit('未找到 service_status_api 旧块，拒绝盲改')
text = text.replace(old_service, new_service, 1)
old_api = '''\t\treverse_proxy http://82.29.54.80:48090 http://103.114.163.226:48090 http://74.48.114.71:48090 {\n\t\t\tlb_policy weighted_round_robin 10 4 1\n'''
new_api = '''\t\treverse_proxy http://103.114.163.226:48090 http://74.48.114.71:48090 {\n\t\t\tlb_policy weighted_round_robin 4 1\n'''
if old_api not in text:
    raise SystemExit('未找到 @api 旧 upstream 行，拒绝盲改')
text = text.replace(old_api, new_api, 1)
tmp = Path(f'/tmp/Caddyfile.{ts}.detach_82_bad_api')
tmp.write_text(text)
res = subprocess.run(['caddy', 'validate', '--config', str(tmp)], text=True, capture_output=True)
print(res.stdout, end='')
print(res.stderr, end='')
if res.returncode != 0:
    raise SystemExit('caddy validate failed')
shutil.copy2(tmp, p)
res = subprocess.run(['systemctl', 'reload', 'caddy'], text=True, capture_output=True)
print(res.stdout, end='')
print(res.stderr, end='')
if res.returncode != 0:
    raise SystemExit('caddy reload failed')
print(f'backup={backup}')
print('changed=@api/service_status_api detach 82.29.54.80:48090')
