#!/usr/bin/python3 -I
"""Explicitly opted-in, Quest-only APT/DNF updates. No Arch or Omarchy actions."""
import fcntl
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import sys
import tempfile
import time
import types

HELPER = Path('/opt/Quest/resources/linux-updater/quest-package-update')
RUNNER = Path('/opt/Quest/resources/linux-updater/quest-package-auto-update')
POLICY = Path('/etc/quest/automatic-updates.json')
LOCK = Path('/run/quest-package-auto-update/lock')
ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'HOME': '/root', 'LC_ALL': 'C', 'DEBIAN_FRONTEND': 'noninteractive'}
MAX_PACKAGE = 1024 ** 3


class Refused(Exception):
    pass


def require(value, code):
    if not value:
        raise Refused(code)


def root_bytes(path, limit=262144):
    require(path.is_absolute() and path.resolve() == path, 'unsafe-path')
    for parent in path.parents:
        info = parent.stat()
        require(info.st_uid == 0 and stat.S_ISDIR(info.st_mode) and not info.st_mode & 0o022, 'unsafe-directory')
    fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
    try:
        info = os.fstat(fd)
        require(stat.S_ISREG(info.st_mode) and info.st_uid == 0 and info.st_nlink == 1
                and not info.st_mode & 0o022 and 0 < info.st_size <= limit, 'unsafe-file')
        raw = os.read(fd, limit + 1)
        require(len(raw) == info.st_size, 'file-changed')
        return raw
    finally:
        os.close(fd)


def load_tooling(route, read=root_bytes, run=None):
    # Authenticate the module before executing it; then verify the complete closed inventory.
    import types
    run = native_query if run is None else run
    directory = Path('/opt/Quest/resources/linux-updater')
    manifest_path, module_path = directory / 'manifest.json', directory / 'quest-package-tooling.py'
    for path in (manifest_path, module_path):
        require(path.resolve() == path, 'unsafe-tooling-path')
        for parent in path.parents:
            info = parent.stat()
            require(stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022, 'unsafe-tooling-directory')
    manifest = json.loads(read(manifest_path))
    require(isinstance(manifest, dict) and set(manifest) == {'schema', 'kind', 'files'}
            and type(manifest['schema']) is int and manifest['schema'] == 1 and manifest['kind'] == 'quest-linux-package-tooling'
            and isinstance(manifest['files'], dict) and set(manifest['files']) == {
                'quest-package-update', 'quest-package-auto-update', 'quest-package-tooling.py',
                'quest-package-auto-update.service', 'quest-package-auto-update.timer'}, 'tooling-manifest')
    row = manifest['files']['quest-package-tooling.py']
    raw = read(module_path)
    require(isinstance(row, dict) and set(row) == {'sha256', 'bytes', 'mode'}
            and row['bytes'] == len(raw) and row['sha256'] == hashlib.sha256(raw).hexdigest()
            and row['mode'] == 0o755 and stat.S_IMODE(module_path.stat().st_mode) == 0o755,
            'tooling-module-changed')
    for path in (manifest_path, module_path):
        if route == 'apt':
            result, expected = run(['/usr/bin/dpkg-query', '-S', str(path)]), 'quest: ' + str(path)
        elif route == 'dnf':
            result, expected = run(['/usr/bin/rpm', '-qf', '--qf', '%{NAME}', str(path)]), 'quest'
        else:
            require(route == 'pacman', 'installation-route')
            result, expected = run(['/usr/bin/pacman', '-Qoq', str(path)]), 'quest'
        require(result == expected, 'tooling-package-owner')
    module = types.ModuleType('quest_package_tooling')
    exec(compile(raw, str(module_path), 'exec'), module.__dict__)
    module.verify_tooling(route, read, run)
    return module


def native_query(args):
    result = subprocess.run(args, stdin=subprocess.DEVNULL, capture_output=True, timeout=30, env=ENV)
    require(result.returncode == 0 and len(result.stdout) <= 8192 and len(result.stderr) <= 8192, 'package-query-failed')
    return result.stdout.decode('utf8').strip()


def policy(raw):
    value = json.loads(raw)
    require(isinstance(value, dict) and set(value) == {'schema', 'enabled', 'route', 'tooling'}
            and type(value['schema']) is int and value['schema'] == 2 and type(value['enabled']) is bool
            and value['route'] in ('apt', 'dnf') and value['tooling'] == 'native-package', 'policy-invalid')
    return value


def processes_idle(proc=Path('/proc')):
    # Root must be able to inspect every live executable. Unknown means skip, never guess idle.
    try:
        for item in proc.iterdir():
            if not item.name.isdecimal():
                continue
            try:
                executable = os.readlink(item / 'exe')
            except (FileNotFoundError, ProcessLookupError):
                continue
            except OSError:
                return False
            if executable in ('/opt/Quest/quest', '/opt/Quest/quest (deleted)'):
                return False
        return True
    except OSError:
        return False


def apt_transaction(text, target):
    # LC_ALL=C apt simulation is evidence only. dpkg later installs exactly the downloaded file,
    # so a concurrent solver change cannot silently add other packages to the actual mutation.
    changes = [line for line in text.splitlines() if re.match(r'^(Inst|Remv|Conf)\s', line)]
    installs = [line for line in changes if line.startswith('Inst ')]
    require(len(installs) == 1 and re.fullmatch(r'Inst quest(?: \[[^\]\r\n]+\])? \(' + re.escape(target) + r' [^\r\n]+\)', installs[0]), 'manual-update-required')
    require(all(line.startswith('Inst quest ') or line.startswith('Conf quest ') for line in changes), 'manual-update-required')
    require(not re.search(r'(?im)^(?:Remv|Purg)\s', text), 'manual-update-required')
    return True


def package_file(directory, suffix):
    files = list(Path(directory).iterdir())
    require(len(files) == 1 and files[0].suffix == suffix, 'download-scope')
    info = files[0].lstat()
    require(stat.S_ISREG(info.st_mode) and info.st_uid == 0 and info.st_nlink == 1
            and 0 < info.st_size <= MAX_PACKAGE, 'download-invalid')
    return files[0]


def rpm_identity(text, version):
    # Empty obsoletes prevents a single Quest RPM from implicitly replacing another package.
    require(text.strip() == 'quest|x86_64|' + version + '|', 'rpm-identity')


def dnf_candidate(text):
    lines = text.strip().splitlines()
    require(len(lines) == 1, 'candidate-ambiguous')
    match = re.fullmatch(r'quest\|(\d+\.\d+\.\d+-[1-9]\d*)\|x86_64\|quest', lines[0])
    require(match, 'candidate-origin')
    return match.group(1)


def newer_native(candidate, current):
    def parts(value):
        match = re.fullmatch(r'(\d+)\.(\d+)\.(\d+)(?:-([1-9]\d*))?', value)
        require(match, 'native-version-invalid')
        return tuple(int(part or 0) for part in match.groups())
    candidate_parts, current_parts = parts(candidate), parts(current)
    # Only the exact installed identity is a healthy no-op; an older selection or
    # a different spelling of the same version must not hide repository drift.
    require(candidate == current or candidate_parts > current_parts, 'package-downgrade-refused')
    return candidate != current


def run_effect(args):
    # Never terminate dpkg/rpm halfway through a transaction. Timer disable stops future starts;
    # an already-started, single-package transaction is allowed to finish.
    result = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                            stderr=subprocess.DEVNULL, env=ENV, check=False)
    require(result.returncode == 0, 'package-update-failed')


def update(helper, route, initial, selected, before_effect):
    def recheck():
        before_effect()
        require(selected['_repositoryValidUntil'] > time.time(), 'stage-expired')
    def commit(args):
        recheck()
        run_effect(args)
    with tempfile.TemporaryDirectory(prefix='quest-auto-') as directory:
        os.chmod(directory, 0o700)
        if route == 'apt':
            safe = ['-o', 'Acquire::AllowInsecureRepositories=false', '-o', 'Acquire::AllowDowngradeToInsecureRepositories=false',
                    '-o', 'APT::Get::AllowUnauthenticated=false']
            helper.command(['/usr/bin/apt-get', *safe, '-o', 'Dir::Etc::sourcelist=/etc/apt/sources.list.d/quest.sources',
                            '-o', 'Dir::Etc::sourceparts=-', 'update'], timeout=180)
            candidate = helper.apt_candidate(helper.command(['/usr/bin/apt-cache', 'policy', 'quest']))
            expected = selected['version'] + ('-' + selected['build'] if selected.get('releaseSet', {}).get('revision') else '')
            require(candidate == expected, 'package-selection-changed')
            if not newer_native(candidate, initial['nativeVersion']):
                recheck()
                return None
            simulated = helper.command(['/usr/bin/apt-get', *safe, '--simulate', '--no-remove', 'install', '--only-upgrade', 'quest=' + candidate])
            apt_transaction(simulated, candidate)
            # apt-get download authenticates the selected package against signed cached metadata.
            previous = os.getcwd()
            try:
                os.chdir(directory)
                helper.command(['/usr/bin/apt-get', *safe, 'download', 'quest=' + candidate], timeout=600)
            finally:
                os.chdir(previous)
            package = package_file(directory, '.deb')
            verify_payload(package, selected, '.deb')
            require(helper.command(['/usr/bin/dpkg-deb', '--show', '--showformat=${Package}|${Architecture}|${Version}', str(package)])
                    == 'quest|amd64|' + candidate, 'deb-identity')
            helper.command(['/usr/bin/dpkg', '--no-act', '--refuse-downgrade', '--install', str(package)])
            commit(['/usr/bin/dpkg', '--refuse-downgrade', '--install', str(package)])
        else:
            safe = ['--disablerepo=*', '--enablerepo=quest', '--setopt=gpgcheck=1', '--setopt=repo_gpgcheck=1', '--setopt=localpkg_gpgcheck=1']
            candidate = dnf_candidate(helper.command(['/usr/bin/dnf', *safe, '--refresh', 'repoquery', '--latest-limit=1',
                '--queryformat', '%{name}|%{version}-%{release}|%{arch}|%{repoid}', 'quest'], timeout=180))
            expected = selected['version'] + '-' + (selected['build'] if selected.get('releaseSet', {}).get('revision') else '1')
            require(candidate == expected, 'package-selection-changed')
            if not newer_native(candidate, initial['nativeVersion']):
                recheck()
                return None
            helper.command(['/usr/bin/dnf', *safe, 'download', '--destdir', directory, 'quest-' + candidate + '.x86_64'], timeout=600)
            package = package_file(directory, '.rpm')
            verify_payload(package, selected, '.rpm')
            rpm_identity(helper.command(['/usr/bin/rpm', '-qp', '--qf', '%{NAME}|%{ARCH}|%{VERSION}-%{RELEASE}|[%{OBSOLETENAME}]', str(package)]), candidate)
            helper.command(['/usr/bin/rpm', '--checksig', str(package)])
            helper.command(['/usr/bin/rpm', '--test', '--upgrade', str(package)])
            # All repositories disabled: only the exact local Quest package can change. Missing
            # dependencies or conflicts fail rather than authorizing unrelated upgrades/removals.
            commit(['/usr/bin/dnf', '--disablerepo=*', '--setopt=localpkg_gpgcheck=1', '--setopt=install_weak_deps=False',
                        '--assumeyes', 'upgrade', str(package)])
        return candidate


def verify_payload(path, selected, suffix):
    assets = [asset for asset in selected['assets'] if isinstance(asset, dict) and str(asset.get('name', '')).endswith(suffix)]
    require(len(assets) == 1 and assets[0].get('size') == path.stat().st_size, 'payload-size')
    sha = hashlib.sha256()
    with path.open('rb') as stream:
        while chunk := stream.read(1024 * 1024):
            sha.update(chunk)
    require(sha.hexdigest() == assets[0].get('sha256'), 'payload-digest')


def main():
    require(os.getuid() == 0 and os.geteuid() == 0 and len(sys.argv) == 1, 'root-service-required')
    settings = policy(root_bytes(POLICY))
    if not settings['enabled']:
        return {'status': 'disabled'}
    tooling = load_tooling(settings['route'])
    manifest = tooling.verify_tooling(settings['route'])
    helper_bytes = root_bytes(HELPER)
    helper_row = manifest['files']['quest-package-update']
    require(len(helper_bytes) == helper_row['bytes'] and hashlib.sha256(helper_bytes).hexdigest() == helper_row['sha256'], 'helper-changed')
    helper = types.ModuleType('quest_package_update')
    exec(compile(helper_bytes, str(HELPER), 'exec'), helper.__dict__)
    route, distro = helper.validate_receipt(json.loads(helper.root_file(helper.RECEIPT)))
    require(route == settings['route'] and route in ('apt', 'dnf') and distro == 'other', 'automatic-route-refused')
    require(LOCK.parent.resolve() == LOCK.parent, 'lock-directory-invalid')
    for parent in (LOCK.parent, *LOCK.parent.parents):
        info = parent.stat()
        require(stat.S_ISDIR(info.st_mode) and info.st_uid == 0 and not info.st_mode & 0o022,
                'lock-directory-invalid')
    require(LOCK.parent.stat().st_mode & 0o777 == 0o700, 'lock-directory-invalid')
    fd = os.open(LOCK, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
    try:
        info = os.fstat(fd)
        require(stat.S_ISREG(info.st_mode) and info.st_uid == 0 and info.st_nlink == 1 and not info.st_mode & 0o077, 'lock-invalid')
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        if not processes_idle():
            return {'status': 'skipped', 'reason': 'application-running-or-unobservable'}
        initial = helper.installed_version(route)
        selected = helper.verified_candidate(route)
        def before_effect():
            require(policy(root_bytes(POLICY)) == settings and settings['enabled'], 'policy-changed')
            require(helper.validate_receipt(json.loads(helper.root_file(helper.RECEIPT))) == (route, distro), 'installation-changed')
            require(helper.installed_version(route) == initial, 'package-changed')
            require(processes_idle(), 'application-running-or-unobservable')
        candidate = update(helper, route, initial, selected, before_effect)
        if candidate is None:
            return {'status': 'skipped', 'reason': 'no-newer-package', 'route': route}
        require(helper.installed_version(route)['nativeVersion'] == candidate, 'post-update-identity')
        require(helper.validate_receipt(json.loads(helper.root_file(helper.RECEIPT))) == (route, distro), 'post-update-tooling-unconfirmed')
        return {'status': 'updated', 'route': route}
    finally:
        os.close(fd)


def cli():
    try:
        print(json.dumps(main(), sort_keys=True))
        return 0
    except Exception:
        print(json.dumps({'status': 'skipped', 'reason': 'manual-update-required'}))
        return 1


if __name__ == '__main__':
    sys.exit(cli())
