#!/usr/bin/python3
"""Prepare Maximizer's virtual camera using the distribution's prebuilt driver.

Called by the native package installer and an idempotent boot unit. No compiler,
kernel headers, DKMS, package-manager invocation or Host restart. An unused legacy
module with no virtual cameras can be reloaded to repair an earlier empty load.
The ioctl layouts are the stable userspace ABI in v4l2loopback.h (0.13–0.15).
"""
import argparse
import errno
import fcntl
import json
import os
from pathlib import Path
import pwd
import re
import stat
import struct
import subprocess
import tempfile

LABEL = b'Maximizer Camera'
STATE = Path('/var/lib/maximizer-camera')
VIDEO = Path('/sys/devices/virtual/video4linux')
ENV = {'PATH': '/usr/sbin:/usr/bin:/sbin:/bin', 'LC_ALL': 'C'}
QUERYCAP = 0x80685600  # _IOR('V', 0, struct v4l2_capability), 104 bytes
VERSION = 0x80047e00  # _IOR('~', 0, uint32_t)
ADD = 0x40487e01      # _IOW('~', 1, struct v4l2_loopback_config), 72 bytes
LEGACY_ADD = 0x4c80


def run(*args, pass_fds=()):
    return subprocess.run(args, check=True, capture_output=True, text=True,
                          timeout=15, env=ENV, pass_fds=pass_fds).stdout


def protected_directory(path):
    path.mkdir(mode=0o700, exist_ok=True)
    info = path.lstat()
    if not stat.S_ISDIR(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
        raise RuntimeError('Camera state directory is not private and root-owned')


def read_state(name, default):
    path = STATE / name
    try:
        fd = os.open(path, os.O_RDONLY | os.O_CLOEXEC | os.O_NOFOLLOW)
    except FileNotFoundError:
        return default
    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 setup state')
        return json.load(stream)


def write_state(name, value):
    fd, temporary = tempfile.mkstemp(prefix='.setup-', 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 users(register=None):
    names = read_state('users.json', [])
    if not isinstance(names, list) or len(names) > 64 or not all(isinstance(x, str) and re.fullmatch(r'[a-zA-Z_][a-zA-Z0-9_.-]*\$?', x) for x in names):
        raise RuntimeError('Invalid camera account list')
    if register:
        account = pwd.getpwnam(register)
        if account.pw_uid == 0 or not re.fullmatch(r'[a-zA-Z_][a-zA-Z0-9_.-]*\$?', register):
            raise RuntimeError('Camera access requires a non-root Host account')
        if register not in names:
            if len(names) >= 64:
                raise RuntimeError('Too many camera accounts')
            names.append(register)
            write_state('users.json', names)
    accounts = []
    for name in names:
        try:
            account = pwd.getpwnam(name)
        except KeyError:
            continue
        if account.pw_uid != 0:
            accounts.append(account.pw_uid)
    return sorted(set(accounts))


def open_camera(path):
    """Validate a dedicated virtual node without selecting a format or streaming."""
    if not re.fullmatch(r'/dev/video[0-9]+', str(path)):
        raise RuntimeError('Invalid virtual camera path')
    fd = os.open(path, os.O_RDWR | os.O_NONBLOCK | os.O_CLOEXEC | os.O_NOFOLLOW)
    try:
        info = os.fstat(fd)
        if not stat.S_ISCHR(info.st_mode) or os.major(info.st_rdev) != 81:
            raise RuntimeError('Camera is not a V4L2 character device')
        caps = bytearray(104)
        fcntl.ioctl(fd, QUERYCAP, caps)
        if caps[:16].split(b'\0', 1)[0] != b'v4l2 loopback' or caps[16:48].split(b'\0', 1)[0] != LABEL:
            raise RuntimeError('Camera is not the dedicated Maximizer receiver')
        return fd
    except BaseException:
        os.close(fd)
        raise


def find_camera():
    for entry in sorted(VIDEO.glob('video*')):
        if not re.fullmatch(r'video[0-9]+', entry.name):
            continue
        try:
            if (entry / 'name').read_text().strip() != LABEL.decode():
                continue
            path = '/dev/' + entry.name
            fd = open_camera(path)
            os.close(fd)
            return path
        except (OSError, RuntimeError):
            continue
    return None


def load_driver():
    loaded = Path('/sys/module/v4l2loopback').exists()
    if loaded:
        if Path('/dev/v4l2loopback').exists() or any(VIDEO.glob('video*')):
            return
        # Some distribution prebuilt drivers have no dynamic-control device.
        # Older Host setup loaded them with devices=0, leaving an inert module.
        # Never remove an existing camera, an open module, or configured user state.
        try:
            if Path('/sys/module/v4l2loopback/refcnt').read_text().strip() != '0':
                return
        except OSError:
            return
    # Preserve existing module options (for example an OBS virtual camera).
    # Create the named camera during a fresh load. This works with both static
    # distro drivers and newer drivers that additionally support dynamic creation.
    options = run('modprobe', '--showconfig')
    configured = any(re.match(r'\s*options\s+v4l2loopback(?:\s|$)', line) for line in options.splitlines())
    if loaded:
        if configured:
            return
        # Exact module only, no --force and no recursive dependency removal. The
        # kernel refuses the operation if a user acquires a reference meanwhile.
        run('rmmod', 'v4l2loopback')
    run('modprobe', 'v4l2loopback', *([] if configured else [
        'devices=1', 'card_label=Maximizer Camera', 'exclusive_caps=0']))
    run('udevadm', 'settle', '--timeout=10')


def create_camera():
    fd = os.open('/dev/v4l2loopback', os.O_RDWR | os.O_CLOEXEC | os.O_NOFOLLOW)
    try:
        if not stat.S_ISCHR(os.fstat(fd).st_mode):
            raise RuntimeError('Invalid virtual-camera control device')
        try:
            fcntl.ioctl(fd, VERSION, bytearray(4))
            request = ADD
        except OSError as error:
            if error.errno not in (errno.ENOTTY, errno.EINVAL):
                raise
            request = LEGACY_ADD
        # Driver allocates a free number atomically. No fixed /dev/video42 and no
        # deletion/reconfiguration of another application's existing device.
        config = bytearray(struct.pack('=ii32sIIIIiiii', -1, 0, LABEL,
                                       0, 4096, 0, 2160, 0, 0, 0, 0))
        number = fcntl.ioctl(fd, request, config)
        if not 0 <= number <= 1048575:
            raise RuntimeError('Invalid camera device number returned by driver')
    finally:
        os.close(fd)
    run('udevadm', 'settle', '--timeout=10')
    return '/dev/video' + str(number)


def prepare(accounts):
    path = find_camera()
    if not path:
        load_driver()
        path = find_camera() or create_camera()
    fd = open_camera(path)
    try:
        # A named ACL is effective immediately for an already logged-in Host user.
        # Boot repeats it, so no logout/group refresh or user configuration is needed.
        for uid in accounts:
            run('setfacl', '-m', 'u:' + str(uid) + ':rw', '--',
                '/proc/self/fd/' + str(fd), pass_fds=(fd,))
    finally:
        os.close(fd)
    return path


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--register-user', help='Host account selected by the package installer')
    args = parser.parse_args()
    if os.geteuid() != 0:
        parser.error('The camera setup helper must run as root')
    protected_directory(STATE)
    fd = os.open(STATE / 'setup.lock', os.O_RDWR | os.O_CREAT | os.O_CLOEXEC | os.O_NOFOLLOW, 0o600)
    try:
        fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
        try:
            path = prepare(users(args.register_user))
            status = {'state': 'ready', 'device': path, 'kernel': os.uname().release}
            write_state('status.json', status)
            print('Maximizer Camera is ready (' + path + ').')
            return 0
        except (OSError, RuntimeError, KeyError, ValueError, subprocess.SubprocessError) as error:
            write_state('status.json', {'state': 'unavailable', 'kernel': os.uname().release,
                                      'detail': str(error)[:1000]})
            print('Camera preparation is pending. Native Mint/Ubuntu installations install a missing supported driver automatically. See maximizer-camera.service for setup details.')
            return 1
    finally:
        os.close(fd)


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