#!/usr/bin/python3
"""Install a missing prebuilt camera driver after the Host package transaction.

Mint/Ubuntu publish signed, kernel-specific linux-modules packages. A separate
systemd worker avoids recursive apt/dpkg locks in postinst. Only module packages
for the running kernel are admitted; no headers, DKMS, kernel switch or module
unload. Existing working receivers take the fast path without package operations.
"""
import argparse
import errno
import fcntl
import hashlib
import json
import os
from pathlib import Path
import platform
import re
import stat
import subprocess
import tarfile
import tempfile
import time

STATE = Path('/var/lib/maximizer-camera')
SETUP = Path(__file__).with_name('maximizer-camera-setup')
ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C',
       'DEBIAN_FRONTEND': 'noninteractive', 'NEEDRESTART_MODE': 'l'}
LOCKS = ('/var/lib/dpkg/lock-frontend', '/var/lib/dpkg/lock',
         '/var/lib/apt/lists/lock', '/var/cache/apt/archives/lock')
APT_OPTIONS = ('-o', 'DPkg::Lock::Timeout=60', '-o', 'Acquire::Retries=2',
               '-o', 'Acquire::http::Timeout=30', '-o', 'Acquire::https::Timeout=30')


class ProvisionError(RuntimeError):
    def __init__(self, reason, message, retry=900):
        super().__init__(message)
        self.reason, self.retry = reason, retry


def execute(*args, timeout=60, cwd=None, check=True):
    result = subprocess.run(args, capture_output=True, text=True, timeout=timeout,
                            cwd=cwd, env=ENV)
    if check and result.returncode:
        # Package-manager output can include authenticated repository URLs. Store
        # a bounded, non-secret reason rather than copying that output to status.
        operation = next((arg for arg in args[1:] if arg in ('update', 'download', 'install')), 'command')
        raise ProvisionError('package-' + operation + '-failed',
                             Path(args[0]).name + ' ' + operation + ' could not complete camera driver installation.')
    return result


def private_state():
    STATE.mkdir(mode=0o700, exist_ok=True)
    info = STATE.lstat()
    if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
        raise RuntimeError('Invalid camera state directory')


def read_state(name):
    try:
        fd = os.open(STATE / name, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW)
    except FileNotFoundError:
        return {}
    with os.fdopen(fd) as stream:
        info = os.fstat(stream.fileno())
        if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022 or info.st_size > 16384:
            raise RuntimeError('Invalid camera installation state')
        value = json.load(stream)
        if not isinstance(value, dict):
            raise RuntimeError('Invalid camera installation state')
        return value


def write_state(name, value):
    fd, temporary = tempfile.mkstemp(prefix='.driver-', dir=STATE)
    try:
        with os.fdopen(fd, 'w') as stream:
            json.dump(value, stream, sort_keys=True); stream.write('\n')
            stream.flush(); os.fsync(stream.fileno())
        os.replace(temporary, STATE / name)
    finally:
        if os.path.exists(temporary):
            os.unlink(temporary)


def package_locks_free():
    opened = []
    try:
        for path in LOCKS:
            try:
                fd = os.open(path, os.O_RDWR | os.O_CLOEXEC | os.O_NOFOLLOW)
            except FileNotFoundError:
                continue
            opened.append(fd)
            try:
                fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except OSError as error:
                if error.errno in (errno.EACCES, errno.EAGAIN):
                    return False
                raise
        return True
    finally:
        for fd in opened:
            os.close(fd)


def wait_for_packages(seconds=180):
    deadline = time.monotonic() + seconds
    while not package_locks_free():
        if time.monotonic() >= deadline:
            raise ProvisionError('package-manager-busy',
                                 'Waiting for the system package installation to finish.', 60)
        time.sleep(1)


def module_present(kernel, name='v4l2loopback'):
    result = execute('modinfo', '-k', kernel, '-F', 'filename', name, check=False)
    filename = result.stdout.strip()
    return result.returncode == 0 and (filename == '(builtin)' or Path(filename).is_file())


def missing_components(kernel):
    # Ubuntu can put v4l2loopback in linux-modules while its V4L2 core is in
    # linux-modules-extra. Presence of the loopback file alone is insufficient.
    pending = ['v4l2loopback', 'videodev']
    seen, missing = set(), set()
    while pending:
        name = pending.pop().replace('-', '_')
        if name in seen:
            continue
        if not re.fullmatch(r'[A-Za-z0-9_]+', name) or len(seen) >= 64:
            raise ProvisionError('invalid-module-dependencies', 'Camera module dependencies are invalid.', 21600)
        seen.add(name)
        if not module_present(kernel, name):
            missing.add(name)
            continue
        dependencies = execute('modinfo', '-k', kernel, '-F', 'depends', name, check=False)
        if dependencies.returncode:
            missing.add(name)
            continue
        pending.extend(item.strip() for item in dependencies.stdout.split(',') if item.strip())
    return missing


def supported_system():
    os_release = platform.freedesktop_os_release()
    return os_release.get('ID') == 'ubuntu' or (
        os_release.get('ID') == 'linuxmint' and bool(os_release.get('UBUNTU_CODENAME')))


def candidates(kernel):
    if not re.fullmatch(r'[0-9][A-Za-z0-9.+_-]{0,127}', kernel):
        raise ProvisionError('unsupported-kernel', 'The running kernel has no supported package identifier.', 21600)
    return ['linux-modules-' + kernel, 'linux-modules-extra-' + kernel]


def candidate_version(package):
    result = execute('apt-cache', 'policy', package)
    match = re.search(r'^\s*Candidate:\s*(\S+)\s*$', result.stdout, re.M)
    if not match or match[1] == '(none)':
        return None
    if not re.fullmatch(r'[0-9][A-Za-z0-9.+:~_-]*', match[1]):
        raise ProvisionError('invalid-package-metadata', 'Camera package metadata is invalid.', 21600)
    return match[1]


def inspect_package(archive, package, version, architecture, kernel, directory,
                    wanted=('v4l2loopback', 'videodev', 'mc')):
    fields = {}
    key = None
    for line in execute('dpkg-deb', '-f', str(archive)).stdout.splitlines():
        if line and line[0].isspace() and key:
            fields[key] += ' ' + line.strip()
        elif line and ':' in line:
            key, value = line.split(':', 1); fields[key] = value.strip()
    if (fields.get('Package'), fields.get('Version'), fields.get('Architecture')) != (package, version, architecture):
        raise ProvisionError('invalid-package-metadata', 'Downloaded camera package identity does not match.', 21600)
    pattern = re.compile(r'(?:\./)?(?:usr/)?lib/modules/' + re.escape(kernel) + r'/.*/([A-Za-z0-9_-]+)\.ko(?:\.xz|\.zst|\.gz)?')
    wanted = {name.replace('-', '_') for name in wanted}
    modules = {}
    process = subprocess.Popen(['dpkg-deb', '--fsys-tarfile', str(archive)],
                               stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=ENV)
    try:
        with tarfile.open(fileobj=process.stdout, mode='r|') as bundle:
            for member in bundle:
                match = pattern.fullmatch(member.name)
                if not match or match[1].replace('-', '_') not in wanted:
                    continue
                name = match[1].replace('-', '_')
                if name in modules or not member.isfile() or member.size > 16 * 1024 * 1024:
                    raise ProvisionError('invalid-driver-payload', 'Camera package has an invalid module payload.', 21600)
                module = directory / Path(member.name).name
                with bundle.extractfile(member) as source, module.open('xb') as target:
                    target.write(source.read())
                modules[name] = module
        if process.wait(timeout=30):
            raise ProvisionError('invalid-driver-payload', 'Camera module package could not be inspected.')
    finally:
        process.stdout.close()
        if process.poll() is None:
            process.kill(); process.wait(timeout=10)
    hashes = {}
    for name, module in modules.items():
        magic = execute('modinfo', '-F', 'vermagic', str(module)).stdout.split()
        if not magic or magic[0] != kernel:
            raise ProvisionError('wrong-kernel-driver', 'Camera driver does not match the running kernel.', 21600)
        with module.open('rb') as stream:
            hashes[name] = hashlib.file_digest(stream, 'sha256').hexdigest()
    return {'modules': hashes, 'depends': fields.get('Depends', '')}


def support_dependencies(depends):
    # Ubuntu's modules-extra has a mandatory dependency on its regulatory
    # database, including on machines with no Wi-Fi. Admit it only when the
    # authenticated module package actually declares that dependency.
    return {'wireless-regdb'} if re.search(
        r'(?:^|,)\s*wireless-regdb(?::any)?(?:\s*\([^)]*\))?\s*(?=,|$)', depends) else set()


def support_requests(names):
    requests = []
    for name in sorted(names):
        installed = execute('dpkg-query', '-W', '-f=${Status}', name, check=False)
        if installed.returncode == 0 and installed.stdout.strip().endswith(' ok installed'):
            continue
        version = candidate_version(name)
        if not version:
            raise ProvisionError('prebuilt-dependency-unavailable',
                                 'A required kernel package dependency is unavailable in the system repositories.', 21600)
        # When a missing module already breaks the installed image dependency,
        # APT requires the complete solution explicitly, including support data.
        requests.append(name + '=' + version)
    return requests


def validate_plan(output, package, allowed):
    operations = []
    for line in output.splitlines():
        match = re.match(r'^(Inst|Conf|Remv|Purg)\s+(\S+)', line)
        if not match:
            continue
        operation, name = match[1], match[2].split(':', 1)[0]
        if operation not in ('Inst', 'Conf') or name not in allowed:
            raise ProvisionError('unrelated-package-changes',
                                 'The package manager requires changes outside this kernel camera package.', 21600)
        operations.append((operation, name))
    if ('Inst', package) not in operations:
        raise ProvisionError('invalid-install-plan', 'Camera package installation could not be confirmed.')


def install_driver(kernel):
    packages = candidates(kernel)
    wait_for_packages()
    audit = execute('dpkg', '--audit')
    if audit.stdout.strip():
        raise ProvisionError('package-manager-needs-repair',
                             'Existing system package errors prevent automatic camera installation.', 21600)
    execute('apt-get', *APT_OPTIONS, '-o', 'APT::Update::Error-Mode=any', 'update', timeout=240)
    architecture = execute('dpkg', '--print-architecture').stdout.strip()
    needed = missing_components(kernel)
    selected, expected_modules, support = [], {}, set()
    with tempfile.TemporaryDirectory(prefix='download-', dir=STATE) as temporary:
        directory = Path(temporary)
        for package in packages:
            if not needed:
                break
            version = candidate_version(package)
            if not version:
                continue
            # apt authenticates the package against the configured signed indexes.
            # Download first so the exact kernel ABI is checked before installation.
            before = set(directory.glob('*.deb'))
            execute('apt-get', *APT_OPTIONS, 'download', package + '=' + version,
                    cwd=directory, timeout=240)
            archives = list(set(directory.glob('*.deb')) - before)
            if len(archives) != 1 or archives[0].stat().st_size > 512 * 1024 * 1024:
                raise ProvisionError('invalid-driver-payload', 'Camera package download is invalid.')
            archive = archives[0]
            probe = directory / package
            probe.mkdir(mode=0o700)
            inspected = inspect_package(archive, package, version, architecture, kernel, probe,
                                        wanted=needed | {'v4l2loopback', 'videodev', 'mc'})
            if not needed.intersection(inspected['modules']):
                continue
            with archive.open('rb') as stream:
                archive_sha256 = hashlib.file_digest(stream, 'sha256').hexdigest()
            selected.append({'package': package, 'version': version, 'sha256': archive_sha256})
            expected_modules.update(inspected['modules'])
            needed.difference_update(inspected['modules'])
            support.update(support_dependencies(inspected['depends']))
        if needed or not selected:
            raise ProvisionError('prebuilt-driver-unavailable',
                                 'The system repositories have no complete prebuilt camera stack for this kernel.', 21600)
        install = ('apt-get', *APT_OPTIONS, '--no-install-recommends', '--no-remove',
                   '--reinstall', '-o', 'Dpkg::Options::=--force-confold',
                   '-o', 'Dir::Cache::archives=' + str(directory), 'install',
                   *(item['package'] + '=' + item['version'] for item in selected),
                   *support_requests(support))
        # Named, pinned packages resolve missing kernel-image dependencies. The
        # private cache reuses authenticated bytes instead of relying on local-deb
        # resolution. Install loopback and missing V4L2 dependencies together.
        plan = execute(*install[:1], '--simulate', *install[1:], timeout=60)
        for item in selected:
            validate_plan(plan.stdout, item['package'], set(packages) | support)
        wait_for_packages()
        if execute('dpkg', '--audit').stdout.strip():
            raise ProvisionError('package-manager-needs-repair', 'System package state changed during camera preparation.')
        execute(*install[:1], '--yes', *install[1:], timeout=360)
        execute('depmod', '-a', kernel, timeout=60)
        if missing_components(kernel):
            raise ProvisionError('driver-not-installed', 'The installed camera module dependencies could not be found.')
        for name, expected in expected_modules.items():
            installed = Path(execute('modinfo', '-k', kernel, '-F', 'filename', name).stdout.strip())
            with installed.open('rb') as stream:
                if hashlib.file_digest(stream, 'sha256').hexdigest() != expected:
                    raise ProvisionError('installed-driver-mismatch',
                                         'The selected camera module differs from the verified package.', 21600)
        return {**selected[0], 'packages': selected, 'modules': expected_modules, 'support_packages': sorted(support)}


def provision():
    kernel = os.uname().release
    # Setup is safe while streaming: it reuses the receiver without changing format.
    if execute(str(SETUP), timeout=60, check=False).returncode == 0:
        previous = read_state('driver.json')
        ready = {'state': 'ready', 'kernel': kernel}
        if previous.get('kernel') == kernel and previous.get('state') == 'ready' and 'installed' in previous:
            ready['installed'] = previous['installed']
        write_state('driver.json', ready)
        return 0
    installer = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
    previous = read_state('driver.json')
    if previous.get('kernel') == kernel and previous.get('installer') == installer and previous.get('retry_after', 0) > time.time():
        return 0
    try:
        if not missing_components(kernel):
            raise ProvisionError('driver-load-failed',
                                 'The camera driver is installed but could not be loaded or prepared.', 21600)
        if not supported_system():
            raise ProvisionError('unsupported-package-provider',
                                 'Automatic driver package installation is supported on Ubuntu and Ubuntu-based Linux Mint.', 21600)
        write_state('status.json', {'state': 'installing', 'kernel': kernel,
                                   'detail': 'Installing the camera driver automatically.'})
        package = install_driver(kernel)
        if execute(str(SETUP), timeout=60, check=False).returncode:
            raise ProvisionError('driver-load-failed',
                                 'The camera driver was installed but could not be loaded or prepared.', 21600)
        write_state('driver.json', {'state': 'ready', 'kernel': kernel, 'installed': package})
        print('Maximizer Camera driver installed and receiver prepared.')
        return 0
    except (ProvisionError, subprocess.TimeoutExpired, OSError) as error:
        reason = getattr(error, 'reason', 'installation-interrupted')
        detail = str(error) if isinstance(error, ProvisionError) else 'Camera installation was interrupted and will retry automatically.'
        value = {'state': 'waiting' if reason == 'package-manager-busy' else 'unavailable',
                 'kernel': kernel, 'reason': reason, 'detail': detail}
        write_state('status.json', value)
        write_state('driver.json', {**value, 'installer': installer,
                                   'retry_after': time.time() + getattr(error, 'retry', 900)})
        print(detail)
        return 1


def main():
    argparse.ArgumentParser(description=__doc__).parse_args()
    if os.geteuid() != 0:
        raise SystemExit('Camera driver installation requires root')
    private_state()
    fd = os.open(STATE / 'driver.lock', os.O_RDWR | os.O_CREAT | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600)
    try:
        try:
            fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return 0
        return provision()
    finally:
        os.close(fd)


if __name__ == '__main__':
    raise SystemExit(main())
