#!/usr/bin/php
<?php
/*
  vim: set expandtab tabstop=4 softtabstop=4 shiftwidth=4:
  +----------------------------------------------------------------------+
  | Issabel version 6.0                                                  |
  | http://www.issabel.org                                               |
  +----------------------------------------------------------------------+
  | Copyright (c) 2021 Issabel Foundation                                |
  | Copyright (c) 2006 Palosanto Solutions S. A.                         |
  +----------------------------------------------------------------------+
  | The contents of this file are subject to the General Public License  |
  | (GPL) Version 2 (the "License"); you may not use this file except in |
  | compliance with the License. You may obtain a copy of the License at |
  | http://www.opensource.org/licenses/gpl-license.php                   |
  |                                                                      |
  | Software distributed under the License is distributed on an "AS IS"  |
  | basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See  |
  | the License for the specific language governing rights and           |
  | limitations under the License.                                       |
  +----------------------------------------------------------------------+
  | The Initial Developer of the Original Code is PaloSanto Solutions    |
  +----------------------------------------------------------------------+
*/

/*
 * Configuración de red sobre NetworkManager (nmcli).
 *
 * Reemplaza la escritura legacy de /etc/sysconfig/network-scripts/ifcfg-*,
 * /etc/sysconfig/network, /etc/resolv.conf y 'route', que ya no existen o no se
 * usan en EL10. La fuente de verdad es NetworkManager.
 *
 * Todo cambio se aplica en modo seguro (commit-confirm): se toma un snapshot de
 * los perfiles, se aplica el cambio y se programa una reversión automática con
 * un timer de systemd. El admin confirma (--confirm <token>) para cancelarla; si
 * no confirma, se revierte (--rollback <token>). El estado pendiente se guarda
 * en un directorio persistente para poder recuperar tras un reboot.
 *
 * Acciones:
 *   --genconf   hostname / DNS / gateway
 *   --ifconf    dirección de una interfaz (static o dhcp)
 *   --confirm   cancela la reversión de un cambio pendiente
 *   --rollback  aplica el snapshot de un cambio (lo invoca el timer)
 *   --pending   imprime el cambio pendiente como JSON (para la GUI)
 *   --recover   revierte un cambio pendiente en el arranque
 *   --getroutes imprime las rutas estáticas IPv4 por interfaz como JSON
 *   --getmethods imprime el método IPv4/IPv6 por interfaz como JSON
 *   --apply     aplica un change set JSON de forma atómica (commit-confirm)
 */

require_once 'Console/Getopt.php';

define('STATE_DIR',       '/var/lib/issabel/netconfig-rollback');
define('PENDING_FILE',    STATE_DIR.'/pending.json');
define('LOCK_FILE',       STATE_DIR.'/.lock');
define('NMCLI',           '/usr/bin/nmcli');
define('SELF',            '/usr/share/issabel/privileged/netconfig');
define('DEFAULT_TIMEOUT', 600);

$LOCK_HANDLE = NULL;

// Parse command-line options
$opt = Console_Getopt::getopt($argv, '', array(
    'genconf',  // General network configuration
    'ifconf',   // Interface-specific configuration
    'confirm=', // Cancel the rollback of a pending change (token)
    'rollback=',// Apply the snapshot of a pending change (token)
    'pending',  // Print the pending change as JSON
    'recover',  // Revert a pending change at boot (used by the systemd unit)
    'getroutes',// Print the IPv4 static routes per interface as JSON
    'getmethods',// Print the IPv4/IPv6 connection methods per interface as JSON
    'setroutes',// Set the IPv4 static routes of an interface
    'routespec=',// Route list in nmcli syntax (for --setroutes)
    'apply',    // Apply an atomic change set (JSON)
    'change=',  // Change set JSON (for --apply)
    'client-ip=',// Client IP, to classify the management interface

    // General network configuration options
    'host=',        // New hostname
    'dns1=',        // DNS 1
    'dns2=',        // DNS 2
    'gateway=',     // Network gateway

    // Interface configuration options
    'device=',      // ethN
    'bootproto=',   // Either 'dhcp' or 'static'
    'ipaddr=',      // IP address for the interface
    'netmask=',     // Network mask for interface
    'ip6method=',   // IPv6 method: auto | manual | dhcp | disabled
    'ip6addr=',     // Static IPv6 address with prefix (addr/prefix)
    'ip6gw=',       // IPv6 gateway

    // General network configuration (IPv6 DNS)
    'dns6=',        // IPv6 DNS server

    'timeout=',     // Seconds before the automatic rollback
));
if (PEAR::isError($opt)) error_exit($opt->getMessage()."\n");
validateOptions($opt);
foreach ($opt[0] as $option) switch ($option[0]) {
case '--genconf':
    exit(action_generalConfiguration($opt) ? 0 : 1);
case '--ifconf':
    exit(action_interfaceConfiguration($opt) ? 0 : 1);
case '--confirm':
    exit(action_confirm($option[1]) ? 0 : 1);
case '--rollback':
    exit(action_rollback($option[1]) ? 0 : 1);
case '--pending':
    exit(action_pending() ? 0 : 1);
case '--recover':
    exit(action_recover() ? 0 : 1);
case '--getroutes':
    exit(action_getroutes() ? 0 : 1);
case '--getmethods':
    exit(action_getmethods() ? 0 : 1);
case '--setroutes':
    exit(action_setroutes($opt) ? 0 : 1);
case '--apply':
    exit(action_apply($opt) ? 0 : 1);
}
error_exit("No action specified (--genconf, --ifconf, --confirm, --rollback or --pending)\n");

function error_exit($sMsg, $errorcode = 1)
{
    fwrite(STDERR, $sMsg);
    exit($errorcode);
}

// Parse and validate known command-line options
function validateOptions($opt)
{
    foreach ($opt[0] as $option) switch ($option[0]) {
    case '--genconf':
    case '--ifconf':
    case '--pending':
    case '--recover':
    case '--getroutes':
    case '--getmethods':
    case '--setroutes':
    case '--apply':
        break;
    case '--change':
        // La estructura se valida en action_apply(); aquí solo se acepta JSON.
        if (json_decode($option[1], TRUE) === NULL)
            error_exit('Option '.$option[0].": Invalid JSON\n");
        break;
    case '--client-ip':
        if (filter_var($option[1], FILTER_VALIDATE_IP) === false)
            error_exit('Option '.$option[0].": Invalid IP address\n");
        break;
    case '--host':
        if (!preg_match('/^(([[:alnum:]-]+)\.)+([[:alnum:]])+$/', $option[1]))
            error_exit('Option '.$option[0].": Invalid hostname\n");
        if (count(explode('.', $option[1])) < 2)
            error_exit('Option '.$option[0].": Invalid hostname - domain-only not acceptable\n");
        break;
    case '--device':
        if (!preg_match('/^[[:alnum:]\._-]+$/', $option[1]))
            error_exit('Option '.$option[0].": Invalid network device\n");
        break;
    case '--bootproto':
        if (!in_array($option[1], array('dhcp', 'static')))
            error_exit('Option '.$option[0].": Invalid bootproto\n");
        break;
    case '--timeout':
        if (!ctype_digit($option[1]) || intval($option[1]) <= 0)
            error_exit('Option '.$option[0].": Invalid timeout\n");
        break;
    case '--routespec':
        if (!preg_match('/^[0-9a-fA-F:.\/,\s=_-]*$/', $option[1]))
            error_exit('Option '.$option[0].": Invalid route specification\n");
        break;
    case '--confirm':
    case '--rollback':
        if (!preg_match('/^[[:alnum:]_-]+$/', $option[1]))
            error_exit('Option '.$option[0].": Invalid token\n");
        break;
    case '--ip6method':
        if (!in_array($option[1], array('auto', 'manual', 'dhcp', 'disabled')))
            error_exit('Option '.$option[0].": Invalid IPv6 method\n");
        break;
    case '--ip6addr':
        $p6 = explode('/', $option[1], 2);
        if (count($p6) != 2
            || filter_var($p6[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false
            || !ctype_digit($p6[1]) || intval($p6[1]) > 128)
            error_exit('Option '.$option[0].": Invalid IPv6 address\n");
        break;
    case '--ip6gw':
    case '--dns6':
        if (filter_var($option[1], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false)
            error_exit('Option '.$option[0].": Invalid IPv6 address\n");
        break;
    case '--dns1':
    case '--dns2':
    case '--gateway':
    case '--ipaddr':
    case '--netmask':
        $regs = NULL;
        if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $option[1], $regs))
            error_exit('Option '.$option[0].": Invalid IP address\n");
        for ($i = 1; $i <= 4; $i++) if ($regs[$i] > 255)
            error_exit('Option '.$option[0].": Invalid IP address\n");
        if ($option[0] == '--netmask') {
            $b = FALSE;
            for ($i = 1; $i <= 4; $i++) {
                if ($regs[$i] == 255 && !$b) continue;
                if ($regs[$i] != 0 && $b)
                    error_exit('Option '.$option[0].": Invalid network mask (1)\n");
                if ($regs[$i] == 0 && $b) continue;
                $b = TRUE;
                if (!in_array($regs[$i], array(255, 254, 252, 248, 240, 224, 192, 128, 0)))
                    error_exit('Option '.$option[0].": Invalid network mask (2)\n");
            }
        }
        break;
    }
}

/* ------------------------------------------------------------------------- *
 *  nmcli helpers
 * ------------------------------------------------------------------------- */

// Ejecuta un comando y devuelve (por referencia) el código y la salida.
function runCommand($argv, &$ret, &$output)
{
    $cmd = '';
    foreach ($argv as $a) $cmd .= ($cmd === '' ? '' : ' ').escapeshellarg($a);
    $output = array();
    $ret = NULL;
    exec($cmd.' 2>&1', $output, $ret);
    return $ret;
}

// Ejecuta nmcli con locale fijo y devuelve la salida como arreglo de líneas.
// Devuelve arreglo vacío si nmcli falla.
function nmcliLines($args)
{
    $argv = array_merge(array('/usr/bin/env', 'LC_ALL=C', 'LANG=C', NMCLI), $args);
    $ret = NULL; $output = array();
    runCommand($argv, $ret, $output);
    if ($ret != 0) return array();
    return $output;
}

// Aplica propiedades a una conexión. $props = array(clave => valor).
function nmcliMod($conn, $props)
{
    $args = array('con', 'mod', $conn);
    foreach ($props as $k => $v) {
        $args[] = $k;
        $args[] = $v;
    }
    $ret = NULL; $output = array();
    $argv = array_merge(array('/usr/bin/env', 'LC_ALL=C', 'LANG=C', NMCLI), $args);
    runCommand($argv, $ret, $output);
    if ($ret != 0) {
        fwrite(STDERR, "ERR: nmcli con mod failed - ".implode(' ', $output)."\n");
        return FALSE;
    }
    return TRUE;
}

// Activa una conexión (con espera acotada). Devuelve TRUE si queda activa.
function nmcliUp($conn, $wait = 30)
{
    // --wait es una opción global de nmcli: va antes del objeto/verbo.
    $argv = array('/usr/bin/env', 'LC_ALL=C', 'LANG=C', NMCLI,
        '--wait', (string)$wait, 'con', 'up', $conn);
    $ret = NULL; $output = array();
    runCommand($argv, $ret, $output);
    if ($ret != 0) {
        fwrite(STDERR, "ERR: nmcli con up failed - ".implode(' ', $output)."\n");
        return FALSE;
    }
    return TRUE;
}

function listConnectionNames()
{
    $names = array();
    foreach (nmcliLines(array('-g', 'NAME', 'con', 'show')) as $n) {
        $n = trim($n);
        if ($n !== '') $names[] = $n;
    }
    return $names;
}

function activeConnectionNames()
{
    $names = array();
    foreach (nmcliLines(array('-t', '-e', 'yes', '-f', 'NAME', 'con', 'show', '--active')) as $n) {
        $n = trim($n);
        if ($n !== '') $names[] = $n;
    }
    return $names;
}

// Conexión asociada a una interfaz (prefiere la activa).
function connectionForDevice($dev)
{
    foreach (nmcliLines(array('-t', '-e', 'yes', '-f', 'NAME,DEVICE', 'con', 'show', '--active')) as $l) {
        $p = explode(':', $l, 2);
        if (isset($p[1]) && $p[1] === $dev) return $p[0];
    }
    foreach (listConnectionNames() as $name) {
        $info = nmcliLines(array('-g', 'connection.interface-name', 'con', 'show', $name));
        if (count($info) > 0 && trim($info[0]) === $dev) return $name;
    }
    return NULL;
}

// Crea una conexión de NetworkManager para una interfaz que no la tiene.
// Devuelve el nombre de la conexión o NULL. VLAN (eth0.100) y ethernet; macvlan
// (mv-*) queda diferido (best-effort, ver NETWORKtodo.md §3.7).
function createConnectionForDevice($dev)
{
    $ret = NULL; $out = array();

    if (preg_match('/^(.+)\.(\d+)$/', $dev, $m)) {
        // VLAN: eth0.100 -> padre eth0, id 100
        $argv = array_merge(array('/usr/bin/env', 'LC_ALL=C', 'LANG=C', NMCLI),
            array('con', 'add', 'type', 'vlan', 'con-name', $dev, 'ifname', $dev,
                  'dev', $m[1], 'id', $m[2]));
        runCommand($argv, $ret, $out);
        if ($ret != 0) {
            fwrite(STDERR, "ERR: cannot create VLAN connection - ".implode(' ', $out)."\n");
            return NULL;
        }
        return $dev;
    }

    if (strpos($dev, 'mv-') === 0) {
        fwrite(STDERR, "ERR: creating macvlan (mv-*) connections from the GUI is not supported yet\n");
        return NULL;
    }

    $argv = array_merge(array('/usr/bin/env', 'LC_ALL=C', 'LANG=C', NMCLI),
        array('con', 'add', 'type', 'ethernet', 'con-name', $dev, 'ifname', $dev));
    runCommand($argv, $ret, $out);
    if ($ret != 0) {
        fwrite(STDERR, "ERR: cannot create connection - ".implode(' ', $out)."\n");
        return NULL;
    }
    return $dev;
}

// Interfaz que lleva la ruta por defecto, según NetworkManager.
function defaultRouteDevice()
{
    $dev = NULL;
    foreach (nmcliLines(array('-t', '-e', 'yes', '-f', 'GENERAL.DEVICE,IP4.GATEWAY', 'device', 'show')) as $l) {
        $m = NULL;
        if (preg_match('/^GENERAL\.DEVICE:(.*)$/', $l, $m)) {
            $dev = trim($m[1]);
        } else if (preg_match('/^IP4\.GATEWAY:(.+)$/', $l, $m) && trim($m[1]) !== '') {
            return $dev;
        }
    }
    return NULL;
}

// Conexión "principal": la de la ruta por defecto; si no, la primera ethernet.
function primaryConnection()
{
    $dev = defaultRouteDevice();
    if ($dev !== NULL) {
        $conn = connectionForDevice($dev);
        if ($conn !== NULL) return $conn;
    }
    foreach (activeConnectionNames() as $name) {
        $type = nmcliLines(array('-g', 'connection.type', 'con', 'show', $name));
        if (count($type) > 0 && in_array(trim($type[0]), array('802-3-ethernet', 'vlan')))
            return $name;
    }
    return NULL;
}

// Interfaz asociada a una conexión (connection.interface-name).
function deviceForConnection($conn)
{
    $info = nmcliLines(array('-g', 'connection.interface-name', 'con', 'show', $conn));
    return (count($info) > 0) ? trim($info[0]) : '';
}

// Interfaz cuya subred IPv4 contiene la IP dada (para clasificar la de gestión).
function deviceSubnetContaining($ip)
{
    if (empty($ip) || filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) return NULL;
    $client = ip2long($ip);
    if ($client === FALSE) return NULL;
    $ret = NULL; $out = array();
    runCommand(array('/usr/bin/env', 'LC_ALL=C', 'LANG=C', '/usr/sbin/ip', '-4', '-o', 'addr', 'show'), $ret, $out);
    foreach ($out as $line) {
        $m = NULL;
        if (preg_match('/^\d+:\s+(\S+)\s+inet (\d+\.\d+\.\d+\.\d+)\/(\d+)/', $line, $m)) {
            $net = ip2long($m[2]);
            $mask = (int)$m[3];
            if ($net === FALSE) continue;
            $maskbits = ($mask === 0) ? 0 : ((0xFFFFFFFF << (32 - $mask)) & 0xFFFFFFFF);
            if (($client & $maskbits) === ($net & $maskbits)) return $m[1];
        }
    }
    return NULL;
}

// Interfaz de gestión: la que sirve la petición, o la de la ruta por defecto.
function managementDevice($clientIp)
{
    if (!empty($clientIp)) {
        $dev = deviceSubnetContaining($clientIp);
        if ($dev !== NULL) return $dev;
    }
    return defaultRouteDevice();
}

// Valida una lista de rutas en sintaxis nmcli:
//   "ip[/prefix] [next-hop] [metric] [attr=val]...[, ip[/prefix] ...]"
// Acepta lista vacía (limpia las rutas). IPv4 e IPv6.
function validRouteSpec($spec)
{
    $spec = trim($spec);
    if ($spec === '') return TRUE;
    foreach (explode(',', $spec) as $entry) {
        $entry = trim($entry);
        if ($entry === '') continue;
        $parts = preg_split('/\s+/', $entry);
        $dest = $parts[0];
        if (preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\/(\d{1,2})$/', $dest, $m)) {
            for ($i = 1; $i <= 4; $i++) if ($m[$i] > 255) return FALSE;
            if ($m[5] > 32) return FALSE;
        } else {
            $p6 = explode('/', $dest, 2);
            if (count($p6) != 2
                || filter_var($p6[0], FILTER_VALIDATE_IP, FILTER_FLAG_IPV6) === false
                || !ctype_digit($p6[1]) || intval($p6[1]) > 128) return FALSE;
        }
        $i = 1;
        if (isset($parts[$i]) && filter_var($parts[$i], FILTER_VALIDATE_IP) !== false) $i++; // next-hop
        if (isset($parts[$i]) && ctype_digit($parts[$i])) $i++;                             // metric
        for (; $i < count($parts); $i++) if (strpos($parts[$i], '=') === FALSE) return FALSE; // atributos
    }
    return TRUE;
}

// Máscara punteada -> longitud de prefijo.
function netmaskToPrefix($mask)
{
    $bits = 0;
    foreach (explode('.', $mask) as $octeto) {
        $o = (int)$octeto & 0xFF;
        while (($o & 0x80) != 0) { $bits++; $o = ($o << 1) & 0xFF; }
    }
    return $bits;
}

/* ------------------------------------------------------------------------- *
 *  Aplicación segura (commit-confirm)
 * ------------------------------------------------------------------------- */

function acquireLock()
{
    global $LOCK_HANDLE;
    if (!is_dir(STATE_DIR)) @mkdir(STATE_DIR, 0700, TRUE);
    $LOCK_HANDLE = @fopen(LOCK_FILE, 'c');
    if ($LOCK_HANDLE === FALSE) return FALSE;
    if (!flock($LOCK_HANDLE, LOCK_EX)) return FALSE;
    @chmod(LOCK_FILE, 0600);
    return TRUE;
}

function releaseLock()
{
    global $LOCK_HANDLE;
    if ($LOCK_HANDLE) { flock($LOCK_HANDLE, LOCK_UN); fclose($LOCK_HANDLE); $LOCK_HANDLE = NULL; }
}

function stateDir($token) { return STATE_DIR.'/'.$token; }

function readPending()
{
    if (!is_file(PENDING_FILE)) return NULL;
    $data = json_decode(file_get_contents(PENDING_FILE), TRUE);
    return is_array($data) ? $data : NULL;
}

// Copia todos los perfiles de NetworkManager al snapshot del token.
// Devuelve la lista de perfiles copiados, o FALSE si no pudo crear el snapshot.
function snapshotProfiles($token)
{
    $dir = stateDir($token);
    if (!is_dir($dir) && !@mkdir($dir, 0700, TRUE)) return FALSE;
    if (!is_dir($dir.'/profiles') && !@mkdir($dir.'/profiles', 0700, TRUE)) return FALSE;

    $files = array();
    foreach (glob('/etc/NetworkManager/system-connections/*') as $f) {
        if (is_file($f)) {
            $base = basename($f);
            if (copy($f, $dir.'/profiles/'.$base)) {
                @chmod($dir.'/profiles/'.$base, 0600);
                $files[] = $base;
            }
        }
    }
    return $files;
}

// Escribe el estado inicial del snapshot (conexiones, activas y perfiles).
function writeMeta($token, $connections, $active, $profiles)
{
    $dir = stateDir($token);
    $meta = array(
        'token'       => $token,
        'connections' => $connections,
        'active'      => $active,
        'profiles'    => $profiles,
    );
    file_put_contents($dir.'/meta.json', json_encode($meta)."\n");
    @chmod($dir.'/meta.json', 0600);
}

function writePending($token, $summary, $timeout, $expires)
{
    $data = array(
        'token'    => $token,
        'summary'  => $summary,
        'created'  => time(),
        'expires'  => $expires,
        'timeout'  => $timeout,
    );
    file_put_contents(PENDING_FILE, json_encode($data)."\n");
    @chmod(PENDING_FILE, 0600);

    // Estado legible por la GUI (sin token) para el aviso global del framework.
    $status = array(
        'summary' => $summary,
        'expires' => $expires,
    );
    file_put_contents(STATE_DIR.'/status.json', json_encode($status)."\n");
    @chmod(STATE_DIR.'/status.json', 0644);
}

// Restaura los perfiles del snapshot y reactiva las conexiones que lo estaban.
function restoreProfiles($token)
{
    $dir = stateDir($token);
    if (!is_dir($dir.'/profiles')) return FALSE;

    $meta = NULL;
    if (is_file($dir.'/meta.json')) $meta = json_decode(file_get_contents($dir.'/meta.json'), TRUE);

    // Borra las conexiones creadas después del snapshot.
    if (is_array($meta) && isset($meta['profiles']) && is_array($meta['profiles'])) {
        foreach (glob('/etc/NetworkManager/system-connections/*') as $f) {
            if (is_file($f) && !in_array(basename($f), $meta['profiles']))
                @unlink($f);
        }
    }

    // Restaura los perfiles guardados.
    foreach (glob($dir.'/profiles/*') as $f) {
        $dst = '/etc/NetworkManager/system-connections/'.basename($f);
        copy($f, $dst);
        @chmod($dst, 0600);
    }
    nmcliLines(array('con', 'reload'));

    if (is_array($meta) && isset($meta['connections'])) {
        foreach ($meta['connections'] as $conn) {
            $ret = NULL; $out = array();
            $argv = array('/usr/bin/env', 'LC_ALL=C', 'LANG=C', NMCLI,
                '--wait', '30', 'con', 'up', $conn);
            runCommand($argv, $ret, $out);
        }
    }
    return TRUE;
}

function cleanupState($token)
{
    $dir = stateDir($token);
    if (is_dir($dir)) {
        foreach (glob($dir.'/profiles/*') as $f) @unlink($f);
        @unlink($dir.'/meta.json');
        @rmdir($dir.'/profiles');
        @rmdir($dir);
    }
    if (is_file(PENDING_FILE)) @unlink(PENDING_FILE);
    if (is_file(STATE_DIR.'/status.json')) @unlink(STATE_DIR.'/status.json');
}

function scheduleRollback($token, $seconds)
{
    $unit = 'issabel-netconfig-rollback-'.$token;
    $ret = NULL; $out = array();
    runCommand(array(
        '/usr/bin/systemd-run',
        '--collect',
        '--on-active='.$seconds,
        '--unit='.$unit,
        SELF, '--rollback', $token,
    ), $ret, $out);
    if ($ret != 0) {
        fwrite(STDERR, "ERR: failed to schedule rollback - ".implode(' ', $out)."\n");
        return FALSE;
    }
    return TRUE;
}

function cancelRollback($token)
{
    $unit = 'issabel-netconfig-rollback-'.$token;
    foreach (array($unit.'.timer', $unit.'.service') as $u) {
        $ret = NULL; $out = array();
        runCommand(array('/usr/bin/systemctl', 'stop', $u), $ret, $out);
    }
    $ret = NULL; $out = array();
    runCommand(array('/usr/bin/systemctl', 'reset-failed', $unit.'.timer', $unit.'.service'), $ret, $out);
}

// Aplica un cambio de forma segura. $applyFn debe devolver TRUE/FALSE.
function applySafely($summary, $timeout, $applyFn)
{
    if (!acquireLock()) {
        fwrite(STDERR, "ERR: unable to acquire state lock\n");
        return FALSE;
    }
    if (readPending() !== NULL) {
        fwrite(STDERR, "ERR: there is a pending network change; confirm or roll it back first\n");
        releaseLock();
        return FALSE;
    }

    $token = bin2hex(random_bytes(8));
    $connections = listConnectionNames();
    $active = activeConnectionNames();
    $profiles = snapshotProfiles($token);
    if ($profiles === FALSE) {
        fwrite(STDERR, "ERR: unable to snapshot NetworkManager profiles\n");
        releaseLock();
        return FALSE;
    }
    writeMeta($token, $connections, $active, $profiles);

    if (!call_user_func($applyFn)) {
        fwrite(STDERR, "ERR: applying the change failed; rolling back\n");
        restoreProfiles($token);
        cleanupState($token);
        releaseLock();
        return FALSE;
    }

    $expires = time() + $timeout;
    writePending($token, $summary, $timeout, $expires);
    if (!scheduleRollback($token, $timeout)) {
        // Sin timer no hay red de seguridad: revertir de inmediato.
        restoreProfiles($token);
        cleanupState($token);
        releaseLock();
        return FALSE;
    }
    releaseLock();

    printf("pending token=%s expires=%d timeout=%d\n", $token, $expires, $timeout);
    return TRUE;
}

/* ------------------------------------------------------------------------- *
 *  Acciones
 * ------------------------------------------------------------------------- */

// Ejecuta la configuración general (hostname, DNS, gateway).
function action_generalConfiguration($opt)
{
    $sHostname = $sGateway = $sDNS1 = $sDNS2 = $sDNS6 = NULL;
    $timeout = 180;
    foreach ($opt[0] as $option) switch ($option[0]) {
    case '--host':      $sHostname = $option[1]; break;
    case '--gateway':   $sGateway  = $option[1]; break;
    case '--dns1':      $sDNS1     = $option[1]; break;
    case '--dns2':      $sDNS2     = $option[1]; break;
    case '--dns6':      $sDNS6     = $option[1]; break;
    case '--timeout':   $timeout   = intval($option[1]); break;
    }

    if (is_null($sDNS1) && !is_null($sDNS2)) {
        fwrite(STDERR, "ERR: DNS 2 requires DNS 1 to be set\n");
        return FALSE;
    }
    if (!is_null($sGateway) || !is_null($sDNS1)) {
        // Cambiar gateway/DNS puede cortar la administración remota.
        $timeout = ($timeout == 180) ? DEFAULT_TIMEOUT : $timeout;
    }

    $summary = 'genconf';
    if (!is_null($sHostname)) $summary .= ' host='.$sHostname;
    if (!is_null($sGateway))  $summary .= ' gateway='.$sGateway;
    if (!is_null($sDNS1))     $summary .= ' dns='.$sDNS1.(is_null($sDNS2)?'':' '.$sDNS2);
    if (!is_null($sDNS6))     $summary .= ' dns6='.$sDNS6;

    return applySafely($summary, $timeout, function() use ($sHostname, $sGateway, $sDNS1, $sDNS2, $sDNS6) {
        $primary = primaryConnection();

        if (!is_null($sGateway)) {
            if (is_null($primary)) {
                fwrite(STDERR, "ERR: no NetworkManager connection to set the gateway on\n");
                return FALSE;
            }
            if (!nmcliMod($primary, array('ipv4.gateway' => $sGateway))) return FALSE;
            foreach (activeConnectionNames() as $c) {
                if ($c !== $primary) nmcliMod($c, array('ipv4.never-default' => 'yes'));
            }
            if (!nmcliUp($primary)) return FALSE;
        }

        if (!is_null($sDNS1)) {
            if (is_null($primary)) {
                fwrite(STDERR, "ERR: no NetworkManager connection to set DNS on\n");
                return FALSE;
            }
            $dns = is_null($sDNS2) ? $sDNS1 : $sDNS1.' '.$sDNS2;
            if (!nmcliMod($primary, array('ipv4.dns' => $dns, 'ipv4.ignore-auto-dns' => 'yes')))
                return FALSE;
            if (!nmcliUp($primary)) return FALSE;
        }

        if (!is_null($sHostname)) setHostname($sHostname);

        if (!is_null($sDNS6)) {
            if (is_null($primary)) {
                fwrite(STDERR, "ERR: no NetworkManager connection to set IPv6 DNS on\n");
                return FALSE;
            }
            if (!nmcliMod($primary, array('ipv6.dns' => $sDNS6, 'ipv6.ignore-auto-dns' => 'yes')))
                return FALSE;
            if (!nmcliUp($primary)) return FALSE;
        }

        return TRUE;
    });
}

// Configura una interfaz concreta (static o dhcp).
function action_interfaceConfiguration($opt)
{
    $sDevice = $sBootproto = $sIpAddr = $sNetMask = NULL;
    $sIp6Method = $sIp6Addr = $sIp6Gw = NULL;
    $timeout = DEFAULT_TIMEOUT;
    foreach ($opt[0] as $option) switch ($option[0]) {
    case '--device':    $sDevice    = $option[1]; break;
    case '--bootproto': $sBootproto = $option[1]; break;
    case '--ipaddr':    $sIpAddr    = $option[1]; break;
    case '--netmask':   $sNetMask   = $option[1]; break;
    case '--ip6method': $sIp6Method = $option[1]; break;
    case '--ip6addr':   $sIp6Addr   = $option[1]; break;
    case '--ip6gw':     $sIp6Gw     = $option[1]; break;
    case '--timeout':   $timeout    = intval($option[1]); break;
    }

    if (is_null($sDevice)) {
        fwrite(STDERR, "ERR: network device must be specified\n");
        return FALSE;
    }
    if (is_null($sBootproto)) {
        fwrite(STDERR, "ERR: bootproto must be either dhcp or static\n");
        return FALSE;
    }
    if ($sBootproto == 'static') {
        if (is_null($sIpAddr)) {
            fwrite(STDERR, "ERR: --bootproto static requires --ipaddr\n");
            return FALSE;
        }
        if (is_null($sNetMask)) {
            fwrite(STDERR, "ERR: --bootproto static requires --netmask\n");
            return FALSE;
        }
    }

    $conn = connectionForDevice($sDevice);
    // Si no existe la conexión, createConnectionForDevice() la crea dentro del
    // apply seguro (así la reversión la elimina si el cambio no se confirma).

    if ($sBootproto == 'dhcp') {
        $props = array(
            'ipv4.method'    => 'auto',
            'ipv4.addresses' => '',
            'ipv4.gateway'   => '',
        );
    } else {
        $prefix = netmaskToPrefix($sNetMask);
        $props = array(
            'ipv4.method'    => 'manual',
            'ipv4.addresses' => $sIpAddr.'/'.$prefix,
        );
    }

    // IPv6 (opcional): método auto/dhcp/disabled o dirección estática + gateway.
    if (!is_null($sIp6Method) || !is_null($sIp6Addr) || !is_null($sIp6Gw)) {
        if (is_null($sIp6Method)) $sIp6Method = is_null($sIp6Addr) ? 'auto' : 'manual';
        $props['ipv6.method'] = $sIp6Method;
        if ($sIp6Method === 'manual') {
            if (is_null($sIp6Addr)) {
                fwrite(STDERR, "ERR: IPv6 method manual requires --ip6addr\n");
                return FALSE;
            }
            $props['ipv6.addresses'] = $sIp6Addr;
        } else {
            // Limpia direcciones estáticas previas al pasar a auto/dhcp/disabled.
            $props['ipv6.addresses'] = '';
            if ($sIp6Method === 'disabled') $props['ipv6.gateway'] = '';
        }
        if (!is_null($sIp6Gw)) $props['ipv6.gateway'] = $sIp6Gw;
    }

    $summary = 'ifconf device='.$sDevice.' bootproto='.$sBootproto
        .($sBootproto == 'static' ? ' addr='.$sIpAddr.'/'.netmaskToPrefix($sNetMask) : '')
        .($sIp6Method !== NULL ? ' ipv6='.$sIp6Method.(is_null($sIp6Addr) ? '' : ' '.$sIp6Addr) : '');

    return applySafely($summary, $timeout, function() use ($sDevice, $conn, $props) {
        $connection = $conn;
        if (is_null($connection)) {
            $connection = createConnectionForDevice($sDevice);
            if (is_null($connection)) return FALSE;
        }
        if (!nmcliMod($connection, $props)) return FALSE;
        return nmcliUp($connection);
    });
}

// Cancela la reversión de un cambio pendiente.
function action_confirm($token)
{
    if (!acquireLock()) { fwrite(STDERR, "ERR: unable to acquire state lock\n"); return FALSE; }
    $pending = readPending();
    if ($pending === NULL || !isset($pending['token']) || $pending['token'] !== $token) {
        fwrite(STDERR, "ERR: no such pending change\n");
        releaseLock();
        return FALSE;
    }
    cancelRollback($token);
    cleanupState($token);
    releaseLock();
    echo "confirmed $token\n";
    return TRUE;
}

// Aplica el snapshot de un cambio (invocado por el timer, o a mano).
function action_rollback($token)
{
    if (!acquireLock()) { fwrite(STDERR, "ERR: unable to acquire state lock\n"); return FALSE; }
    if (!is_dir(stateDir($token))) {
        fwrite(STDERR, "ERR: no snapshot for token $token\n");
        releaseLock();
        return FALSE;
    }
    $ok = restoreProfiles($token);
    cleanupState($token);
    releaseLock();
    echo "rolled back $token\n";
    return $ok;
}

// Imprime el cambio pendiente (JSON) para que la GUI pueda avisar.
function action_pending()
{
    $pending = readPending();
    if ($pending === NULL) {
        echo json_encode(array('pending' => FALSE))."\n";
        return TRUE;
    }
    $pending['pending'] = TRUE;
    $pending['remaining'] = max(0, intval($pending['expires']) - time());
    echo json_encode($pending)."\n";
    return TRUE;
}

// Revierte un cambio pendiente al arrancar (lo invoca issabel-netconfig-recover).
function action_recover()
{
    $pending = readPending();
    if ($pending === NULL || !isset($pending['token'])) return TRUE; // nada que hacer
    $token = $pending['token'];
    cancelRollback($token);
    return action_rollback($token);
}

// Imprime las rutas estáticas IPv4 por interfaz (JSON) para la grilla de la GUI.
function action_getroutes()
{
    $result = array();
    foreach (listConnectionNames() as $name) {
        $dev = nmcliLines(array('-g', 'connection.interface-name', 'con', 'show', $name));
        $dev = (count($dev) > 0) ? trim($dev[0]) : '';
        if ($dev === '') continue;
        $type = nmcliLines(array('-g', 'connection.type', 'con', 'show', $name));
        $type = (count($type) > 0) ? trim($type[0]) : '';
        if (!in_array($type, array('802-3-ethernet', 'vlan'))) continue;

        $specs = array();
        foreach (nmcliLines(array('-g', 'ipv4.routes', 'con', 'show', $name)) as $line) {
            foreach (explode(',', $line) as $s) {
                $s = trim($s);
                if ($s !== '') $specs[] = $s;
            }
        }
        $result[$dev] = $specs;
    }
    echo json_encode($result)."\n";
    return TRUE;
}

// Imprime el método IPv4/IPv6 configurado por interfaz (JSON) para la grilla de
// la GUI: permite ver de un vistazo que una interfaz tiene IPv6 'disabled'.
function action_getmethods()
{
    $result = array();
    foreach (listConnectionNames() as $name) {
        $dev = nmcliLines(array('-g', 'connection.interface-name', 'con', 'show', $name));
        $dev = (count($dev) > 0) ? trim($dev[0]) : '';
        if ($dev === '') continue;
        $type = nmcliLines(array('-g', 'connection.type', 'con', 'show', $name));
        $type = (count($type) > 0) ? trim($type[0]) : '';
        if (!in_array($type, array('802-3-ethernet', 'vlan'))) continue;

        $m4 = nmcliLines(array('-g', 'ipv4.method', 'con', 'show', $name));
        $m6 = nmcliLines(array('-g', 'ipv6.method', 'con', 'show', $name));
        $result[$dev] = array(
            'ipv4' => (count($m4) > 0) ? trim($m4[0]) : '',
            'ipv6' => (count($m6) > 0) ? trim($m6[0]) : '',
        );
    }
    echo json_encode($result)."\n";
    return TRUE;
}

// Fija la lista completa de rutas estáticas IPv4 de una interfaz (apply seguro).
function action_setroutes($opt)
{
    $sDevice = NULL;
    $sSpec = '';
    $timeout = DEFAULT_TIMEOUT;
    foreach ($opt[0] as $option) switch ($option[0]) {
    case '--device':    $sDevice  = $option[1]; break;
    case '--routespec': $sSpec    = $option[1]; break;
    case '--timeout':   $timeout  = intval($option[1]); break;
    }

    if (is_null($sDevice)) {
        fwrite(STDERR, "ERR: --setroutes requires --device\n");
        return FALSE;
    }
    if (!validRouteSpec($sSpec)) {
        fwrite(STDERR, "ERR: invalid route specification\n");
        return FALSE;
    }

    $conn = connectionForDevice($sDevice);
    if (is_null($conn)) {
        fwrite(STDERR, "ERR: no NetworkManager connection bound to device $sDevice\n");
        return FALSE;
    }

    $summary = 'routes device='.$sDevice.' ['.$sSpec.']';

    return applySafely($summary, $timeout, function() use ($conn, $sSpec) {
        if (!nmcliMod($conn, array('ipv4.routes' => $sSpec))) return FALSE;
        return nmcliUp($conn);
    });
}

// Aplica un conjunto de cambios de forma atómica, con una sola confirmación si
// es bloqueante. JSON:
//   { "ifconf":[{"device","bootproto","ipaddr?","netmask?","ip6method?","ip6addr?","ip6gw?"}],
//     "genconf":{"gateway?","dns1?","dns2?","dns6?","host?"},
//     "routes":[{"device","routespec"}] }
function action_apply($opt)
{
    $sChange = NULL;
    $clientIp = NULL;
    foreach ($opt[0] as $option) switch ($option[0]) {
    case '--change':    $sChange  = $option[1]; break;
    case '--client-ip': $clientIp = $option[1]; break;
    }
    if (is_null($sChange)) {
        fwrite(STDERR, "ERR: --apply requires --change\n");
        return FALSE;
    }
    $change = json_decode($sChange, TRUE);
    if (!is_array($change)) {
        fwrite(STDERR, "ERR: invalid change set\n");
        return FALSE;
    }

    $mgmtDev  = managementDevice($clientIp);
    $mgmtConn = ($mgmtDev !== NULL) ? connectionForDevice($mgmtDev) : NULL;

    $props = array();     // conexión => propiedades (mod + up)
    $modOnly = array();   // conexión => propiedades (solo mod)
    $create = array();    // interfaces cuya conexión hay que crear
    $host = NULL;
    $blocking = FALSE;
    $summaryParts = array();

    // --- ifconf ---
    if (isset($change['ifconf']) && is_array($change['ifconf'])) {
        foreach ($change['ifconf'] as $op) {
            if (!is_array($op) || empty($op['device'])) {
                fwrite(STDERR, "ERR: ifconf requires device\n");
                return FALSE;
            }
            $dev = $op['device'];
            $conn = connectionForDevice($dev);
            if ($conn === NULL) { $conn = $dev; $create[$dev] = TRUE; }

            $p = array();
            $bootproto = isset($op['bootproto']) ? $op['bootproto'] : NULL;
            if ($bootproto === 'dhcp') {
                $p['ipv4.method'] = 'auto';
                $p['ipv4.addresses'] = '';
                $p['ipv4.gateway'] = '';
            } else if ($bootproto === 'static') {
                if (empty($op['ipaddr']) || empty($op['netmask'])) {
                    fwrite(STDERR, "ERR: static requires ipaddr and netmask\n");
                    return FALSE;
                }
                $p['ipv4.method'] = 'manual';
                $p['ipv4.addresses'] = $op['ipaddr'].'/'.netmaskToPrefix($op['netmask']);
            }
            if (!empty($op['ip6method']) || !empty($op['ip6addr']) || !empty($op['ip6gw'])) {
                $m = !empty($op['ip6method']) ? $op['ip6method'] : (empty($op['ip6addr']) ? 'auto' : 'manual');
                $p['ipv6.method'] = $m;
                if ($m === 'manual') {
                    if (empty($op['ip6addr'])) {
                        fwrite(STDERR, "ERR: IPv6 method manual requires ip6addr\n");
                        return FALSE;
                    }
                    $p['ipv6.addresses'] = $op['ip6addr'];
                } else {
                    $p['ipv6.addresses'] = '';
                    if ($m === 'disabled') $p['ipv6.gateway'] = '';
                }
                if (!empty($op['ip6gw'])) $p['ipv6.gateway'] = $op['ip6gw'];
            }
            $props[$conn] = isset($props[$conn]) ? array_merge($props[$conn], $p) : $p;
            $summaryParts[] = 'ifconf '.$dev;
            if ($bootproto !== NULL && $dev === $mgmtDev) $blocking = TRUE;
        }
    }

    // --- genconf ---
    if (isset($change['genconf']) && is_array($change['genconf'])) {
        $g = $change['genconf'];
        $primary = primaryConnection();
        if ((!empty($g['gateway']) || !empty($g['dns1']) || !empty($g['dns6'])) && $primary === NULL) {
            fwrite(STDERR, "ERR: no primary connection\n");
            return FALSE;
        }
        if (!empty($g['gateway'])) {
            $add = array('ipv4.gateway' => $g['gateway']);
            $props[$primary] = isset($props[$primary]) ? array_merge($props[$primary], $add) : $add;
            foreach (activeConnectionNames() as $c) if ($c !== $primary) $modOnly[$c] = array('ipv4.never-default' => 'yes');
            $pdev = deviceForConnection($primary);
            if ($pdev !== '' && $pdev === $mgmtDev) $blocking = TRUE;
            $summaryParts[] = 'gateway='.$g['gateway'];
        }
        if (!empty($g['dns1'])) {
            $dns = $g['dns1'].(!empty($g['dns2']) ? ' '.$g['dns2'] : '');
            $add = array('ipv4.dns' => $dns, 'ipv4.ignore-auto-dns' => 'yes');
            $props[$primary] = isset($props[$primary]) ? array_merge($props[$primary], $add) : $add;
            $summaryParts[] = 'dns='.$dns;
        }
        if (!empty($g['dns6'])) {
            $add = array('ipv6.dns' => $g['dns6'], 'ipv6.ignore-auto-dns' => 'yes');
            $props[$primary] = isset($props[$primary]) ? array_merge($props[$primary], $add) : $add;
            $summaryParts[] = 'dns6='.$g['dns6'];
        }
        if (!empty($g['host'])) { $host = $g['host']; $summaryParts[] = 'host='.$host; }
    }

    // --- routes ---
    if (isset($change['routes']) && is_array($change['routes'])) {
        foreach ($change['routes'] as $op) {
            if (!is_array($op) || empty($op['device']) || !array_key_exists('routespec', $op)) {
                fwrite(STDERR, "ERR: routes requires device and routespec\n");
                return FALSE;
            }
            $dev = $op['device'];
            $conn = connectionForDevice($dev);
            if ($conn === NULL) { $conn = $dev; $create[$dev] = TRUE; }
            if (!validRouteSpec((string)$op['routespec'])) {
                fwrite(STDERR, "ERR: invalid route specification for $dev\n");
                return FALSE;
            }
            $add = array('ipv4.routes' => $op['routespec']);
            $props[$conn] = isset($props[$conn]) ? array_merge($props[$conn], $add) : $add;
            $summaryParts[] = 'routes '.$dev;
            if ($dev === $mgmtDev) $blocking = TRUE;
        }
    }

    if (empty($props) && empty($modOnly) && is_null($host)) {
        fwrite(STDERR, "ERR: empty change set\n");
        return FALSE;
    }

    $plan = array(
        'props'   => $props,
        'modOnly' => $modOnly,
        'create'  => array_keys($create),
        'host'    => $host,
        'mgmt'    => $mgmtConn,
    );
    $summary = 'apply '.implode('; ', $summaryParts);

    if ($blocking) {
        return applySafely($summary, DEFAULT_TIMEOUT, function() use ($plan) {
            return runChangeSet($plan);
        });
    }
    // No bloqueante: se aplica sin ventana de confirmación.
    $ok = runChangeSet($plan);
    if ($ok) echo "applied\n";
    return $ok;
}

// Ejecuta un plan de change set ya validado (props por conexión + activación).
function runChangeSet($plan)
{
    foreach ($plan['create'] as $dev) {
        if (connectionForDevice($dev) === NULL) {
            if (createConnectionForDevice($dev) === NULL) return FALSE;
        }
    }
    foreach ($plan['modOnly'] as $conn => $props) {
        if (!nmcliMod($conn, $props)) return FALSE;
    }
    foreach ($plan['props'] as $conn => $props) {
        if (!nmcliMod($conn, $props)) return FALSE;
    }
    // Activa primero las que no son de gestión; la de gestión al final.
    foreach ($plan['props'] as $conn => $props) {
        if ($plan['mgmt'] !== NULL && $conn === $plan['mgmt']) continue;
        if (!nmcliUp($conn)) return FALSE;
    }
    if ($plan['mgmt'] !== NULL && isset($plan['props'][$plan['mgmt']])) {
        if (!nmcliUp($plan['mgmt'])) return FALSE;
    }
    if ($plan['host'] !== NULL) setHostname($plan['host']);
    return TRUE;
}

// Define el hostname del sistema y lo propaga a /etc/hosts y postfix.
function setHostname($sHostname)
{
    // hostnamectl puede fallar en entornos donde /etc/hostname no es escribible
    // (contenedores, fichero inmutable). Se avisa pero no se aborta: el fichero
    // se escribe igualmente unas líneas más abajo.
    $ret = NULL; $out = array();
    runCommand(array('/usr/bin/hostnamectl', 'set-hostname', $sHostname), $ret, $out);
    if ($ret != 0)
        fwrite(STDERR, "WARN: hostnamectl could not set the static hostname - ".implode(' ', $out)."\n");

    file_put_contents('/etc/hostname', "$sHostname\n");
    chmod('/etc/hostname', 0644);

    // En /etc/hosts, reemplaza el hostname de 127.0.0.1
    $bClavePresente = FALSE;
    $contenidoNuevo = array();
    foreach (file('/etc/hosts') as $sLinea) {
        if (preg_match('/^127\.0\.0\.1\s+/', $sLinea)) {
            $bClavePresente = TRUE;
            $contenidoNuevo[] = "127.0.0.1\tlocalhost $sHostname localhost.localdomain\n";
        } else {
            $contenidoNuevo[] = $sLinea;
        }
    }
    if ($bClavePresente) file_put_contents('/etc/hosts', $contenidoNuevo);

    // Figura un dominio para el hostname
    $partes = explode('.', $sHostname, 2);
    $sDomain = array_pop($partes);

    if (file_exists('/etc/postfix/main.cf')) {
        $bClavePresente = array('myhostname' => FALSE, 'mydomain' => FALSE);
        $contenidoNuevo = array();
        foreach (file('/etc/postfix/main.cf') as $sLinea) {
            if (preg_match('/^myhostname\s*=/', $sLinea)) {
                $bClavePresente['myhostname'] = TRUE;
                $contenidoNuevo[] = "myhostname = $sHostname\n";
            } elseif (preg_match('/^mydomain\s*=/', $sLinea)) {
                $bClavePresente['mydomain'] = TRUE;
                $contenidoNuevo[] = "mydomain = $sDomain\n";
            } else {
                $contenidoNuevo[] = $sLinea;
            }
        }
        if (!$bClavePresente['myhostname']) $contenidoNuevo[] = "myhostname = $sHostname\n";
        if (!$bClavePresente['mydomain']) $contenidoNuevo[] = "mydomain = $sDomain\n";
        file_put_contents('/etc/postfix/main.cf', $contenidoNuevo);
        exec('/usr/bin/systemctl restart postfix 2>/dev/null');
    }
}
?>
