#!/usr/bin/python3 -I
"""Bounded USB-CAN setup helper. Installed copy is root-owned and used by polkit."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import tempfile

CONFIG = Path('/etc/star-arm-lumos/can.json')
SYS_NET = Path('/sys/class/net')
IP = '/usr/sbin/ip'
BITRATE = 1_000_000


def device_identity(interface, sys_net=SYS_NET):
    if not isinstance(interface, str) or not re.fullmatch(r'[A-Za-z][A-Za-z0-9_.-]{0,14}', interface):
        raise ValueError('CAN 接口名称无效')
    node = sys_net / interface
    if (node / 'type').read_text().strip() != '280' or not (node / 'device').exists():
        raise ValueError('请选择真实 USB-CAN 接口')
    device = (node / 'device').resolve()
    channel = next((p.joinpath('bInterfaceNumber').read_text().strip()
                    for p in (device, *device.parents) if p.joinpath('bInterfaceNumber').is_file()), '')
    for parent in (device, *device.parents):
        if (parent / 'idVendor').is_file() and (parent / 'idProduct').is_file():
            serial_path = parent / 'serial'
            serial = serial_path.read_text().strip() if serial_path.is_file() else ''
            return {'vendor': (parent / 'idVendor').read_text().strip(),
                    'product': (parent / 'idProduct').read_text().strip(),
                    'serial': serial, 'channel': channel,
                    # Without a serial number, remember the physical USB socket.
                    'path': '' if serial else str(device),
                    'dev_id': (node / 'dev_id').read_text().strip() if (node / 'dev_id').is_file() else '',
                    'dev_port': (node / 'dev_port').read_text().strip() if (node / 'dev_port').is_file() else ''}
    raise ValueError('当前自动配置仅支持 USB-CAN；未识别到 USB 设备')


def read_links(runner=subprocess.run):
    result = runner([IP, '-details', '-json', 'link', 'show'], capture_output=True,
                    text=True, check=True, timeout=5)
    value = json.loads(result.stdout)
    if not isinstance(value, list):
        raise ValueError('CAN 状态格式无效')
    return value


def can_devices(runner=subprocess.run, sys_net=SYS_NET, config=CONFIG):
    try:
        saved = json.loads(config.read_text()).get('devices', [])
    except (OSError, ValueError, AttributeError):
        saved = []
    devices = []
    for link in read_links(runner):
        info = link.get('linkinfo', {})
        if info.get('info_kind') != 'can':
            continue
        name = link.get('ifname')
        bitrate = info.get('info_data', {}).get('bittiming', {}).get('bitrate')
        try:
            identity = device_identity(name, sys_net)
            supported, reason = True, ''
        except (OSError, ValueError) as error:
            identity, supported, reason = None, False, str(error)
        devices.append({'name': name, 'up': 'UP' in link.get('flags', []),
                        'bitrate': bitrate, 'ready': 'UP' in link.get('flags', []) and bitrate == BITRATE,
                        'supported': supported, 'reason': reason,
                        'saved': identity is not None and identity in saved,
                        'device_key': hashlib.sha256(json.dumps(identity, sort_keys=True).encode()).hexdigest() if identity else None,
                        'label': f"{name}" + (f" · USB {identity['vendor']}:{identity['product']}" if identity else '')})
    return devices


def configure(interface, *, restore=False, runner=subprocess.run, config=CONFIG, sys_net=SYS_NET):
    identity = device_identity(interface, sys_net)
    for other in sys_net.iterdir():
        if other.name == interface:
            continue
        try:
            duplicate = device_identity(other.name, sys_net) == identity
        except (OSError, ValueError):
            continue
        if duplicate:
            raise ValueError('无法唯一识别此 USB-CAN 通道，未修改接口。请使用有独立设备或通道标识的适配器。')
    try:
        saved = json.loads(config.read_text()).get('devices', [])
        if not isinstance(saved, list):
            raise ValueError('保存的 CAN 配置格式无效')
    except FileNotFoundError:
        saved = []
    if restore and identity not in saved:
        return False
    links = read_links(runner)
    link = next((item for item in links if item.get('ifname') == interface), None)
    if not link or link.get('linkinfo', {}).get('info_kind') != 'can':
        raise ValueError('CAN 设备已拔出，请重新检测')
    up = 'UP' in link.get('flags', [])
    bitrate = link.get('linkinfo', {}).get('info_data', {}).get('bittiming', {}).get('bitrate')
    if up and bitrate != BITRATE:
        raise ValueError('CAN 正以其他速率运行。请先在使用它的软件中停止并停用接口，再重试；助手不会强制中断它。')
    if not up:
        # Revalidate after enumeration; only configure the selected physical CAN.
        if device_identity(interface, sys_net) != identity:
            raise ValueError('USB-CAN 已变化，请重新检测')
        runner([IP, 'link', 'set', 'dev', interface, 'type', 'can', 'bitrate', str(BITRATE)],
               check=True, capture_output=True, text=True, timeout=5)
        runner([IP, 'link', 'set', 'dev', interface, 'up'],
               check=True, capture_output=True, text=True, timeout=5)
    checked = next((item for item in read_links(runner) if item.get('ifname') == interface), {})
    actual = checked.get('linkinfo', {}).get('info_data', {}).get('bittiming', {}).get('bitrate')
    if ('UP' not in checked.get('flags', []) or actual != BITRATE
            or device_identity(interface, sys_net) != identity):
        raise ValueError('CAN 配置后检查未通过，请检查设备和驱动')
    if not restore and identity not in saved:
        config.parent.mkdir(parents=True, exist_ok=True, mode=0o755)
        descriptor, temporary = tempfile.mkstemp(prefix='.can-', dir=config.parent)
        try:
            with os.fdopen(descriptor, 'w') as file:
                json.dump({'devices': [*saved, identity]}, file)
                file.flush()
                os.fsync(file.fileno())
                os.fchmod(file.fileno(), 0o644)
            os.replace(temporary, config)
        finally:
            if os.path.exists(temporary):
                os.unlink(temporary)
    return True


def main(argv=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('operation', choices=['configure', 'restore'])
    parser.add_argument('interface')
    args = parser.parse_args(argv)
    if os.geteuid() != 0:
        raise SystemExit('请通过系统授权配置 CAN')
    try:
        configure(args.interface, restore=args.operation == 'restore')
    except (OSError, ValueError, subprocess.SubprocessError) as error:
        print(str(error), flush=True)
        return 1
    return 0


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