"""Verified incremental website deployment. Run on the existing Linux web server."""
from pathlib import Path, PurePosixPath
from urllib.request import urlopen
import argparse, fcntl, hashlib, json, os, shutil, time, uuid

p = argparse.ArgumentParser()
p.add_argument('--base-url', required=True)
p.add_argument('--manifest-sha256', required=True)
p.add_argument('--check-only', action='store_true')
a = p.parse_args()
root = Path('/var/www/thmiuler.com.cn')
assert root.resolve() == root and root.is_dir()
lock = open('/var/lock/thmiuler-website-release.lock', 'a')
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
def sha(data): return hashlib.sha256(data).hexdigest()
def fetch(name):
    with urlopen(a.base_url.rstrip('/') + '/' + name, timeout=45) as r: return r.read()
raw = fetch('site-release-manifest.json')
assert sha(raw) == a.manifest_sha256, 'Manifest digest mismatch'
manifest = json.loads(raw)
assert manifest['expectedRoot'] == str(root) and manifest['format'] == 1
files = manifest['files']
assert len({f['path'] for f in files}) == len(files)
def target(name):
    rel = PurePosixPath(name)
    assert not rel.is_absolute() and '..' not in rel.parts and '\\' not in name
    assert (len(rel.parts) == 1 and rel.suffix == '.html') or (rel.parts[0] == 'home' and rel.suffix in ['.js', '.css', '.svg', '.jpg', '.png'])
    dest = root.joinpath(*rel.parts)
    assert root in dest.resolve().parents and not dest.is_symlink()
    return dest
incoming = Path('/var/backups/thmiuler-site') / (time.strftime('%Y%m%d-%H%M%S') + '-' + uuid.uuid4().hex[:8])
incoming.mkdir(parents=True)
(incoming / 'site-release-manifest.json').write_bytes(raw)
prepared = {}
for f in files:
    dest = target(f['path'])
    old = f.get('expectedOldSha256')
    if old: assert dest.is_file() and sha(dest.read_bytes()) == old, 'Live file changed: ' + f['path']
    else: assert not dest.exists() or sha(dest.read_bytes()) == f['sha256'], 'Unexpected existing asset: ' + f['path']
    data = fetch(f['path'])
    assert len(data) == f['bytes'] and sha(data) == f['sha256'], f['path']
    src = incoming / 'incoming' / f['path']; src.parent.mkdir(parents=True, exist_ok=True); src.write_bytes(data)
    prepared[f['path']] = src
print(json.dumps({'ready': True, 'files': len(files), 'backup': str(incoming)}), flush=True)
if a.check_only: raise SystemExit(0)
guard_paths = ['app.js', 'support-widget.js', 'support-widget.css', 'data/lessons.json', 'data/cases.json', 'robots.txt', 'sitemap.xml']
guards = {name: sha((root / name).read_bytes()) for name in guard_paths}
media = {str(f.relative_to(root)): (f.stat().st_size, f.stat().st_mtime_ns) for folder in ['media', 'downloads'] for f in (root / folder).rglob('*') if f.is_file()}
old_files = []
for f in files:
    dest = target(f['path'])
    if dest.exists():
        backup = incoming / 'before' / f['path']; backup.parent.mkdir(parents=True, exist_ok=True); shutil.copy2(dest, backup)
        old_files.append(f['path'])
(incoming / 'old-files.json').write_text(json.dumps(old_files))
def replace(src, dest):
    dest.parent.mkdir(parents=True, exist_ok=True)
    tmp = dest.parent / ('.site-stage-' + uuid.uuid4().hex)
    try:
        shutil.copyfile(src, tmp); tmp.chmod(0o644); os.replace(tmp, dest)
    finally:
        if tmp.exists(): tmp.unlink()
applied = []
try:
    # Assets first, complete inner documents next, homepage last. Each file replaces atomically.
    for f in sorted(files, key=lambda f: (f['path'] == 'index.html', f['path'].endswith('.html'), f['path'])):
        replace(prepared[f['path']], target(f['path'])); applied.append(f['path'])
    assert all(sha(target(f['path']).read_bytes()) == f['sha256'] for f in files)
    assert all(sha((root / name).read_bytes()) == digest for name, digest in guards.items())
    assert all(((root / name).stat().st_size, (root / name).stat().st_mtime_ns) == info for name, info in media.items())
except BaseException:
    for name in reversed(applied):
        if name in old_files: replace(incoming / 'before' / name, target(name))
        else: target(name).unlink()
    raise
report = {'success': True, 'release': manifest['release'], 'files': len(files), 'preservedMediaFiles': len(media), 'preservedServices': True, 'backup': str(incoming)}
(incoming / 'deployment-report.json').write_text(json.dumps(report, indent=2), 'utf-8')
print('SITE_DEPLOY_SUCCESS ' + json.dumps(report), flush=True)
