#!/usr/bin/python3
"""Restricted root helper for AI Station Portal v0.8."""
import fcntl, base64, json, os, re, subprocess, sys, ipaddress, time
from pathlib import Path
from zoneinfo import available_timezones

STATE_DIR = Path('/var/lib/ai-station-portal')
STATE = STATE_DIR / 'network-try.json'
DBUS_SERVICE = 'io.netplan.Netplan'
DBUS_ROOT = '/io/netplan/Netplan'
DBUS_IFACE = 'io.netplan.Netplan'
DBUS_CONFIG_IFACE = 'io.netplan.Netplan.Config'
NETPLAN_TIMEOUT = 120

def run(*args, timeout=30):
    return subprocess.run(args, check=True, timeout=timeout, capture_output=True, text=True)

def write(path, data, mode=0o600):
    path.parent.mkdir(parents=True, exist_ok=True)
    tmp = path.with_suffix(path.suffix + '.tmp')
    tmp.write_text(data)
    os.chmod(tmp, mode)
    os.replace(tmp, path)

def busctl(*args, timeout=15):
    return subprocess.run(
        ['/usr/bin/busctl', '--system', *args],
        check=True, timeout=timeout, capture_output=True, text=True
    ).stdout.strip()


def dbus_config_create():
    output = busctl('call', DBUS_SERVICE, DBUS_ROOT, DBUS_IFACE, 'Config')
    match = re.fullmatch(r'o "(/io/netplan/Netplan/config/[A-Z0-9]+)"', output)
    if not match:
        raise RuntimeError(f'Unexpected Netplan D-Bus Config response: {output}')
    return match.group(1)


def dbus_config_call(obj, method, *signature_and_values, timeout=15):
    output = busctl(
        'call', DBUS_SERVICE, obj, DBUS_CONFIG_IFACE, method,
        *signature_and_values, timeout=timeout
    )
    if output != 'b true':
        raise RuntimeError(f'Netplan D-Bus {method} failed: {output}')
    return True


def dbus_object_exists(obj):
    result = subprocess.run(
        ['/usr/bin/busctl', '--system', 'introspect', DBUS_SERVICE, obj],
        capture_output=True, text=True, timeout=8, check=False
    )
    return result.returncode == 0


def network_apply(encoded):
    """Create an isolated Netplan config and start its native Try transaction."""
    lock_path = Path('/run/lock/ai-station-network.lock')
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    with lock_path.open('w') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        return _network_apply_locked(encoded)


def _network_apply_locked(encoded):
    if STATE.exists():
        old = json.loads(STATE.read_text())
        if dbus_object_exists(old.get('object', '')):
            raise ValueError('A network change is already pending')
        STATE.unlink(missing_ok=True)

    cfg = json.loads(base64.urlsafe_b64decode(encoded.encode()).decode())
    if cfg.get('mode') not in ('dhcp', 'static'):
        raise ValueError('Invalid mode')

    current = subprocess.check_output(
        ['/usr/sbin/netplan', 'get', 'network.ethernets.lan0'],
        text=True, timeout=10
    )
    mac_match = re.search(
        r'^\s*macaddress:\s*"?([0-9a-fA-F]{2}(?::[0-9a-fA-F]{2}){5})',
        current, re.MULTILINE
    )
    mac = mac_match.group(1) if mac_match else Path(
        '/sys/class/net/lan0/address'
    ).read_text().strip()
    if not re.fullmatch(r'(?:[0-9a-fA-F]{2}:){5}[0-9a-fA-F]{2}', mac):
        raise ValueError('Invalid interface MAC')

    # Netplan D-Bus Set() merges YAML values. Empty arrays do not reliably
    # replace inherited lists, so remove the existing keys with NULL first.
    # This prevents old addresses, routes and DNS entries accumulating.
    deltas = [
        f'network.ethernets.lan0.match.macaddress="{mac.lower()}"',
        'network.ethernets.lan0.set-name=lan0',
        'network.ethernets.lan0.dhcp4=' + ('true' if cfg['mode'] == 'dhcp' else 'false'),
        'network.ethernets.lan0.addresses=NULL',
        'network.ethernets.lan0.routes=NULL',
        'network.ethernets.lan0.nameservers.addresses=NULL',
        'network.ethernets.lan0.nameservers.search=NULL',
    ]
    if cfg['mode'] == 'static':
        interface = ipaddress.ip_interface(cfg['address'])
        gateway = ipaddress.ip_address(cfg['gateway'])
        if interface.version != 4 or gateway.version != 4 or gateway not in interface.network:
            raise ValueError('Invalid IPv4 network')
        deltas.extend([
            f'network.ethernets.lan0.addresses=["{interface}"]',
            f'network.ethernets.lan0.routes=[{{to: default, via: {gateway}}}]',
        ])
        dns = []
        for value in (cfg.get('dns1'), cfg.get('dns2')):
            if value:
                dns_ip = ipaddress.ip_address(value)
                if dns_ip.version != 4:
                    raise ValueError('DNS must be IPv4')
                dns.append(str(dns_ip))
        deltas.append('network.ethernets.lan0.nameservers.addresses=[' + ', '.join('"'+x+'"' for x in dns) + ']')
        domain = cfg.get('search_domain', '').strip()
        if domain:
            labels = domain.rstrip('.').split('.')
            if len(domain) > 253 or any(not re.fullmatch(r'(?i)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', x) for x in labels):
                raise ValueError('Invalid search domain')
            domain = '.'.join(labels)
            deltas.append('network.ethernets.lan0.nameservers.search=["' + domain + '"]')
        else:
            deltas.append('network.ethernets.lan0.nameservers.search=[]')
    else:
        # Explicitly clear static properties inherited from the existing profile.
        deltas.extend([
        ])

    obj = dbus_config_create()
    try:
        for delta in deltas:
            dbus_config_call(obj, 'Set', 'ss', delta, '50-cloud-init')

        # Validate the merged candidate before touching the live network.
        merged = busctl('call', DBUS_SERVICE, obj, DBUS_CONFIG_IFACE, 'Get', timeout=10)
        if 'lan0' not in merged:
            raise RuntimeError('Candidate Netplan configuration does not contain lan0')

        expected = '' if cfg['mode'] == 'dhcp' else str(interface)
        state = {
            'object': obj,
            'started_at': time.time(),
            'timeout': NETPLAN_TIMEOUT,
            'expected_address': expected,
            'mode': cfg['mode'],
            'phase': 'starting',
        }
        STATE_DIR.mkdir(parents=True, exist_ok=True)
        write(STATE, json.dumps(state), 0o600)

        # D-Bus Try() starts netplan try and returns once its ready stamp exists.
        dbus_config_call(obj, 'Try', 'u', str(NETPLAN_TIMEOUT), timeout=20)
        state['phase'] = 'pending'
        write(STATE, json.dumps(state), 0o600)
        return 0
    except Exception:
        # Cancel discards an un-applied object, or rejects a Try already started.
        try:
            if dbus_object_exists(obj):
                dbus_config_call(obj, 'Cancel', timeout=25)
        except Exception as cancel_error:
            print(f'Netplan cleanup warning: {cancel_error}', file=sys.stderr)
        STATE.unlink(missing_ok=True)
        raise


def network_status():
    address = ''
    try:
        result = subprocess.run(
            ['/usr/sbin/ip', '-o', '-4', 'addr', 'show', 'dev', 'lan0', 'scope', 'global'],
            capture_output=True, text=True, timeout=5, check=False
        )
        match = re.search(r'\binet\s+(\d{1,3}(?:\.\d{1,3}){3}/\d+)', result.stdout)
        if result.returncode == 0 and match:
            address = match.group(1)
    except (subprocess.TimeoutExpired, OSError):
        pass

    if not STATE.exists():
        print(json.dumps({'pending': False, 'remaining_seconds': 0, 'try_active': False, 'timer_active': False,
                          'rollback_failed': False, 'address': address}))
        return 0

    try:
        state = json.loads(STATE.read_text())
        obj = state.get('object', '')
        active = bool(state.get('phase') == 'pending' and obj and dbus_object_exists(obj))
        if state.get('phase') == 'starting' and obj and dbus_object_exists(obj):
            # A helper crash before Try() became ready must not look like a live transaction.
            try:
                dbus_config_call(obj, 'Cancel', timeout=10)
            except Exception:
                pass
    except Exception:
        state, active = {}, False

    if not active:
        STATE.unlink(missing_ok=True)
        print(json.dumps({'pending': False, 'remaining_seconds': 0, 'try_active': False, 'timer_active': False,
                          'rollback_failed': False, 'address': address}))
        return 0

    elapsed = max(0, int(time.time() - float(state.get('started_at', time.time()))))
    remaining = max(0, int(state.get('timeout', NETPLAN_TIMEOUT)) - elapsed)
    print(json.dumps({'pending': True, 'remaining_seconds': remaining,
                      'try_active': True, 'timer_active': True, 'rollback_failed': False,
                      'address': address, 'expected_address': state.get('expected_address', '')}))
    return 0


def network_confirm():
    lock_path = Path('/run/lock/ai-station-network.lock')
    lock_path.parent.mkdir(parents=True, exist_ok=True)
    with lock_path.open('w') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        if not STATE.exists():
            raise RuntimeError('No pending Netplan configuration')
        state = json.loads(STATE.read_text())
        obj = state.get('object', '')
        if not obj or not dbus_object_exists(obj):
            STATE.unlink(missing_ok=True)
            raise RuntimeError('Netplan Try has already ended or rolled back')

        expected = state.get('expected_address', '')
        current = subprocess.run(
            ['/usr/sbin/ip', '-o', '-4', 'addr', 'show', 'dev', 'lan0', 'scope', 'global'],
            capture_output=True, text=True, timeout=5, check=False
        )
        addresses = re.findall(r'\binet\s+(\d{1,3}(?:\.\d{1,3}){3}/\d+)', current.stdout)
        if expected and expected not in addresses:
            raise RuntimeError(f'Current interface address does not match candidate: expected {expected}, found {addresses}')
        if not expected and not addresses:
            raise RuntimeError('No IPv4 address is configured on lan0; refusing confirmation')

        dbus_config_call(obj, 'Apply', timeout=25)
        STATE.unlink(missing_ok=True)
        return 0


def network_cancel():
    if not STATE.exists():
        return 0
    state = json.loads(STATE.read_text())
    obj = state.get('object', '')
    if obj and dbus_object_exists(obj):
        dbus_config_call(obj, 'Cancel', timeout=25)
    STATE.unlink(missing_ok=True)
    return 0


def network_read(iface):
    if iface != 'lan0':
        raise ValueError('Unsupported interface')
    def output(*args):
        try:
            return run(*args, timeout=8).stdout.strip()
        except (subprocess.CalledProcessError, subprocess.TimeoutExpired, OSError):
            return ''
    addr_text = output('/usr/sbin/ip', '-o', '-4', 'addr', 'show', 'dev', iface)
    addr_match = re.search(r'\binet\s+(\d{1,3}(?:\.\d{1,3}){3}/\d+)', addr_text)
    route_text = output('/usr/sbin/ip', '-4', 'route', 'show', 'default', 'dev', iface)
    gw_match = re.search(r'\bvia\s+(\d{1,3}(?:\.\d{1,3}){3})', route_text)
    dns_text = output('/usr/bin/resolvectl', 'dns', iface)
    dns_match = re.search(r'^Link\s+\d+\s+\([^)]*\):\s*(.*)$', dns_text, re.MULTILINE)
    dns = re.findall(r'(?:\d{1,3}\.){3}\d{1,3}', dns_match.group(1)) if dns_match else []
    domain_text = output('/usr/bin/resolvectl', 'domain', iface)
    domain_match = re.search(r'^Link\s+\d+\s+\([^)]*\):\s*(.*)$', domain_text, re.MULTILINE)
    domains = domain_match.group(1).split() if domain_match else []
    search_domain = next((d for d in domains if not d.startswith('~')), '')
    config = output('/usr/sbin/netplan', 'get', 'network.ethernets.' + iface)
    dhcp_match = re.search(r'^\s*dhcp4:\s*(true|false)\s*$', config, re.MULTILINE | re.IGNORECASE)
    if not dhcp_match:
        raise ValueError('Cannot determine DHCP mode from Netplan configuration')
    mac_path = Path('/sys/class/net') / iface / 'address'
    mac = mac_path.read_text().strip() if mac_path.exists() else ''
    print(json.dumps({
        'interface': iface,
        'address': addr_match.group(1) if addr_match else '',
        'gateway': gw_match.group(1) if gw_match else '',
        'dns1': dns[0] if dns else '',
        'dns2': dns[1] if len(dns) > 1 else '',
        'search_domain': search_domain,
        'dhcp': dhcp_match.group(1).lower() == 'true',
        'mac': mac,
    }))
    return 0


def password_change(username):
    if username != 'theroot':
        return 2

    password = sys.stdin.readline(258)
    if not password.endswith('\n'):
        return 2

    password = password[:-1]

    if (
        len(password) < 8
        or len(password) > 256
        or any(ord(char) < 32 or ord(char) == 127 for char in password)
        or ':' in password
    ):
        return 2

    subprocess.run(
        ['/usr/sbin/chpasswd'],
        input=f'{username}:{password}\n',
        text=True,
        check=True,
        capture_output=True,
        timeout=15,
    )
    return 0

def main():
    if len(sys.argv) != 3: return 2
    action, value = sys.argv[1:]
    if action == 'hostname':
        if len(value) > 63 or not re.fullmatch(r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?', value): return 2
        run('/usr/bin/hostnamectl', 'set-hostname', value); return 0
    if action == 'timezone':
        if value not in available_timezones(): return 2
        run('/usr/bin/timedatectl', 'set-timezone', value); return 0
    if action == 'ntp':
        if value not in {'yes', 'no'}: return 2
        run('/usr/bin/timedatectl', 'set-ntp', 'true' if value == 'yes' else 'false'); return 0
    if action == 'password-change': return password_change(value)
    if action == 'network-read': return network_read(value)
    if action == 'network-status': return network_status()
    if action == 'network-apply': return network_apply(value)
    if action == 'network-confirm': return network_confirm()
    if action == 'network-cancel': return network_cancel()
    return 2

if __name__ == '__main__':
    try:
        raise SystemExit(main())
    except subprocess.CalledProcessError as exc:
        command = ' '.join(str(part) for part in (exc.cmd or []))
        print(f'Command failed (exit {exc.returncode}): {command}', file=sys.stderr)
        if exc.stdout:
            print('STDOUT:', exc.stdout.strip(), file=sys.stderr)
        if exc.stderr:
            print('STDERR:', exc.stderr.strip(), file=sys.stderr)
        raise SystemExit(1)
    except subprocess.TimeoutExpired as exc:
        command = ' '.join(str(part) for part in (exc.cmd or []))
        print(f'Command timed out after {exc.timeout}s: {command}', file=sys.stderr)
        if exc.stdout:
            print('STDOUT:', exc.stdout.decode(errors='replace').strip() if isinstance(exc.stdout, bytes) else exc.stdout.strip(), file=sys.stderr)
        if exc.stderr:
            print('STDERR:', exc.stderr.decode(errors='replace').strip() if isinstance(exc.stderr, bytes) else exc.stderr.strip(), file=sys.stderr)
        raise SystemExit(1)
    except Exception as exc:
        print(f'{type(exc).__name__}: {exc}', file=sys.stderr)
        raise SystemExit(1)
