#!/usr/bin/env python3
"""Apply the OneERP Charter Hire update to a matching source checkout."""
import argparse
import hashlib
import json
import os
from pathlib import Path, PurePosixPath
import shutil
import stat
import sys
import tempfile

PACKAGE = Path(__file__).resolve().parent


def digest(path):
    if not path.exists():
        return None
    if not path.is_file():
        raise ValueError(f"Expected a regular file: {path}")
    return hashlib.sha256(path.read_bytes()).hexdigest()


def safe_path(base, name):
    relative = PurePosixPath(name)
    if relative.is_absolute() or not relative.parts or '..' in relative.parts or '\\' in name:
        raise ValueError(f"Unsafe package path: {name}")
    current = base
    for part in relative.parts:
        current = current / part
        if current.is_symlink():
            raise ValueError(f"Refusing to follow a symbolic link: {current}")
    return current


def replace_file(src, dst, mode):
    dst.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=dst.parent, prefix='.charter-hire-', delete=False) as stream:
        temporary = Path(stream.name)
        try:
            with src.open('rb') as content:
                shutil.copyfileobj(content, stream)
            stream.flush()
            os.fsync(stream.fileno())
            os.chmod(temporary, mode)
            stream.close()
            os.replace(temporary, dst)
        finally:
            temporary.unlink(missing_ok=True)


def verify_targets(root, changes):
    pending, conflicts = [], []
    for name, hashes in changes.items():
        target = safe_path(root, name)
        content = safe_path(PACKAGE / 'files', name)
        if digest(content) != hashes['after']:
            raise ValueError(f"Package content failed integrity check: {name}")
        current = digest(target)
        if current == hashes['after']:
            continue
        if current not in hashes['accepted_before']:
            conflicts.append(name)
        else:
            pending.append((name, target, content, current))
    if conflicts:
        raise ValueError('Target differs from Benjamin\'s export and the verified RC3 files. No app files changed. Rebase these files first:\n  ' + '\n  '.join(conflicts))
    return pending


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--target', '-t', default='.', help='OneERP application root')
    parser.add_argument('--apply', action='store_true', help='Write the checked changes. Default is dry run.')
    parser.add_argument('--backup-dir', help='New backup path outside the app root. Default is an automatically named sibling directory.')
    args = parser.parse_args()
    if args.backup_dir and not args.apply:
        parser.error('--backup-dir requires --apply')
    root = Path(args.target).resolve(strict=True)
    for required in ('artisan', 'composer.json', 'routes/web.php'):
        if not safe_path(root, required).is_file():
            raise ValueError(f'Not a OneERP application root: missing {required}')
    if (PACKAGE / 'files').is_symlink():
        raise ValueError('Refusing a symbolic link for the package payload.')
    changes = json.loads((PACKAGE / 'manifest.json').read_text(encoding='utf-8'))['files']
    if not args.apply:
        pending = verify_targets(root, changes)
        print(f'Dry run passed. {len(pending)} files to install; {len(changes)-len(pending)} already match. No files written.')
        return

    # Prevent two runs of this installer on the same checkout; deploy under a maintenance window.
    lock = root / '.nue-charter-hire-install.lock'
    lock.mkdir()
    try:
        pending = verify_targets(root, changes)
        if not pending:
            print('Already installed. No files written.')
            return
        if args.backup_dir:
            backup = Path(args.backup_dir).resolve()
            if backup.is_relative_to(root) or backup.is_relative_to(PACKAGE):
                raise ValueError('Backup must be outside the application and package directories.')
            backup.mkdir(mode=0o700)
        else:
            backup = Path(tempfile.mkdtemp(prefix=f'{root.name}-charter-hire-backup-', dir=root.parent))
        for name, target, _, previous in pending:
            if previous is not None:
                saved = backup / 'files' / name
                saved.parent.mkdir(parents=True, exist_ok=True)
                shutil.copy2(target, saved)
                if digest(saved) != previous:
                    raise RuntimeError(f'Backup failed verification: {name}')
        (backup / 'restore-manifest.json').write_text(json.dumps({
            name: {'before': previous, 'after': changes[name]['after']} for name, _, _, previous in pending
        }, indent=2) + '\n', encoding='utf-8')
        finished = []
        try:
            for name, target, content, previous in pending:
                if digest(target) != previous:
                    raise ValueError(f'Target changed during installation: {name}')
                mode = stat.S_IMODE(target.stat().st_mode) if previous is not None else 0o644
                replace_file(content, target, mode)
                finished.append((name, target, previous))
                if digest(target) != changes[name]['after']:
                    raise RuntimeError(f'Installed content failed verification: {name}')
        except BaseException:
            failed = []
            for name, target, previous in reversed(finished):
                try:
                    if digest(target) != changes[name]['after']:
                        raise RuntimeError('Installed bytes differ; manual restoration required.')
                    if previous is None:
                        target.unlink()
                    else:
                        saved = backup / 'files' / name
                        replace_file(saved, target, stat.S_IMODE(saved.stat().st_mode))
                except Exception:
                    failed.append(name)
            if failed:
                raise RuntimeError(f'Installation interrupted. Manual restore from {backup} needed for: {", ".join(failed)}')
            print(f'Installation interrupted. Applied file writes were reversed. Backup: {backup}', file=sys.stderr)
            raise
        print(f'Installed {len(finished)} files. Verified originals are backed up at {backup}')
        print('No database migrations, builds, cache or environment changes were run.')
    finally:
        lock.rmdir()


if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, RuntimeError) as ex:
        print(f'ERROR: {ex}', file=sys.stderr)
        sys.exit(1)
