set -euo pipefail
TS=$(date +%Y%m%d_%H%M%S)
cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.bak.$TS
python3 - <<'PY'
from pathlib import Path
from textwrap import dedent

path = Path('/etc/caddy/Caddyfile')
text = path.read_text()
label = 'sub-lb35.tap365.org {'
if label in text:
    print('ALREADY_PRESENT')
    raise SystemExit(0)
anchor = 'sub-lb80.tap365.org {'
idx = text.find(anchor)
if idx < 0:
    raise SystemExit('未找到插入锚点 sub-lb80.tap365.org {')
block = dedent('''
sub-lb35.tap365.org {
	root * /srv/sub2api-80/current/frontend-dist
	encode zstd gzip

	@assets path /assets/* /favicon.ico /logo.png
	handle @assets {
		header {
			Cache-Control "public, max-age=31536000, immutable"
		}
		file_server
	}

	@service_status_api path /api/v1/settings/service-status
	handle @service_status_api {
		reverse_proxy http://127.0.0.1:8090 {
			import sub2api_proxy_common
		}
	}

	@api {
		path /api/*
		path /v1/*
		path /v1beta/*
		path /antigravity/*
		path /setup/*
		path /health
		path /responses
		path /responses/*
	}
	handle @api {
		reverse_proxy http://127.0.0.1:8090 http://74.48.114.71:48090 http://103.114.163.226:48090 {
			lb_policy weighted_round_robin 10 4 4
			health_uri /health
			health_interval 10s
			health_timeout 5s
			fail_duration 30s
			max_fails 1
			header_up Host {upstream_hostport}
			import sub2api_proxy_common
		}
	}

	@html path / /index.html
	header @html Cache-Control "no-cache, no-store, must-revalidate"

	handle {
		try_files {path} /index.html
		file_server
	}
}

''')
new_text = text[:idx] + block + text[idx:]
path.write_text(new_text)
print('INSERTED')
PY
caddy validate --config /etc/caddy/Caddyfile
caddy reload --config /etc/caddy/Caddyfile --adapter caddyfile
python3 - <<'PY'
from pathlib import Path
text = Path('/etc/caddy/Caddyfile').read_text()
start = text.find('sub-lb35.tap365.org {')
end = text.find('\n}\n', start)
print(text[start:end+3])
PY
