from pathlib import Path
import secrets, subprocess, shutil
p=Path('/etc/caddy/Caddyfile')
original=p.read_text()
assert 'shorts.archivedpiece.com {' not in original
password=secrets.token_urlsafe(24)
login=Path('/root/workspace/shorts-login.txt')
login.touch(mode=0o600, exist_ok=False)
login.write_text('URL: https://shorts.archivedpiece.com\nUsername: control\nPassword: '+password+'\n')
hash_value=subprocess.check_output(['caddy','hash-password','--plaintext',password],text=True).strip()
shutil.copy2(p, '/etc/caddy/Caddyfile.before-shorts')
candidate=Path('/root/workspace/Caddyfile.shorts')
candidate.write_text(original+'\n\nshorts.archivedpiece.com {\n\tbasicauth {\n\t\tcontrol '+hash_value+'\n\t}\n\treverse_proxy 127.0.0.1:8790\n}\n')
subprocess.run(['caddy','validate','--config',str(candidate),'--adapter','caddyfile'],check=True)
shutil.copyfile(candidate,p)
subprocess.run(['systemctl','reload','caddy'],check=True)
print('configured')
