#!/usr/bin/python3
"""Supported, bounded Harresi configuration operations (root or sudo admin).

Commands validate before writes; privileged paths are fixed. Network and SSH
changes have independent systemd rollback timers. No caller paths or shell code.
"""
import argparse
import base64
import configparser
import datetime
import fcntl
import grp
import ipaddress
import json
import os
from pathlib import Path
import pwd
import re
import secrets
import stat
import subprocess
import sys
import tempfile
import time
import uuid as uuid_module

STATE = Path('/var/lib/harresi/config')
BACKUPS = Path('/var/backups/harresi/config')
ENVIRONMENT = Path('/etc/environment')
DHCP = Path('/etc/dhcp/dhcpd.conf')
PROFILES = {role: Path('/etc/NetworkManager/system-connections') / ('harresi-' + role + '.nmconnection') for role in ('lan', 'wan')}
SSH_OVERRIDE = Path('/etc/ssh/sshd_config.d/00-harresi-admin.conf')
CA_KEY = Path('/opt/sslproxy/ca.key')
CA_CERT = Path('/opt/sslproxy/ca.crt')
HELPER = '/usr/local/sbin/harresi-config'
ROLES = ('admin', 'operador', 'auditor')
SHELL = '/usr/local/bin/ssh-tmux-wrapper.sh'
ROLLBACK_SECONDS = 120

class ConfigError(Exception):
    pass

def run(*args, check=True, input=None):
    result = subprocess.run(args, input=input, text=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=90)
    if check and result.returncode:
        raise ConfigError('Falló ' + args[0] + ': ' + result.stdout.strip())
    return result

def authorize():
    if os.geteuid() != 0:
        raise ConfigError('Ejecute este comando mediante sudo como administrador.')
    user = os.environ.get('SUDO_USER')
    if user and user != 'root':
        record = pwd.getpwnam(user)
        if grp.getgrnam('admin').gr_gid not in os.getgrouplist(user, record.pw_gid):
            raise ConfigError('Esta operación requiere el rol admin.')

def atomic(path, content, mode=0o600):
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=path.parent, prefix='.harresi-', delete=False) as stream:
        temporary = Path(stream.name)
        try:
            os.fchmod(stream.fileno(), mode)
            stream.write(content if isinstance(content, bytes) else content.encode())
            stream.flush()
            os.fsync(stream.fileno())
        except BaseException:
            temporary.unlink(missing_ok=True)
            raise
    os.replace(temporary, path)

def snapshot(paths):
    if any(path.is_symlink() for path in paths):
        raise ConfigError('Se conserva la configuración: una ruta administrada es un enlace simbólico. Revísela desde recuperación.')
    return {str(path): {'data': base64.b64encode(path.read_bytes()).decode(), 'mode': stat.S_IMODE(path.stat().st_mode)} if path.exists() else None for path in paths}

def restore(files):
    for name, saved in files.items():
        path = Path(name)
        if saved is None:
            path.unlink(missing_ok=True)
        else:
            atomic(path, base64.b64decode(saved['data']), saved['mode'])

def backup(files, topic):
    BACKUPS.mkdir(parents=True, exist_ok=True, mode=0o700)
    os.chmod(BACKUPS, 0o700)
    destination = BACKUPS / (datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S') + '-' + topic + '-' + secrets.token_hex(4) + '.json')
    atomic(destination, json.dumps(files))
    return destination

def integer(value, minimum, maximum, label):
    if not re.fullmatch(r'[0-9]{1,8}', str(value)) or not minimum <= int(value) <= maximum:
        raise ConfigError(f'{label}: valor permitido entre {minimum} y {maximum}.')
    return int(value)

def dns_values(value):
    if not value or '\n' in value:
        raise ConfigError('Indique al menos un servidor DNS IPv4 separado por comas.')
    try:
        values = [str(ipaddress.IPv4Address(part.strip())) for part in value.split(',')]
    except ValueError as error:
        raise ConfigError('DNS no válido: ' + str(error)) from error
    if len(values) > 8:
        raise ConfigError('Se permiten hasta ocho servidores DNS.')
    return list(dict.fromkeys(values))

def read_profile(role):
    parser = configparser.ConfigParser(interpolation=None, strict=True)
    parser.optionxform = str
    path = PROFILES[role]
    if not path.is_file():
        raise ConfigError('Falta el perfil NetworkManager ' + str(path))
    parser.read(path)
    expected = {'id': 'harresi-' + role, 'interface-name': 'eth0' if role == 'lan' else 'eth1'}
    for key, value in expected.items():
        if parser.get('connection', key, fallback='') != value:
            raise ConfigError('El perfil no coincide con la identidad de fábrica; revise ' + str(path))
    uuid = parser.get('connection', 'uuid', fallback='')
    try:
        uuid_module.UUID(uuid)
    except ValueError:
        raise ConfigError('El perfil carece de UUID válido.')
    return parser

def service_status(unit):
    active = run('/bin/systemctl', 'is-active', unit, check=False).stdout.strip() or 'desconocido'
    enabled = run('/bin/systemctl', 'is-enabled', unit, check=False).stdout.strip() or 'desconocido'
    print(f'{unit}: estado={active}; inicio automático={enabled}')

def verify_service(unit):
    if run('/bin/systemctl', 'is-active', '--quiet', unit, check=False).returncode:
        raise ConfigError(unit + ' no alcanzó el estado activo.')

def dhcp_content(existing, subnet, first, last, gateway, dns, lease, lan_address=None):
    try:
        network = ipaddress.IPv4Network(subnet, strict=True)
        start, end, router = [ipaddress.IPv4Address(value) for value in (first, last, gateway)]
    except ValueError as error:
        raise ConfigError('Dirección/subred no válida: ' + str(error)) from error
    if network.prefixlen > 30:
        raise ConfigError('DHCP requiere una subred con direcciones de host.')
    if any(value not in network or value in (network.network_address, network.broadcast_address) for value in (start, end, router)):
        raise ConfigError('Rango y puerta de enlace deben ser hosts de la subred.')
    if int(start) > int(end):
        raise ConfigError('El inicio del rango debe ser anterior al final.')
    if start <= router <= end:
        raise ConfigError('La puerta de enlace no puede formar parte del rango DHCP.')
    if lan_address:
        lan = ipaddress.IPv4Interface(lan_address.split(',')[0])
        if lan.network != network:
            raise ConfigError('La subred debe coincidir con el perfil LAN actual.')
        if router != lan.ip:
            raise ConfigError('La puerta de enlace DHCP debe ser la dirección LAN de Harresi.')
        if start <= lan.ip <= end:
            raise ConfigError('La dirección LAN está dentro del rango DHCP.')
    duration = integer(lease, 60, 604800, 'Duración de concesión (segundos)')
    servers = dns_values(dns)
    # Preserve global declarations. Complex external DHCP scopes require CLI recovery.
    clean = re.sub(r'#[^\n]*', '', existing)
    if re.search(r'\b(include|pool|shared-network|host)\b', clean):
        raise ConfigError('Hay declaraciones DHCP avanzadas; revíselas en el apéndice de recuperación antes de utilizar este asistente.')
    blocks = list(re.finditer(r'\bsubnet\s+[^{}]+\{[^{}]*\}', existing))
    if len(blocks) > 1 or existing.count('{') != len(blocks) or existing.count('}') != len(blocks):
        raise ConfigError('El asistente admite un único ámbito DHCP. Se conserva la configuración existente.')
    rendered = (f'subnet {network.network_address} netmask {network.netmask} {{\n'
                f'  range {start} {end};\n  option routers {router};\n'
                f'  option subnet-mask {network.netmask};\n  option domain-name-servers {", ".join(servers)};\n'
                f'  default-lease-time {duration};\n  max-lease-time {duration};\n}}')
    if blocks:
        return existing[:blocks[0].start()] + rendered + existing[blocks[0].end():]
    return existing.rstrip() + '\n' + rendered + '\n'

def apply_dhcp(args):
    profile = read_profile('lan')
    if profile.get('ipv4', 'method', fallback='') != 'manual':
        raise ConfigError('DHCP requiere que el perfil LAN tenga una dirección estática.')
    content = dhcp_content(DHCP.read_text(), args.subnet, args.first, args.last, args.gateway, args.dns, args.lease, profile.get('ipv4', 'address1', fallback=''))
    # DHCP parser is run on an uninstalled candidate.
    with tempfile.NamedTemporaryFile(dir=DHCP.parent, mode='w', prefix='.harresi-', delete=False) as stream:
        candidate = Path(stream.name)
        stream.write(content)
    try:
        run('/usr/sbin/dhcpd', '-t', '-cf', str(candidate))
    finally:
        candidate.unlink(missing_ok=True)
    previous = snapshot([DHCP])
    saved = backup(previous, 'dhcp')
    was_active = run('/bin/systemctl', 'is-active', '--quiet', 'isc-dhcp-server', check=False).returncode == 0
    try:
        atomic(DHCP, content, 0o644)
        run('/bin/systemctl', 'restart', 'isc-dhcp-server')
        verify_service('isc-dhcp-server')
    except Exception as error:
        restore(previous)
        recovery = run('/bin/systemctl', 'restart' if was_active else 'stop', 'isc-dhcp-server', check=False)
        raise ConfigError(f'No se aplicó DHCP; configuración restaurada. {error}. Recuperación: {recovery.stdout.strip() or recovery.returncode}') from error
    print('DHCP guardado y aplicado. Copia: ' + str(saved))

def pending_path(kind):
    return STATE / (kind + '-pending.json')

def stage(kind, paths, extra):
    path = pending_path(kind)
    if path.exists():
        raise ConfigError('Hay un cambio pendiente: confirme o revierta antes de continuar.')
    files = snapshot(paths)
    backup(files, kind)
    token = secrets.token_hex(12)
    unit = 'harresi-config-' + kind + '-' + token
    state = {'token': token, 'unit': unit, 'expires': time.time() + ROLLBACK_SECONDS, 'files': files, **extra}
    atomic(path, json.dumps(state))
    try:
        run('/usr/bin/systemd-run', '--unit=' + unit, '--on-active=' + str(ROLLBACK_SECONDS) + 's', '--timer-property=AccuracySec=1s', HELPER, kind + '-rollback', token)
    except Exception:
        path.unlink(missing_ok=True)
        raise
    return state

def pending(kind, token):
    if not re.fullmatch(r'[a-f0-9]{24}', token):
        raise ConfigError('Código de confirmación no válido.')
    path = pending_path(kind)
    if not path.exists():
        raise ConfigError('No hay cambio pendiente: pudo expirar y ser restaurado.')
    state = json.loads(path.read_text())
    if not secrets.compare_digest(state['token'], token):
        raise ConfigError('El código no corresponde al cambio pendiente.')
    return state

def finish_timer(state):
    # During rollback this command may run inside its own .service: stop the timer only.
    run('/bin/systemctl', 'stop', state['unit'] + '.timer', check=False)

def rollback(kind, token):
    state = pending(kind, token)
    restore(state['files'])
    if kind == 'network':
        run('/usr/bin/nmcli', 'connection', 'reload')
        run('/usr/bin/nmcli', 'connection', 'up', 'uuid', state['uuid'])
    else:
        run('/usr/sbin/sshd', '-t')
        run('/bin/systemctl', 'reload', 'ssh')
        verify_service('ssh')
    finish_timer(state)
    pending_path(kind).unlink(missing_ok=True)
    print('Configuración anterior restaurada: ' + kind)

def confirm(kind, token):
    state = pending(kind, token)
    if time.time() >= state['expires']:
        rollback(kind, token)
        raise ConfigError('La confirmación llegó fuera de plazo; se restauró la configuración anterior.')
    if kind == 'network':
        active = run('/usr/bin/nmcli', '-t', '-f', 'UUID', 'connection', 'show', '--active').stdout.splitlines()
        if state['uuid'] not in active:
            raise ConfigError('El perfil previsto no está activo; el cambio sigue pendiente.')
    else:
        run('/usr/sbin/sshd', '-t')
        verify_service('ssh')
    finish_timer(state)
    pending_path(kind).unlink(missing_ok=True)
    print('Configuración confirmada y persistente tras reinicio: ' + kind)

def network_content(profile, role, method, address, gateway, dns):
    if method not in ('manual', 'auto') or (role == 'lan' and method != 'manual'):
        raise ConfigError('LAN admite estática; WAN admite estática o DHCP.')
    if 'ipv4' not in profile:
        profile['ipv4'] = {}
    for key in list(profile['ipv4']):
        if key in ('addresses', 'gateway', 'dns', 'method', 'never-default', 'ignore-auto-dns') or re.fullmatch(r'address[0-9]+', key):
            del profile['ipv4'][key]
    profile['ipv4']['method'] = method
    profile['connection']['autoconnect'] = 'true'
    profile['ipv4']['never-default'] = 'true' if role == 'lan' else 'false'
    if method == 'manual':
        try:
            interface = ipaddress.IPv4Interface(address)
            if '/' not in address or interface.network.prefixlen > 30 or interface.ip in (interface.network.network_address, interface.network.broadcast_address):
                raise ValueError('Dirección de host/prefijo no válida.')
            router = ipaddress.IPv4Address(gateway) if gateway else None
            if router and (router not in interface.network or router in (interface.network.network_address, interface.network.broadcast_address) or router == interface.ip):
                raise ValueError('Puerta de enlace fuera de subred o coincidente con la dirección local.')
        except ValueError as error:
            raise ConfigError(str(error)) from error
        if role == 'lan' and router:
            raise ConfigError('LAN no configura puerta de enlace; la ruta por defecto pertenece a WAN.')
        profile['ipv4']['address1'] = str(interface) + (',' + str(router) if router else '')
        profile['ipv4']['dns'] = ';'.join(dns_values(dns)) + ';'
    elif address or gateway or dns:
        raise ConfigError('WAN DHCP obtiene dirección, puerta de enlace y DNS automáticamente; deje esos campos vacíos.')
    from io import StringIO
    output = StringIO()
    profile.write(output, space_around_delimiters=False)
    return output.getvalue()

def apply_network(args):
    profile = read_profile(args.role)
    interface = profile['connection']['interface-name']
    current = run('/usr/bin/nmcli', '-t', '-f', 'UUID,DEVICE', 'connection', 'show', '--active').stdout.splitlines()
    if any(line.endswith(':' + interface) and line.split(':')[0] != profile['connection']['uuid'] for line in current):
        raise ConfigError('La interfaz utiliza otro perfil activo. Revise NetworkManager antes de cambiar el perfil Harresi.')
    content = network_content(profile, args.role, args.method, args.address, args.gateway, args.dns)
    if args.role == 'lan':
        print('Después de confirmar la red, revise el ámbito DHCP (Configuración del sistema → 4) para que coincida con la subred LAN.', flush=True)
    # Catch LAN/WAN overlap before arming or writing anything.
    if args.method == 'manual':
        other = read_profile('wan' if args.role == 'lan' else 'lan')
        if other.get('ipv4', 'method', fallback='') == 'manual':
            other_address = other.get('ipv4', 'address1', fallback='').split(',')[0]
            if ipaddress.IPv4Interface(args.address).network.overlaps(ipaddress.IPv4Interface(other_address).network):
                raise ConfigError('Las subredes LAN y WAN no pueden solaparse.')
    uuid = profile['connection']['uuid']
    state = stage('network', [PROFILES[args.role]], {'uuid': uuid})
    print(f'Código: {state["token"]}; confirmar en {ROLLBACK_SECONDS}s desde una nueva conexión.', flush=True)
    try:
        atomic(PROFILES[args.role], content)
        run('/usr/bin/nmcli', 'connection', 'reload')
        run('/usr/bin/nmcli', 'connection', 'up', 'uuid', uuid)
    except Exception as error:
        rollback('network', state['token'])
        raise ConfigError('Falló la aplicación de red; restaurada: ' + str(error)) from error
    print('Red aplicada provisionalmente. Confirme con: sudo harresi-config network-confirm ' + state['token'])

def apply_ssh(args):
    port = integer(args.port, 1, 65535, 'Puerto SSH')
    interval = integer(args.alive, 0, 3600, 'ClientAliveInterval')
    content = f'# Administrado por harresi-config\nPort {port}\nPermitRootLogin no\nPasswordAuthentication yes\nAuthenticationMethods password\nUsePAM yes\nClientAliveInterval {interval}\nClientAliveCountMax 2\n'
    with tempfile.NamedTemporaryFile(dir=SSH_OVERRIDE.parent, mode='w', prefix='.harresi-validation-', delete=False) as stream:
        candidate = Path(stream.name)
        stream.write(content + '\nInclude /etc/ssh/sshd_config\n')
    try:
        run('/usr/sbin/sshd', '-t', '-f', str(candidate))
    finally:
        candidate.unlink(missing_ok=True)
    state = stage('ssh', [SSH_OVERRIDE], {})
    print(f'Código: {state["token"]}; confirmar en {ROLLBACK_SECONDS}s desde una nueva conexión al puerto {port}.', flush=True)
    try:
        atomic(SSH_OVERRIDE, content, 0o644)
        run('/usr/sbin/sshd', '-t')
        run('/bin/systemctl', 'reload', 'ssh')
        verify_service('ssh')
        effective = run('/usr/sbin/sshd', '-T').stdout
        for expected in (f'port {port}', 'passwordauthentication yes', 'usepam yes', 'authenticationmethods password', 'permitrootlogin no'):
            if expected not in effective.splitlines():
                raise ConfigError('La configuración principal impide aplicar ' + expected)
    except Exception as error:
        rollback('ssh', state['token'])
        raise ConfigError('Falló SSH; restaurado: ' + str(error)) from error
    print('SSH aplicado provisionalmente. Confirme con: sudo harresi-config ssh-confirm ' + state['token'])

def ca_validate(key, cert):
    run('/usr/bin/openssl', 'pkey', '-in', str(key), '-check', '-noout')
    key_public = run('/usr/bin/openssl', 'pkey', '-in', str(key), '-pubout').stdout
    cert_public = run('/usr/bin/openssl', 'x509', '-in', str(cert), '-pubkey', '-noout').stdout
    if key_public != cert_public:
        raise ConfigError('La clave privada y el certificado CA no coinciden.')
    run('/usr/bin/openssl', 'x509', '-in', str(cert), '-checkend', '0', '-noout')

def ca_regenerate(args):
    if args.accept != 'REEMPLAZAR':
        raise ConfigError('Debe aceptar la redistribución del certificado CA con REEMPLAZAR.')
    days = integer(args.days, 1, 3650, 'Validez (días)')
    CA_KEY.parent.mkdir(parents=True, exist_ok=True, mode=0o750)
    previous = snapshot([CA_KEY, CA_CERT])
    saved = backup(previous, 'ca')
    with tempfile.TemporaryDirectory(dir=CA_KEY.parent, prefix='.harresi-ca-') as directory:
        key, cert = Path(directory) / 'ca.key', Path(directory) / 'ca.crt'
        run('/usr/bin/openssl', 'genpkey', '-algorithm', 'RSA', '-pkeyopt', 'rsa_keygen_bits:4096', '-out', str(key))
        os.chmod(key, 0o600)
        run('/usr/bin/openssl', 'req', '-new', '-x509', '-sha256', '-days', str(days), '-key', str(key), '-out', str(cert), '-subj', '/CN=HARRESI SSL CA/OU=Harresi/O=Cibersare/C=ES', '-addext', 'basicConstraints=critical,CA:TRUE', '-addext', 'keyUsage=critical,keyCertSign,cRLSign')
        ca_validate(key, cert)
        units = [unit for unit in ('sslproxyd', 'suricata_mitm') if run('/bin/systemctl', 'is-active', '--quiet', unit, check=False).returncode == 0]
        try:
            atomic(CA_KEY, key.read_bytes(), 0o600)
            atomic(CA_CERT, cert.read_bytes(), 0o644)
            for unit in units:
                run('/bin/systemctl', 'restart', unit)
                verify_service(unit)
        except Exception as error:
            restore(previous)
            errors = [unit for unit in units if run('/bin/systemctl', 'restart', unit, check=False).returncode]
            raise ConfigError(f'CA anterior restaurada. {error}. Servicios con fallo de recuperación: {errors}') from error
    print('CA reemplazada y servicios activos reiniciados. Distribuya /opt/sslproxy/ca.crt a los clientes. Copia privada protegida: ' + str(saved))

def supported_accounts():
    accounts = []
    for account in pwd.getpwall():
        if account.pw_shell != SHELL:
            continue
        groups = os.getgrouplist(account.pw_name, account.pw_gid)
        roles = [role for role in ROLES if grp.getgrnam(role).gr_gid in groups]
        accounts.append((account, roles))
    return accounts

def usable_admins():
    import spwd
    usable = []
    today = int(time.time() // 86400)
    for account, roles in supported_accounts():
        if 'admin' not in roles:
            continue
        secret = spwd.getspnam(account.pw_name)
        if not secret.sp_pwdp.startswith(('!', '*')) and secret.sp_pwdp and (secret.sp_expire < 0 or secret.sp_expire >= today):
            usable.append(account.pw_name)
    return usable

def require_supported(user):
    if not re.fullmatch(r'[a-z][a-z0-9_-]{0,31}', user) or user == 'root':
        raise ConfigError('Nombre permitido: letra minúscula inicial, letras/números/guiones; hasta 32 caracteres.')
    for account, roles in supported_accounts():
        if account.pw_name == user:
            return account, roles
    raise ConfigError('La cuenta no es una cuenta Harresi compatible.')

def role_memberships(role):
    return role

def account_action(args):
    user = args.user
    if args.action == 'user-create':
        if not re.fullmatch(r'[a-z][a-z0-9_-]{0,31}', user) or user == 'root':
            raise ConfigError('Nombre de usuario no válido.')
        try:
            pwd.getpwnam(user)
        except KeyError:
            pass
        else:
            raise ConfigError('La cuenta ya existe.')
        run('/usr/sbin/useradd', '-m', '-s', SHELL, '-G', role_memberships(args.role), user)
        try:
            print('Defina la contraseña inicial (política PAM vigente):', flush=True)
            result = subprocess.run(['/usr/bin/passwd', user], timeout=180)
            if result.returncode:
                raise ConfigError('Contraseña inicial cancelada o no válida.')
            run('/usr/bin/chage', '-d', '0', user)
        except Exception:
            run('/usr/sbin/userdel', user, check=False)
            raise
        print('Cuenta creada; cambio de contraseña obligatorio en la próxima conexión.')
        return
    account, roles = require_supported(user)
    if args.action == 'user-role' and grp.getgrgid(account.pw_gid).gr_name in ROLES and grp.getgrgid(account.pw_gid).gr_name != args.role:
        raise ConfigError('La cuenta de fábrica utiliza el rol como grupo principal; cree otra cuenta con el rol deseado.')
    if args.action in ('user-delete', 'user-role'):
        if user == os.environ.get('SUDO_USER'):
            raise ConfigError('No puede eliminar ni cambiar el rol de su sesión administrativa actual.')
        losing_admin = args.action == 'user-delete' or args.role != 'admin'
        if 'admin' in roles and losing_admin and not [name for name in usable_admins() if name != user]:
            raise ConfigError('Se conservará el último administrador utilizable.')
    if args.action == 'user-delete':
        # Keep the home and logs for recovery; never delete caller-selected paths.
        run('/usr/sbin/userdel', user)
        print('Cuenta eliminada. Directorio personal y registros conservados para recuperación.')
    elif args.action == 'user-role':
        gids = os.getgrouplist(user, account.pw_gid)
        retained = [grp.getgrgid(gid).gr_name for gid in gids if gid != account.pw_gid and grp.getgrgid(gid).gr_name not in ROLES]
        run('/usr/sbin/usermod', '-G', ','.join(dict.fromkeys(retained + role_memberships(args.role).split(','))), user)
        print('Rol guardado. Se aplica al iniciar una nueva conexión.')
    else:
        print('Restablecer contraseña con la política PAM vigente:', flush=True)
        result = subprocess.run(['/usr/bin/passwd', user], timeout=180)
        if result.returncode:
            raise ConfigError('No se cambió la contraseña.')
        run('/usr/bin/chage', '-d', '0', user)
        print('Contraseña restablecida; cambio obligatorio en la próxima conexión.')

def vpn_profiles():
    profiles = {}
    for directory, prefix in (('/etc/openvpn/client', 'openvpn-client@'), ('/etc/openvpn/server', 'openvpn-server@'), ('/etc/openvpn', 'openvpn@')):
        for path in Path(directory).glob('*.conf'):
            if re.fullmatch(r'[A-Za-z0-9_-]{1,64}', path.stem) and path.is_file():
                profiles[prefix + path.stem + '.service'] = path
    return profiles

def show(topic):
    if topic == 'dhcp':
        print(DHCP.read_text())
        print('Interfaz de servicio: ' + Path('/etc/default/isc-dhcp-server').read_text())
        service_status('isc-dhcp-server')
    elif topic == 'network':
        print('Asignación de fábrica: puerto LAN = eth0; puerto WAN = eth1. Verifique el etiquetado físico en el dispositivo.')
        for role in PROFILES:
            profile = read_profile(role)
            print(f'\n{role.upper()}: {PROFILES[role]}\n' + '\n'.join(f'{key}={value}' for key, value in profile['ipv4'].items()))
        print(run('/usr/bin/nmcli', '-f', 'NAME,UUID,TYPE,DEVICE', 'connection', 'show').stdout)
        print(run('/usr/sbin/ip', '-brief', 'address').stdout)
        print(run('/usr/sbin/ip', 'route', 'show').stdout)
        show_pending('network')
    elif topic == 'timeout':
        values = re.findall(r'^SESSION_TIMEOUT=([0-9]+)$', ENVIRONMENT.read_text(), re.M)
        print('SESSION_TIMEOUT=' + (values[-1] if values else '15 (predeterminado)') + ' minutos de duración TOTAL de la conexión SSH.\nNo es un temporizador de inactividad. Las conexiones nuevas usan el nuevo valor; las existentes conservan su límite.')
    elif topic == 'ca':
        print(run('/usr/bin/openssl', 'x509', '-in', str(CA_CERT), '-noout', '-subject', '-dates', '-fingerprint', '-sha256').stdout)
        ca_validate(CA_KEY, CA_CERT)
        if CA_KEY.stat().st_uid != 0 or stat.S_IMODE(CA_KEY.stat().st_mode) & 0o077:
            raise ConfigError('La clave CA tiene permisos inseguros; admin debe corregirla a root:root 0600 desde el terminal de recuperación.')
        print('Clave privada protegida. Certificado público exportable: /opt/sslproxy/ca.crt')
    elif topic == 'users':
        for account, roles in supported_accounts():
            print(account.pw_name + '\t' + ','.join(roles) + '\t' + run('/usr/bin/passwd', '-S', account.pw_name).stdout.strip())
    elif topic == 'ssh':
        effective = run('/usr/sbin/sshd', '-T').stdout
        keys = ('port', 'passwordauthentication', 'pubkeyauthentication', 'permitrootlogin', 'usepam', 'authenticationmethods', 'clientaliveinterval', 'clientalivecountmax', 'allowgroups', 'allowusers')
        print('\n'.join(line for line in effective.splitlines() if line.split(' ', 1)[0] in keys))
        print('ClientAlive verifica clientes inalcanzables; la duración total se controla por SESSION_TIMEOUT.')
        service_status('ssh')
        show_pending('ssh')
    else:
        profiles = vpn_profiles()
        if not profiles:
            print('VPN no disponible: se instala OpenVPN, pero no se suministra ningún perfil de soporte. Es necesario un perfil/certificados proporcionados por soporte.')
        for unit, path in profiles.items():
            print(str(path))
            service_status(unit)

def show_pending(kind):
    path = pending_path(kind)
    if path.exists():
        state = json.loads(path.read_text())
        print(f'CAMBIO PENDIENTE: {state["token"]}; reversión automática en {max(0, int(state["expires"] - time.time()))}s')

def recover_pending():
    # Boot runs before NetworkManager/SSH: restore files without activating units.
    # Transient timers do not survive reboot, so every unconfirmed change is undone.
    for kind in ('network', 'ssh'):
        path = pending_path(kind)
        if path.exists():
            state = json.loads(path.read_text())
            restore(state['files'])
            path.unlink()
            print('Cambio sin confirmar restaurado antes del arranque: ' + kind)

def parser():
    command = argparse.ArgumentParser(description=__doc__)
    sub = command.add_subparsers(dest='action', required=True)
    p = sub.add_parser('show'); p.add_argument('topic', choices=('dhcp', 'network', 'timeout', 'ca', 'users', 'ssh', 'vpn'))
    p = sub.add_parser('dhcp-apply')
    for name in ('subnet', 'first', 'last', 'gateway', 'dns', 'lease'): p.add_argument(name)
    p = sub.add_parser('network-apply'); p.add_argument('role', choices=('lan', 'wan')); p.add_argument('method', choices=('manual', 'auto'))
    for name in ('address', 'gateway', 'dns'): p.add_argument(name)
    for kind in ('network', 'ssh'):
        for action in ('confirm', 'rollback'):
            p = sub.add_parser(kind + '-' + action); p.add_argument('token')
    p = sub.add_parser('timeout-set'); p.add_argument('minutes')
    p = sub.add_parser('ssh-apply'); p.add_argument('port'); p.add_argument('alive')
    p = sub.add_parser('ca-regenerate'); p.add_argument('days'); p.add_argument('accept')
    sub.add_parser('ca-export')
    sub.add_parser('recover-pending')
    for action in ('create', 'role', 'reset', 'delete'):
        p = sub.add_parser('user-' + action); p.add_argument('user')
        if action in ('create', 'role'): p.add_argument('role', choices=ROLES)
    p = sub.add_parser('vpn-action'); p.add_argument('unit'); p.add_argument('operation', choices=('start', 'stop', 'status'))
    return command

def main():
    args = parser().parse_args()
    try:
        authorize()
        os.umask(0o077)
        STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
        with (STATE / 'lock').open('a') as lock:
            fcntl.flock(lock, fcntl.LOCK_EX)
            if args.action == 'show': show(args.topic)
            elif args.action == 'dhcp-apply': apply_dhcp(args)
            elif args.action == 'network-apply': apply_network(args)
            elif args.action == 'ssh-apply': apply_ssh(args)
            elif args.action.endswith('-confirm'): confirm(args.action.split('-')[0], args.token)
            elif args.action.endswith('-rollback'): rollback(args.action.split('-')[0], args.token)
            elif args.action == 'timeout-set':
                minutes = integer(args.minutes, 1, 1440, 'SESSION_TIMEOUT (minutos)')
                previous = snapshot([ENVIRONMENT]); saved = backup(previous, 'timeout')
                content = re.sub(r'^SESSION_TIMEOUT=.*\n?', '', ENVIRONMENT.read_text(), flags=re.M)
                atomic(ENVIRONMENT, content.rstrip() + '\nSESSION_TIMEOUT=' + str(minutes) + '\n', 0o644)
                print(f'Duración total guardada: {minutes} minutos. Abra una nueva conexión. Copia: {saved}')
            elif args.action == 'ca-regenerate': ca_regenerate(args)
            elif args.action == 'ca-export': print(CA_CERT.read_text(), end='')
            elif args.action == 'recover-pending': recover_pending()
            elif args.action.startswith('user-'): account_action(args)
            elif args.action == 'vpn-action':
                if args.unit not in vpn_profiles(): raise ConfigError('No hay un perfil OpenVPN compatible para esa instancia.')
                if args.operation == 'status': service_status(args.unit)
                else:
                    previous = run('/bin/systemctl', 'is-enabled', '--quiet', args.unit, check=False).returncode == 0
                    try:
                        run('/bin/systemctl', 'enable' if args.operation == 'start' else 'disable', '--now', args.unit)
                        if args.operation == 'start': verify_service(args.unit)
                    except Exception:
                        run('/bin/systemctl', 'enable' if previous else 'disable', '--now', args.unit, check=False)
                        raise
                    service_status(args.unit)
    except (ConfigError, OSError, ValueError, KeyError, subprocess.TimeoutExpired, configparser.Error) as error:
        print('ERROR: ' + str(error), file=sys.stderr)
        return 1
    return 0

if __name__ == '__main__':
    sys.exit(main())
