from pathlib import Path, PurePosixPath
import os, shutil, subprocess, tarfile
home = Path('/home/justrep-ssh')
web = home / 'www'
name = 'rec-explorer-mail-20261007-v2'
archive_path = home / f'{name}.tar.gz'
staging = home / name
backup = home / f'{name}-backup'
assert web.is_dir(), 'Web root missing'
assert not staging.exists(), 'Staging directory already exists'
assert not backup.exists(), 'Backup directory already exists'
staging.mkdir(mode=0o700)
backup.mkdir(mode=0o700)
allowed = {
    PurePosixPath('backend/core/rec-server.php'),
    PurePosixPath('backend/objects/explorateurs/explorateurs.php'),
}
with tarfile.open(archive_path, 'r:gz') as archive:
    members = archive.getmembers()
    paths = {PurePosixPath(member.name) for member in members}
    assert paths == allowed, f'Unexpected archive contents: {paths}'
    assert all(member.isfile() for member in members), 'Archive must contain files only'
    archive.extractall(staging)
for relative in sorted(allowed):
    source = staging.joinpath(*relative.parts)
    target = web.joinpath(*relative.parts)
    assert target.is_file(), f'Missing live file: {target}'
    backup_target = backup.joinpath(*relative.parts)
    backup_target.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(target, backup_target)
    lint = subprocess.run(['php', '-l', str(source)], check=True, capture_output=True, text=True)
    print(lint.stdout.strip())
for relative in sorted(allowed):
    source = staging.joinpath(*relative.parts)
    target = web.joinpath(*relative.parts)
    temp = target.with_name(target.name + '.rec-next')
    shutil.copyfile(source, temp)
    temp.chmod(target.stat().st_mode & 0o777)
    os.replace(temp, target)
for relative in sorted(allowed):
    target = web.joinpath(*relative.parts)
    subprocess.run(['php', '-l', str(target)], check=True)
print(f'Published {len(allowed)} PHP files; backup={backup}', flush=True)
archive_path.unlink()
Path(__file__).unlink()
