"""Revalidate static-site responses without changing any API location or TLS setting."""
from pathlib import Path
import os, shutil, subprocess, time

config = Path('/etc/nginx/sites-enabled/thmiuler.com.cn')
old = config.read_text()
marker = 'server_name thmiuler.com.cn www.thmiuler.com.cn;'
assert old.count(marker) == 1
before, after = old.split(marker)
location = 'location / {\n        try_files $uri $uri/ =404;'
replacement = 'location / {\n        # Revalidate site pages/assets after incremental publication.\n        expires -1;\n        try_files $uri $uri/ =404;'
if replacement in after:
    print('SITE_CACHE_ALREADY_CONFIGURED'); raise SystemExit(0)
assert after.count(location) == 1, 'Inspect changed site configuration before applying'
new = before + marker + after.replace(location, replacement)
backup = Path('/var/backups/thmiuler-site') / ('nginx-cache-' + time.strftime('%Y%m%d-%H%M%S'))
backup.mkdir(parents=True, exist_ok=False)
shutil.copy2(config, backup / 'thmiuler.com.cn')
stage = config.with_name('.thmiuler-site-cache-stage')
assert not stage.exists()
try:
    stage.write_text(new); shutil.copymode(config, stage); os.replace(stage, config)
    subprocess.run(['nginx', '-t'], check=True)
    subprocess.run(['systemctl', 'reload', 'nginx'], check=True)
except BaseException:
    shutil.copy2(backup / 'thmiuler.com.cn', config)
    subprocess.run(['nginx', '-t'], check=True)
    subprocess.run(['systemctl', 'reload', 'nginx'], check=True)
    raise
print('SITE_CACHE_CONFIGURED ' + str(backup))
