from pathlib import Path, PurePosixPath
import os, re, shutil, sys, tarfile
home=Path('/home/justrep-ssh')
web=home/'www'
slug='rec-references-20260930'
release=home/slug
backup=home/(slug+'-backup')
archive_path=home/(slug+'.tar.gz')
assert web.is_dir(), 'Web root is missing'
assert not release.exists() and not backup.exists(), 'Deployment path already exists; inspect before retrying'
release.mkdir(mode=0o755)
backup.mkdir(mode=0o700)
with tarfile.open(archive_path,'r:gz') as archive:
    members=[]
    for member in archive.getmembers():
        path=PurePosixPath(member.name)
        assert not path.is_absolute() and '..' not in path.parts and member.isfile(), f'Unsafe archive member: {member.name}'
        members.append((member.name, path))
    archive.extractall(release)
files=[(release.joinpath(*path.parts),path) for _,path in members]
with tarfile.open(backup/'overwritten-files.tar.gz','w:gz') as old:
    for _,relative in files:
        target=web.joinpath(*relative.parts)
        if target.is_file(): old.add(target,arcname=relative.as_posix(),recursive=False)
# Publish immutable assets first and HTML entry points last.
for source,relative in sorted(files,key=lambda item:(item[1].suffix=='.html',item[1].as_posix())):
    target=web.joinpath(*relative.parts)
    target.parent.mkdir(parents=True,exist_ok=True)
    temp=target.with_name(target.name+'.justrec-next')
    shutil.copyfile(source,temp)
    temp.chmod(0o644)
    os.replace(temp,target)
index=(web/'index.html').read_text()
assets=set(re.findall(r'(?:src|href)="(/assets/[^"]+)"',index))
assert assets and all((web/a.lstrip('/')).is_file() for a in assets), 'Published index references a missing asset'
refs=next((p for p in assets if 'ReferencesPage-' in p),None)
assert refs, 'References bundle is not linked by the published index'
print(f'Published {len(files)} frontend files; backup={backup}; references_bundle={refs}')
