from pathlib import Path
from datetime import datetime

p = Path('/etc/caddy/Caddyfile')
text = p.read_text()
old = '''# IndexTTS API - mason1 via FRP, protected by API key
indextts.tap365.org {
	request_body {
		max_size 200MB
	}

	@authorized_header {
		header X-API-Key "c26928204b928c74fea9e4e28266f7437fb341e3ec8e6a2a"
	}

	@authorized_bearer {
		header Authorization "Bearer c26928204b928c74fea9e4e28266f7437fb341e3ec8e6a2a"
	}

	handle @authorized_header {
		reverse_proxy localhost:17862
	}

	handle @authorized_bearer {
		reverse_proxy localhost:17862
	}

	respond "Unauthorized" 401
	encode gzip
}
'''
new = '''# IndexTTS API - mason1 via FRP, protected by API key
indextts.tap365.org {
	request_body {
		max_size 200MB
	}

	handle_path /tester* {
		root * /var/www/indextts-tester
		try_files {path} /index.html
		file_server
	}

	@authorized_header {
		header X-API-Key "c26928204b928c74fea9e4e28266f7437fb341e3ec8e6a2a"
	}

	@authorized_bearer {
		header Authorization "Bearer c26928204b928c74fea9e4e28266f7437fb341e3ec8e6a2a"
	}

	handle @authorized_header {
		reverse_proxy localhost:17862
	}

	handle @authorized_bearer {
		reverse_proxy localhost:17862
	}

	respond "Unauthorized" 401
	encode gzip
}
'''
if old not in text:
    raise SystemExit('target block not found')
backup = Path('/etc/caddy/Caddyfile.bak_' + datetime.now().strftime('%Y%m%d_%H%M%S'))
backup.write_text(text)
p.write_text(text.replace(old, new, 1))
print(backup)
