#!/usr/bin/python3
"""Explicit, stopped-service-only serial grants. Default is a read-only plan.

Does not start/restart a service, enumerate/open serial ports, install drivers,
delete backups, or change unrelated config. New grants expire on device identity
change (including replug). --test-pty is an expiring simulated-device grant.
"""
import argparse
import json
import os
from pathlib import Path
import pwd
import re
import stat
import subprocess
import time
import uuid


def run(*args):
    return subprocess.run(args, check=True, text=True, capture_output=True,
                          env=dict(os.environ, LC_ALL='C')).stdout


def pty_group_fallback(test_pty, error):
    return test_pty and isinstance(error, subprocess.CalledProcessError) and 'not supported' in (error.stderr or '').lower()


def exclusive_test_group(user, uid, gid, members, accounts):
    return all(member == user for member in members) and all(
        entry_gid != gid or entry_uid == uid for _, entry_uid, entry_gid in accounts)


def device_record(source, index, test_pty):
    path = Path(source).resolve(strict=True)
    pattern = r"/dev/pts/[0-9]+" if test_pty else r"/dev/tty(?:USB|ACM|S)[0-9]+"
    if not re.fullmatch(pattern, str(path)):
        raise ValueError("Only explicit ttyUSB/ttyACM/ttyS devices (or --test-pty /dev/pts/N) are allowed")
    info = path.stat()
    if not stat.S_ISCHR(info.st_mode):
        raise ValueError("Not a character device")
    return {"path": f"/dev/bdiiot-serial-{index}", "source": str(path),
            "rdev": info.st_rdev, "inode": info.st_ino, "filesystem": info.st_dev}


def make_policy(devices, uid, test_pty, now, lifetime):
    if not 1 <= len(devices) <= 16 or len({(d['rdev'], d['inode'], d['filesystem']) for d in devices}) != len(devices):
        raise ValueError("Require 1-16 distinct devices")
    if not 60 <= lifetime <= 86400:
        raise ValueError("Test grant lifetime must be 60..86400 seconds")
    return {"version": 1, "uid": uid, "test_pty": test_pty,
            "expires_at": now + lifetime if test_pty else 0, "devices": devices}


def unit_text(policy, policy_path):
    # One node per bind, not /dev. PrivateDevices and closed cgroup stay enabled.
    lines = ["# Generated by bdiiot-authorize-serial; restart after authorization.",
             "[Service]", "PrivateDevices=true", "DevicePolicy=closed",
             f'Environment="BDIIOT_SERIAL_POLICY={policy_path}"']
    for dev in policy['devices']:
        lines.extend([f"BindPaths={dev['source']}:{dev['path']}", f"DeviceAllow={dev['source']} rw"])
    return "\n".join(lines) + "\n"


def secure_directory(path):
    if path.exists():
        if path.is_symlink() or not path.is_dir():
            raise ValueError(f"Unsafe directory: {path}")
        info = path.stat()
        if info.st_uid != 0 or info.st_mode & 0o022:
            raise ValueError(f"Directory must be root owned, not group/world writable: {path}")
    else:
        path.mkdir(mode=0o755, parents=True)
    if path.resolve() != path:
        raise ValueError(f"Symlinked directory: {path}")


def publish(path, data, backup):
    if path.exists() or path.is_symlink():
        info = path.lstat()
        if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
            raise ValueError(f"Unsafe existing file: {path}")
        (backup / (path.name + '.before')).write_bytes(path.read_bytes())
    stage = path.with_name(path.name + '.new-' + uuid.uuid4().hex)
    fd = os.open(stage, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o644)
    with os.fdopen(fd, 'w') as handle:
        handle.write(data)
        handle.flush()
        os.fsync(handle.fileno())
    os.replace(stage, path)  # Only these generated files; old contents retained.


def generated_snapshot(path):
    if not path.exists() and not path.is_symlink():
        return None
    info = path.lstat()
    if not stat.S_ISREG(info.st_mode) or info.st_uid != 0 or info.st_mode & 0o022:
        raise ValueError(f'Unsafe existing file: {path}')
    return path.read_text()


def retain_file(path, backup, label):
    if path.exists() or path.is_symlink():
        generated_snapshot(path)
        os.replace(path, backup / (label + '-' + uuid.uuid4().hex))


def apply_device_grant(dev, uid, gid, test_pty, backup):
    index = int(dev['path'].rsplit('-', 1)[1])
    if device_record(dev['source'], index, test_pty) != dev:
        raise ValueError('Device identity changed during authorization')
    try:
        run('setfacl', '-m', f'u:{uid}:rw', dev['source'])
    except subprocess.CalledProcessError as error:
        if not pty_group_fallback(test_pty, error):
            raise ValueError(f"Device ACL grant failed: {(error.stderr or '').strip()}") from error
        os.chown(dev['source'], -1, gid)
        os.chmod(dev['source'], 0o660)
        print('Simulated PTY lacks ACL support; granted only its test-service group (0660).')
    if device_record(dev['source'], index, test_pty) != dev:
        raise ValueError('Device identity changed after authorization')


def restore_device_grant(dev, index, test_pty, backup):
    # Never restore permissions onto a different device that reused its name.
    if device_record(dev['source'], index, test_pty) != dev:
        raise ValueError(f"Cannot restore changed device: {dev['source']}")
    try:
        run('setfacl', '--restore=' + str(backup / f'device-{index}.acl'))
    except subprocess.CalledProcessError as error:
        if not pty_group_fallback(test_pty, error):
            raise
        meta = json.loads((backup / f'device-{index}.ownership.json').read_text())
        os.chown(dev['source'], meta['uid'], meta['gid'])
        os.chmod(dev['source'], meta['mode'])


def apply_grant_transaction(policy, policy_path, dropin, gid, backup):
    # Withdraw the old application gate first. An interruption or failed grant
    # must not leave the old policy paired with a new device binding/partial ACL.
    generated_snapshot(policy_path)
    previous_dropin = generated_snapshot(dropin)
    attempted = []
    retain_file(policy_path, backup, 'policy-disabled-before-apply')
    try:
        for index, dev in enumerate(policy['devices']):
            attempted.append((index, dev))
            apply_device_grant(dev, policy['uid'], gid, policy['test_pty'], backup)
        publish(dropin, unit_text(policy, policy_path), backup)
        run('systemctl', 'daemon-reload')
        # Final gate opens only after every device and the unit are ready.
        publish(policy_path, json.dumps(policy, ensure_ascii=False, indent=2) + '\n', backup)
    except (OSError, ValueError, subprocess.CalledProcessError) as error:
        failures = []
        try:
            retain_file(policy_path, backup, 'failed-policy')
        except (OSError, ValueError) as rollback:
            failures.append(f'policy gate: {rollback}')
        for index, dev in reversed(attempted):
            try:
                restore_device_grant(dev, index, policy['test_pty'], backup)
            except (OSError, ValueError, subprocess.CalledProcessError) as rollback:
                failures.append(f"{dev['source']}: {rollback}")
        try:
            retain_file(dropin, backup, 'failed-dropin')
            if previous_dropin is not None:
                publish(dropin, previous_dropin, backup)
            run('systemctl', 'daemon-reload')
        except (OSError, ValueError, subprocess.CalledProcessError) as rollback:
            failures.append(f'unit restoration: {rollback}')
        detail = '; '.join(failures) if failures else 'attempted device permissions and unit binding restored'
        raise ValueError(f'Grant failed ({error}); policy remains disabled. {detail}. '
                         f'Review retained backups and rerun authorization: {backup}') from error


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('devices', nargs='+')
    parser.add_argument('--apply', action='store_true')
    parser.add_argument('--test-pty', action='store_true')
    parser.add_argument('--lifetime', type=int, default=3600)
    parser.add_argument('--user', default='bdiiot-gateway')
    parser.add_argument('--unit', default='bdiiot-gateway.service')
    parser.add_argument('--policy', default='/etc/bdiiot-gateway/serial-policy.json')
    args = parser.parse_args()
    if os.geteuid() != 0:
        raise ValueError('Run as root; never setuid this script')
    if not re.fullmatch(r'[A-Za-z0-9_@.-]+\.service', args.unit):
        raise ValueError('Invalid unit name')
    policy_path = Path(args.policy)
    if not re.fullmatch(r'/[A-Za-z0-9_./-]+', args.policy) or '..' in policy_path.parts:
        raise ValueError('Policy path must be an absolute path without whitespace or dot-dot')
    account = pwd.getpwnam(args.user)
    uid = account.pw_uid
    if uid == 0:
        raise ValueError('The gateway must run as an unprivileged account')
    # Fail before changing anything, including ACLs. The administrator controls
    # when an existing service may be stopped and restarted.
    status = subprocess.run(['systemctl', 'is-active', '--quiet', args.unit])
    if status.returncode == 0:
        raise ValueError(f'Stop {args.unit} explicitly before applying device grants')
    if status.returncode not in (3, 4):
        raise ValueError('Cannot determine service state')
    configured_user = run('systemctl', 'show', args.unit, '--property=User', '--value').strip()
    if configured_user != args.user:
        raise ValueError('Unit User must match --user; create the isolated test unit first')
    configured_group = run('systemctl', 'show', args.unit, '--property=Group', '--value').strip()
    if configured_group and configured_group not in (args.user, str(account.pw_gid)):
        raise ValueError('Unit Group must match the authorized account primary group')
    if args.test_pty:
        import grp
        group = grp.getgrgid(account.pw_gid)
        if not exclusive_test_group(args.user, uid, account.pw_gid, group.gr_mem,
                                    [(p.pw_name, p.pw_uid, p.pw_gid) for p in pwd.getpwall()]):
            raise ValueError('Test PTY group must be exclusive to this test UID; shared groups are rejected')
    devices = [device_record(p, i, args.test_pty) for i, p in enumerate(args.devices)]
    policy = make_policy(devices, uid, args.test_pty, int(time.time()), args.lifetime)
    dropin = Path('/etc/systemd/system') / (args.unit + '.d') / '60-bdiiot-serial.conf'
    print(json.dumps(policy, ensure_ascii=False, indent=2))
    print(unit_text(policy, policy_path))
    if not args.apply:
        print('Read-only plan. Add --apply to grant ONLY these devices; no service will start.')
        return
    secure_directory(policy_path.parent)
    secure_directory(dropin.parent)
    backup = policy_path.parent / ('serial-grant-backup-' + uuid.uuid4().hex)
    backup.mkdir(mode=0o700)
    for i, dev in enumerate(devices):
        acl = run('getfacl', '--absolute-names', dev['source'])
        # Recalculating the ACL mask must not expose permissions deliberately
        # masked for another user/group. Ask the administrator to resolve it.
        if '#effective:' in acl:
            raise ValueError('Existing restricted ACL requires administrator review; no grant applied to this device')
        (backup / f'device-{i}.acl').write_text(acl)
        meta = os.stat(dev['source'])
        (backup / f'device-{i}.ownership.json').write_text(json.dumps({
            'path': dev['source'], 'uid': meta.st_uid, 'gid': meta.st_gid,
            'mode': stat.S_IMODE(meta.st_mode)}))
    apply_grant_transaction(policy, policy_path, dropin, account.pw_gid, backup)
    print(f'Authorized. Backups: {backup}')
    print(f'Next: sudo systemctl start {args.unit}; configure the /dev/bdiiot-serial-N alias shown above.')
    print('Unplug/replug or reboot: reauthorize while stopped. Revocation: stop service, retain/remove this policy and drop-in, then restore the saved ACLs after reviewing them. No backups are deleted automatically.')


if __name__ == '__main__':
    try:
        main()
    except (OSError, ValueError, subprocess.CalledProcessError) as error:
        raise SystemExit(f'No automatic service restart. Authorization failed: {error}')
