#!/usr/bin/php8.3
<?php
/**
 * fnwsctl —— fn-webstack 受控特权助手
 *
 * 面板（www-data）唯一被允许 sudo 执行的就是本脚本，不接受命令行参数；
 * 所有请求以 JSON 形式从 stdin 传入，脚本内部做白名单校验后再操作 Nginx / MariaDB。
 *
 * 请求：{"action":"site.list","payload":{...}}
 * 响应：{"ok":true,"message":"...","data":{...}}
 *
 * v1.3.1：站点文件放 ${TRIM_APPDEST_VOL}/@appshare/wwwroot，数据库放
 *         ${TRIM_APPDEST_VOL}/@appshare/server/data；运行期可变状态（站点清单 /
 *         伪静态片段 / 站点 vhost）搬到数据盘，/etc 只保留安装期文件。
 *         原始说明：运行期可变状态全部搬到数据盘
 *         ${DATA_DIR}/conf，/etc 只保留安装期文件，绕开“面板进程写 /etc 被拦”；
 *         写失败时把 errno、目录可写性、剩余空间一起抛出来。
 * v1.2.3：status 返回真实局域网 IP；v1.2.2：svc.action 服务控制；
 * v1.2.0：落盘失败即报错；站点支持运行目录；清单原子写 + 回读校验；diag 自检。
 */

declare(strict_types=1);

const FNWSCTL_VERSION = '1.5.0';

// 仅安装期文件（生命周期脚本写入，运行期只读）
const CONF_DIR       = '/etc/fnwebstack';
const MYSQL_PASS     = CONF_DIR . '/mysql_root.pass';
const MYSQL_ADMIN_PASS = CONF_DIR . '/mysql_admin.pass';
const LEGACY_SITES   = CONF_DIR . '/sites.json';
const LEGACY_REWRITE = CONF_DIR . '/rewrite';

const NGINX_CONF_D   = '/etc/nginx/conf.d';
const PHP_SOCK       = 'unix:/run/php/php8.3-fpm.sock';
const SVC_WHITELIST  = ['nginx', 'php8.3-fpm', 'mariadb', 'redis-server'];

function out(bool $ok, $data = [], string $msg = ''): void
{
    echo json_encode(['ok' => $ok, 'message' => $msg, 'data' => $data], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), "\n";
    exit($ok ? 0 : 1);
}

function fail(string $msg): void
{
    out(false, [], $msg);
}

function sh(string $cmd): array
{
    $lines = [];
    $code = 0;
    exec($cmd . ' 2>&1', $lines, $code);
    return [$code, implode("\n", $lines)];
}

function runtimeEnv(): array
{
    static $cfg = null;
    if ($cfg !== null) {
        return $cfg;
    }
    $cfg = [
        'NGINX_HTTP_PORT'  => '8080',
        'NGINX_HTTPS_PORT' => '8443',
        'PANEL_PORT'       => '8081',
        'MYSQL_PORT'       => '3306',
        'REDIS_PORT'       => '6379',
        'DATA_DIR'         => '',
        'STATE_DIR'        => '',
        'WWW_DIR'          => '',
        'MYSQL_DATA'       => '',
    ];
    $f = CONF_DIR . '/runtime.env';
    if (is_readable($f)) {
        foreach (file($f, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) as $line) {
            if (strpos($line, '=') === false) {
                continue;
            }
            [$k, $v] = explode('=', $line, 2);
            $cfg[trim($k)] = trim($v);
        }
    }
    return $cfg;
}

function dataDir(): string
{
    static $d = null;
    if ($d !== null) {
        return $d;
    }
    $cfg = runtimeEnv();
    $d = rtrim((string)($cfg['DATA_DIR'] ?? ''), '/');
    if ($d === '' && !empty($cfg['STATE_DIR'])) {
        $d = rtrim(dirname(rtrim($cfg['STATE_DIR'], '/')), '/');
    }
    if ($d === '') {
        foreach (array_merge(glob('/vol*/@appshare/server', GLOB_ONLYDIR) ?: [],
                             glob('/vol*/fnwebstack', GLOB_ONLYDIR) ?: []) as $c) {
            $d = $c;
            break;
        }
    }
    return $d;
}

/** 站点根目录：优先 @appshare/wwwroot，退回数据盘 www */
function wwwDir(): string
{
    static $w = null;
    if ($w !== null) {
        return $w;
    }
    $cfg = runtimeEnv();
    $w = rtrim((string)($cfg['WWW_DIR'] ?? ''), '/');
    if ($w === '') {
        foreach (glob('/vol*/@appshare/wwwroot', GLOB_ONLYDIR) ?: [] as $c) {
            $w = $c;
            break;
        }
    }
    if ($w === '') {
        $vol = rtrim((string)($cfg['DATA_DIR'] ?? ''), '/');
        if ($vol !== '') {
            foreach (glob(dirname($vol) . '/@appshare/wwwroot', GLOB_ONLYDIR) ?: [] as $c) {
                $w = $c;
                break;
            }
        }
    }
    if ($w === '') {
        $w = dataDir() . '/www';
    }
    return $w;
}

/** 运行期状态目录：数据盘上的 conf（不用 /etc） */
function stateDir(): string
{
    static $d = null;
    if ($d !== null) {
        return $d;
    }
    $cfg = runtimeEnv();
    $d = !empty($cfg['STATE_DIR'])
        ? rtrim($cfg['STATE_DIR'], '/')
        : dataDir() . '/conf';
    return $d;
}

function stateSites(): string { return stateDir() . '/sites.json'; }
function stateRewrite(): string { return stateDir() . '/rewrite'; }
function stateVhost(): string { return stateDir() . '/nginx'; }

/** 确保状态目录存在，并把 1.2.x 留在 /etc 的数据迁移过来（只做一次） */
function ensureState(): void
{
    static $done = false;
    if ($done) {
        return;
    }
    $done = true;

    $base = stateDir();
    if ($base === '' || $base === '/conf') {
        fail('未取得数据目录（runtime.env 的 DATA_DIR 为空），无法定位站点状态目录');
    }
    foreach ([$base, stateRewrite(), stateVhost()] as $d) {
        if (!is_dir($d) && !@mkdir($d, 0755, true)) {
            fail('创建状态目录失败：' . $d . '（检查数据盘是否可写）');
        }
    }

    if (!is_file(stateSites()) && is_file(LEGACY_SITES)) {
        @copy(LEGACY_SITES, stateSites());
    }
    if (!is_file(stateSites())) {
        @file_put_contents(stateSites(), '{"sites":[]}');
    }
    if (is_dir(LEGACY_REWRITE)) {
        foreach (glob(LEGACY_REWRITE . '/*') ?: [] as $f) {
            $to = stateRewrite() . '/' . basename($f);
            if (!is_file($to)) {
                @copy($f, $to);
            }
        }
    }
    @chmod($base, 0755);
    @chmod(stateSites(), 0644);
    @chmod(stateRewrite(), 0755);
    @chmod(stateVhost(), 0755);
    foreach (array_merge(glob(stateRewrite() . '/*') ?: [], glob(stateVhost() . '/*') ?: []) as $f) {
        @chmod($f, 0644);
    }
}

/** 写文件；失败时把 errno、目录可写性、剩余空间一并抛出来 */
function writeFile(string $path, string $content): void
{
    $dir = dirname($path);
    if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
        throw new RuntimeException('创建目录失败：' . $dir);
    }
    $n = @file_put_contents($path, $content);
    if ($n === false || $n !== strlen($content)) {
        $last = error_get_last();
        $free = @disk_free_space($dir);
        throw new RuntimeException(sprintf(
            '写入 %s 失败：%s（目录存在=%s，可写=%s，剩余=%s）',
            $path,
            isset($last['message']) ? preg_replace('/^.*?:\s*/', '', $last['message']) : '未知错误',
            is_dir($dir) ? '是' : '否',
            is_writable($dir) ? '是' : '否',
            $free === false ? '未知' : round($free / 1048576, 1) . ' MB'
        ));
    }
    @chmod($path, 0644);
}

/** 读站点清单。文件损坏时抛异常，绝不静默返回空列表 */
function loadSites(): array
{
    ensureState();
    $file = stateSites();
    if (!is_file($file)) {
        return ['sites' => []];
    }
    $raw = @file_get_contents($file);
    if ($raw === false) {
        throw new RuntimeException('读取 ' . $file . ' 失败，请检查文件权限');
    }
    if (trim($raw) === '') {
        return ['sites' => []];
    }
    $j = json_decode($raw, true);
    if (!is_array($j) || !isset($j['sites']) || !is_array($j['sites'])) {
        throw new RuntimeException(
            '站点清单 ' . $file . ' 已损坏（' . strlen($raw) . ' 字节，' . json_last_error_msg() . '）'
        );
    }
    foreach ($j['sites'] as $i => $s) {
        if (!isset($j['sites'][$i]['run_dir'])) {
            $j['sites'][$i]['run_dir'] = '';
        }
    }
    return $j;
}

/** 原子写站点清单：先写 .tmp 再 rename，任何一步失败都会抛异常 */
function saveSites(array $data): void
{
    ensureState();
    $file = stateSites();
    $json = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
    if ($json === false) {
        throw new RuntimeException('站点清单编码失败：' . json_last_error_msg());
    }
    $tmp = $file . '.tmp';
    $n = @file_put_contents($tmp, $json);
    if ($n === false || $n !== strlen($json)) {
        $last = error_get_last();
        $free = @disk_free_space(dirname($file));
        throw new RuntimeException(sprintf(
            '写入 %s 失败：%s（可写=%s，剩余=%s）',
            $tmp,
            isset($last['message']) ? preg_replace('/^.*?:\s*/', '', $last['message']) : '未知错误',
            is_writable(dirname($file)) ? '是' : '否',
            $free === false ? '未知' : round($free / 1048576, 1) . ' MB'
        ));
    }
    @chmod($tmp, 0644);
    if (!@rename($tmp, $file)) {
        @unlink($tmp);
        throw new RuntimeException('替换 ' . $file . ' 失败，请检查文件是否被占用');
    }
    clearstatcache(true, $file);
}

function nginxReload(): void
{
    [$code, $msg] = sh('nginx -t');
    if ($code !== 0) {
        throw new RuntimeException("Nginx 配置校验失败：\n" . $msg);
    }
    [$code, $msg] = sh('systemctl reload nginx');
    if ($code !== 0) {
        throw new RuntimeException('Nginx 重载失败：' . $msg);
    }
}

function checkName(string $v): string
{
    if (!preg_match('/^[a-z0-9][a-z0-9\-]{0,30}$/', $v)) {
        fail('站点名只能由小写字母、数字、短横线组成，长度 1-31');
    }
    return $v;
}

function checkDbId(string $v): string
{
    if (!preg_match('/^[A-Za-z0-9_]{1,32}$/', $v)) {
        fail('库名/用户名只能由字母、数字、下划线组成，长度 1-32');
    }
    return $v;
}

function checkDomains($input): array
{
    $domains = array_values(array_filter(array_map('trim', (array)$input)));
    foreach ($domains as $d) {
        if (!preg_match('/^[A-Za-z0-9\.\-\_\*]{1,80}$/', $d)) {
            fail('域名格式不正确：' . $d);
        }
    }
    return $domains;
}

/** 运行目录（站点根下的子目录，如 public）；空串表示站点根即运行目录 */
function checkRunDir($v): string
{
    $v = trim((string)$v);
    $v = trim($v, '/');
    if ($v === '' || $v === '.') {
        return '';
    }
    if (strpos($v, '..') !== false) {
        fail('运行目录不能包含 ..');
    }
    if (!preg_match('#^[A-Za-z0-9_\-][A-Za-z0-9_\-/\.]{0,62}$#', $v)) {
        fail('运行目录只能用字母、数字、下划线、短横线、斜杠和点，且不能以斜杠开头');
    }
    return $v;
}

function siteRoot(array $cfg, string $name): string
{
    return wwwDir() . '/' . $name;
}

function siteDocRoot(array $cfg, string $name, string $runDir): string
{
    $root = siteRoot($cfg, $name);
    return $runDir === '' ? $root : $root . '/' . $runDir;
}

function mysqlRootPass(): string
{
    if (!is_readable(MYSQL_PASS)) {
        fail('缺少 MySQL root 凭据文件，请重新安装应用');
    }
    $p = trim((string)file_get_contents(MYSQL_PASS));
    if ($p === '') {
        fail('MySQL root 凭据为空');
    }
    return $p;
}

/** 用指定凭据执行一条 SQL；凭据为 __SOCKET__ 时走 unix_socket 免密 */
function mysqlRun(string $pass, string $sql): array
{
    if ($pass === '__SOCKET__') {
        return sh('mysql --protocol=socket -u root -N -B -e ' . escapeshellarg($sql));
    }
    return sh('MYSQL_PWD=' . escapeshellarg($pass) . ' mysql --protocol=socket -u root -N -B -e ' . escapeshellarg($sql));
}

/** 可用凭据候选：root 密码 → 备用管理账号 → unix_socket */
function mysqlCandidates(): array
{
    $c = [];
    foreach ([MYSQL_PASS => 'root.pass', MYSQL_ADMIN_PASS => 'admin.pass'] as $f => $label) {
        if (!is_readable($f)) {
            continue;
        }
        $p = trim((string)file_get_contents($f));
        if ($p !== '') {
            $c[$label] = $p;
        }
    }
    $c['socket'] = '__SOCKET__';
    return $c;
}

/** 执行 SQL，自动挑选可用凭据；本进程内记住成功的那一个 */
function mysqlExec(string $sql): array
{
    static $working = null;
    if ($working !== null) {
        return mysqlRun($working, $sql);
    }
    $tried = [];
    foreach (mysqlCandidates() as $label => $pass) {
        [$c] = mysqlRun($pass, 'SELECT 1');
        if ($c === 0) {
            $working = $pass;
            return mysqlRun($pass, $sql);
        }
        $tried[] = $label;
    }
    fail('连接 MariaDB 失败：root 密码、备用账号、unix_socket 均不可用（已尝试 ' . implode('/', $tried) . '）');
}

/** 写 600 root 的凭据文件 */
function writeSecret(string $path, string $value): bool
{
    $ok = @file_put_contents($path, $value) !== false;
    if ($ok) {
        @chmod($path, 0600);
        @chown($path, 'root');
        @chgrp($path, 'root');
    }
    return $ok;
}

function buildSiteConf(array $site, array $cfg): string
{
    $root    = siteRoot($cfg, $site['name']);
    $docRoot = siteDocRoot($cfg, $site['name'], (string)($site['run_dir'] ?? ''));
    $listen  = (int)$site['port'];
    $names   = implode(' ', $site['domains']);
    $frag    = stateRewrite() . '/' . $site['name'] . '.conf';
    $logDir  = rtrim($cfg['DATA_DIR'], '/') . '/logs/nginx';

    $php = '';
    if ($site['php']) {
        $sock = PHP_SOCK;
        $php = "\n    # PHP 交给独立的 php8.3-fpm socket\n"
             . "    location ~ \\.php$ {\n"
             . "        include snippets/fastcgi-php.conf;\n"
             . "        fastcgi_pass {$sock};\n"
             . "        fastcgi_read_timeout 300;\n"
             . "    }\n"
             . "\n    # 禁止直接访问隐藏文件\n"
             . "    location ~ /\\. { deny all; }\n";
    }

    $runNote = $site['run_dir'] !== ''
        ? "# 运行目录：站点根 / " . $site['run_dir'] . "（站点根 {$root}）\n"
        : "# 运行目录：站点根（{$root}）\n";

    return "# 由 fn-webstack 面板生成，请勿手改（重建/更新会被覆盖）\n"
        . $runNote
        . "server {\n"
        . "    listen {$listen};\n"
        . "    server_name {$names};\n"
        . "    root {$docRoot};\n"
        . "    index index.php index.html index.htm;\n"
        . "    client_max_body_size 100m;\n"
        . "    charset utf-8;\n"
        . $php
        . "\n    # 伪静态片段\n"
        . "    include {$frag};\n"
        . "\n    access_log {$logDir}/{$site['name']}.access.log;\n"
        . "    error_log  {$logDir}/{$site['name']}.error.log;\n"
        . "}\n";
}

function findSiteIndex(array $data, string $name): ?int
{
    foreach ($data['sites'] as $i => $s) {
        if (($s['name'] ?? '') === $name) {
            return (int)$i;
        }
    }
    return null;
}

function vhostEnabled(string $name): string { return stateVhost() . '/' . $name . '.conf'; }
function vhostDisabled(string $name): string { return stateVhost() . '/' . $name . '.conf.off'; }

/* ---------------------------- actions ---------------------------- */

/** 本机全局 IPv4，供面板拼访问入口 */
function lanIps(): array
{
    $ips = [];
    [$c, $out] = sh('ip -4 addr show scope global 2>&1');
    if ($c === 0 && preg_match_all('/inet\s+(\d+(?:\.\d+){3})\//', $out, $m)) {
        $ips = $m[1];
    }
    if (!$ips) {
        [$c, $hn] = sh('hostname -I 2>&1');
        if ($c === 0) {
            foreach (preg_split('/\s+/', trim($hn)) as $ip) {
                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
                    $ips[] = $ip;
                }
            }
        }
    }
    return array_values(array_unique($ips));
}

function actionStatus(array $p): void
{
    $cfg  = runtimeEnv();
    $svcs = [];
    foreach (SVC_WHITELIST as $s) {
        [$c] = sh('systemctl is-active --quiet ' . escapeshellarg($s));
        $svcs[$s] = $c === 0;
    }
    [$c, $ss] = sh('ss -ltn');
    $listen = [];
    if ($c === 0) {
        foreach (explode("\n", $ss) as $line) {
            if (preg_match('/:(\d+)\s/', $line, $m)) {
                $listen[(int)$m[1]] = true;
            }
        }
    }
    try {
        $siteCount = count(loadSites()['sites']);
    } catch (Throwable $e) {
        $siteCount = -1;
    }
    $ips = lanIps();
    out(true, [
        'services'   => $svcs,
        'ports'      => [
            'http'  => (int)$cfg['NGINX_HTTP_PORT'],
            'panel' => (int)$cfg['PANEL_PORT'],
            'mysql' => (int)$cfg['MYSQL_PORT'],
            'redis' => (int)$cfg['REDIS_PORT'],
        ],
        'listening'  => [
            'http'  => isset($listen[(int)$cfg['NGINX_HTTP_PORT']]),
            'panel' => isset($listen[(int)$cfg['PANEL_PORT']]),
            'mysql' => isset($listen[(int)$cfg['MYSQL_PORT']]),
            'redis' => isset($listen[(int)$cfg['REDIS_PORT']]),
        ],
        'data_dir'   => $cfg['DATA_DIR'],
        'state_dir'  => stateDir(),
        'www_dir'    => wwwDir(),
        'mysql_dir'  => $cfg['MYSQL_DATA'] !== '' ? $cfg['MYSQL_DATA'] : $cfg['DATA_DIR'] . '/data',
        'panel_port' => (int)$cfg['PANEL_PORT'],
        'site_count' => $siteCount,
        'lan_ip'     => $ips[0] ?? '',
        'lan_ips'    => $ips,
        'version'    => FNWSCTL_VERSION,
    ]);
}

/** 服务控制：服务名与操作都走白名单 */
function actionSvc(array $p): void
{
    $svc = (string)($p['service'] ?? '');
    $act = strtolower((string)($p['action'] ?? ''));
    if (!in_array($svc, SVC_WHITELIST, true)) {
        fail('不支持的服务：' . $svc);
    }
    if (!in_array($act, ['start', 'stop', 'restart', 'reload', 'status'], true)) {
        fail('不支持的操作：' . $act);
    }
    if ($act === 'status') {
        [$c, $out] = sh('systemctl is-active ' . escapeshellarg($svc) . ' 2>&1');
        out(true, ['service' => $svc, 'active' => $c === 0, 'detail' => trim($out)],
            $svc . ($c === 0 ? ' 正在运行' : ' 未运行'));
    }
    [$c, $out] = sh('systemctl ' . $act . ' ' . escapeshellarg($svc) . ' 2>&1');
    if ($c !== 0) {
        fail($svc . ' ' . $act . ' 失败：' . trim($out));
    }
    [$c2, $st] = sh('systemctl is-active ' . escapeshellarg($svc) . ' 2>&1');
    $active = $c2 === 0;
    if (in_array($act, ['start', 'restart'], true) && !$active) {
        fail($svc . ' 已执行 ' . $act . ' 但服务未能保持运行：' . trim($st));
    }
    $label = ['start' => '启动', 'stop' => '停止', 'restart' => '重启', 'reload' => '重载'][$act];
    out(true, ['service' => $svc, 'action' => $act, 'active' => $active],
        $svc . ' 已' . $label . ($active ? '' : '（当前未运行）'));
}

function actionSiteList(array $p): void
{
    $cfg = runtimeEnv();
    try {
        $data = loadSites();
    } catch (Throwable $e) {
        fail($e->getMessage());
    }
    $out = [];
    foreach ($data['sites'] as $s) {
        $root    = siteRoot($cfg, (string)$s['name']);
        $runDir  = (string)($s['run_dir'] ?? '');
        $docRoot = $runDir === '' ? $root : $root . '/' . $runDir;
        $s['run_dir']  = $runDir;
        $s['root']     = $root;
        $s['doc_root'] = $docRoot;
        $s['exists']   = is_dir($docRoot);
        $s['size_mb']  = is_dir($root)
            ? round((float)trim((string)@shell_exec('du -sm ' . escapeshellarg($root) . ' 2>/dev/null')), 1)
            : 0;
        $out[] = $s;
    }
    out(true, [
        'sites'         => $out,
        'default_port'  => (int)$cfg['NGINX_HTTP_PORT'],
        'data_dir'      => $cfg['DATA_DIR'],
        'state_dir'     => stateDir(),
        'www_dir'       => wwwDir(),
        'mysql_dir'     => $cfg['MYSQL_DATA'] !== '' ? $cfg['MYSQL_DATA'] : $cfg['DATA_DIR'] . '/data',
        'conf_writable' => is_writable(stateDir()),
    ]);
}

/** 列出站点根下的子目录，供面板选运行目录 */
function actionSiteDirs(array $p): void
{
    $name = checkName((string)($p['name'] ?? ''));
    $cfg  = runtimeEnv();
    $root = siteRoot($cfg, $name);
    $dirs = [];
    if (is_dir($root)) {
        foreach (scandir($root) ?: [] as $d) {
            if ($d === '.' || $d === '..') {
                continue;
            }
            if (is_dir($root . '/' . $d) && !is_link($root . '/' . $d)) {
                $dirs[] = $d;
            }
        }
    }
    sort($dirs);
    out(true, ['name' => $name, 'root' => $root, 'dirs' => $dirs]);
}

function actionRewriteList(array $p): void
{
    ensureState();
    $meta = [];
    $f = stateRewrite() . '/meta.json';
    if (is_file($f)) {
        $meta = json_decode((string)file_get_contents($f), true) ?: [];
    }
    $items = [];
    foreach ($meta as $m) {
        $file = stateRewrite() . '/' . ($m['file'] ?? '');
        $items[] = [
            'id'      => $m['id'] ?? '',
            'name'    => $m['name'] ?? '',
            'desc'    => $m['desc'] ?? '',
            'run_dir' => $m['run_dir'] ?? '',
            'content' => is_file($file) ? (string)file_get_contents($file) : '',
        ];
    }
    out(true, ['templates' => $items, 'dir' => stateRewrite()]);
}

function actionSiteCreate(array $p): void
{
    ensureState();

    $name    = checkName((string)($p['name'] ?? ''));
    $domains = checkDomains($p['domains'] ?? []);
    if (!$domains) {
        $domains = [$name . '.local'];
    }
    $tpl = (string)($p['template'] ?? 'none');
    if (!preg_match('/^[a-z0-9\-]{1,32}$/', $tpl) || !is_file(stateRewrite() . '/' . $tpl . '.conf')) {
        fail('伪静态模板不存在：' . $tpl);
    }
    $runDir = checkRunDir($p['run_dir'] ?? '');

    try {
        $data = loadSites();
    } catch (Throwable $e) {
        fail($e->getMessage());
    }

    foreach ($data['sites'] as $s) {
        if ($s['name'] === $name) {
            fail('站点名已存在');
        }
        $overlap = array_intersect($domains, (array)$s['domains']);
        if ($overlap) {
            fail('域名已被站点「' . $s['name'] . '」占用：' . implode(', ', $overlap));
        }
    }

    $cfg  = runtimeEnv();
    $port = (int)($p['port'] ?? (int)$cfg['NGINX_HTTP_PORT']);
    if ($port < 1024 || $port > 65535) {
        fail('端口需在 1024-65535 之间');
    }
    if ($port === (int)$cfg['PANEL_PORT']) {
        fail('不能占用面板端口');
    }
    foreach ($data['sites'] as $s) {
        if ((int)$s['port'] === $port && !empty($s['enabled'])) {
            fail('端口 ' . $port . ' 已被站点「' . $s['name'] . '」使用');
        }
    }

    $root    = siteRoot($cfg, $name);
    $docRoot = $runDir === '' ? $root : $root . '/' . $runDir;
    if (!is_dir($docRoot) && !@mkdir($docRoot, 0755, true)) {
        fail('创建站点目录失败：' . $docRoot . '（检查数据盘是否可写）');
    }

    $site = [
        'name'     => $name,
        'domains'  => $domains,
        'port'     => $port,
        'php'      => !empty($p['php']),
        'template' => $tpl,
        'run_dir'  => $runDir,
        'enabled'  => true,
        'created'  => date('Y-m-d H:i:s'),
    ];

    $conf     = vhostEnabled($name);
    $confOff  = vhostDisabled($name);
    $fragFile = stateRewrite() . '/' . $name . '.conf';

    try {
        $frag = (string)file_get_contents(stateRewrite() . '/' . $tpl . '.conf');
        $custom = trim((string)($p['custom_rewrite'] ?? ''));
        if ($custom !== '') {
            $frag .= "\n    # ---- 自定义规则 ----\n    " . str_replace("\n", "\n    ", $custom) . "\n";
        }
        writeFile($fragFile, $frag);
        writeFile($conf, buildSiteConf($site, $cfg));
        @unlink($confOff);

        if (!glob($docRoot . '/*')) {
            @file_put_contents($docRoot . '/index.html', "<!doctype html><meta charset=\"utf-8\"><title>{$name}</title><h2>{$name} 站点已就绪</h2>\n");
        }
        sh('chown -R www-data:www-data ' . escapeshellarg($root));

        // 先落盘清单，再校验 Nginx：任一失败都回滚
        $data['sites'][] = $site;
        saveSites($data);

        nginxReload();
    } catch (Throwable $e) {
        @unlink($conf);
        @unlink($fragFile);
        try {
            $rb = loadSites();
            $rb['sites'] = array_values(array_filter($rb['sites'], static fn($s) => $s['name'] !== $name));
            saveSites($rb);
        } catch (Throwable $ignore) {
        }
        fail($e->getMessage());
    }

    try {
        $check = loadSites();
        if (findSiteIndex($check, $name) === null) {
            fail('站点已写入配置，但清单回读不到该站点，请执行「环境自检」并把结果反馈');
        }
    } catch (Throwable $e) {
        fail($e->getMessage());
    }

    out(true, ['site' => $site], '站点已创建并生效');
}

function actionSiteUpdate(array $p): void
{
    ensureState();

    $name = checkName((string)($p['name'] ?? ''));
    try {
        $data = loadSites();
    } catch (Throwable $e) {
        fail($e->getMessage());
    }
    $idx = findSiteIndex($data, $name);
    if ($idx === null) {
        fail('站点不存在');
    }
    $site = $data['sites'][$idx];
    $cfg  = runtimeEnv();

    if (isset($p['domains'])) {
        $domains = checkDomains($p['domains']);
        foreach ($domains as $d) {
            foreach ($data['sites'] as $i => $s) {
                if ($i !== $idx && in_array($d, (array)$s['domains'], true)) {
                    fail('域名已被站点「' . $s['name'] . '」占用：' . $d);
                }
            }
        }
        $site['domains'] = $domains ?: [$name . '.local'];
    }
    if (isset($p['php'])) {
        $site['php'] = !empty($p['php']);
    }
    if (isset($p['template'])) {
        $t = (string)$p['template'];
        if (!preg_match('/^[a-z0-9\-]{1,32}$/', $t) || !is_file(stateRewrite() . '/' . $t . '.conf')) {
            fail('伪静态模板不存在');
        }
        $site['template'] = $t;
    }
    if (array_key_exists('run_dir', $p)) {
        $site['run_dir'] = checkRunDir($p['run_dir']);
    }
    if (!isset($site['run_dir'])) {
        $site['run_dir'] = '';
    }

    $docRoot = siteDocRoot($cfg, $name, (string)$site['run_dir']);
    if (!is_dir($docRoot) && !@mkdir($docRoot, 0755, true)) {
        fail('运行目录不存在且无法创建：' . $docRoot);
    }
    sh('chown -R www-data:www-data ' . escapeshellarg(siteRoot($cfg, $name)));

    $conf     = vhostEnabled($name);
    $fragFile = stateRewrite() . '/' . $name . '.conf';

    try {
        $frag = (string)file_get_contents(stateRewrite() . '/' . $site['template'] . '.conf');
        $custom = trim((string)($p['custom_rewrite'] ?? ''));
        if ($custom !== '') {
            $frag .= "\n    # ---- 自定义规则 ----\n    " . str_replace("\n", "\n    ", $custom) . "\n";
        }
        writeFile($fragFile, $frag);
        writeFile($conf, buildSiteConf($site, $cfg));
        nginxReload();
        $data['sites'][$idx] = $site;
        saveSites($data);
    } catch (Throwable $e) {
        fail($e->getMessage());
    }

    out(true, ['site' => $site], '站点配置已更新');
}

function actionSiteToggle(array $p): void
{
    ensureState();

    $name = checkName((string)($p['name'] ?? ''));
    try {
        $data = loadSites();
    } catch (Throwable $e) {
        fail($e->getMessage());
    }
    $idx = findSiteIndex($data, $name);
    if ($idx === null) {
        fail('站点不存在');
    }
    $enable  = !empty($p['enabled']);
    $conf    = vhostEnabled($name);
    $confOff = vhostDisabled($name);

    if ($enable) {
        if (!is_file($conf) && is_file($confOff) && !@rename($confOff, $conf)) {
            fail('启用失败：无法重命名 ' . $confOff);
        }
    } else {
        if (is_file($conf) && !@rename($conf, $confOff)) {
            fail('停用失败：无法重命名 ' . $conf);
        }
    }

    try {
        nginxReload();
    } catch (Throwable $e) {
        $enable ? @rename($conf, $confOff) : @rename($confOff, $conf);
        fail($e->getMessage());
    }
    $data['sites'][$idx]['enabled'] = $enable;
    try {
        saveSites($data);
    } catch (Throwable $e) {
        fail('配置已生效，但清单写入失败：' . $e->getMessage());
    }
    out(true, [], $enable ? '站点已启用' : '站点已停用');
}

function actionSiteDelete(array $p): void
{
    ensureState();

    $name = checkName((string)($p['name'] ?? ''));
    try {
        $data = loadSites();
    } catch (Throwable $e) {
        fail($e->getMessage());
    }
    $idx = findSiteIndex($data, $name);
    if ($idx === null) {
        fail('站点不存在');
    }
    $remove = !empty($p['remove_files']);

    @unlink(vhostEnabled($name));
    @unlink(vhostDisabled($name));
    @unlink(stateRewrite() . '/' . $name . '.conf');

    if ($remove) {
        $cfg = runtimeEnv();
        sh('rm -rf ' . escapeshellarg(siteRoot($cfg, $name)));
    }

    array_splice($data['sites'], $idx, 1);
    try {
        saveSites($data);
    } catch (Throwable $e) {
        fail('站点文件已移除，但清单写入失败：' . $e->getMessage());
    }

    try {
        nginxReload();
    } catch (Throwable $e) {
        fail('站点已移除，但 Nginx 重载失败：' . $e->getMessage());
    }
    out(true, [], '站点已删除' . ($remove ? '（含站点目录）' : '（站点目录已保留）'));
}

/** 查看 MariaDB root 密码（面板已登录才可调；仅 root 能读密码文件） */
function actionDbRootGet(array $p): void
{
    $readable = is_readable(MYSQL_PASS);
    $stored = $readable ? trim((string)file_get_contents(MYSQL_PASS)) : '';
    $rootOk = false;
    if ($stored !== '') {
        [$c] = mysqlRun($stored, 'SELECT 1');
        $rootOk = ($c === 0);
    }
    $via = '';
    foreach (mysqlCandidates() as $label => $pass) {
        [$c] = mysqlRun($pass, 'SELECT 1');
        if ($c === 0) {
            $via = $label;
            break;
        }
    }
    out(true, [
        'password'      => $stored,
        'file'          => MYSQL_PASS,
        'file_readable' => $readable,
        'root_ok'       => $rootOk,
        'via'           => $via,
        'has_admin'     => is_readable(MYSQL_ADMIN_PASS),
    ], $rootOk ? 'root 密码有效' : ($via !== '' ? '密码文件里的值连不上，建议重置' : '所有凭据都连不上 MariaDB'));
}

/** 重置 MariaDB root 密码：先尝试现有凭据，改完立即用新密码验证 */
function actionDbRootReset(array $p): void
{
    $new = (string)($p['password'] ?? '');
    if (strlen($new) < 8) {
        fail('新密码至少 8 位');
    }
    if (strlen($new) > 64) {
        fail('新密码最长 64 位');
    }
    if (preg_match('/[^\x21-\x7e]/', $new) === 1 || strpbrk($new, "'\"\\") !== false) {
        fail('新密码只能用可见 ASCII 字符，且不能包含引号或反斜杠');
    }
    $sql = "ALTER USER 'root'@'localhost' IDENTIFIED BY '" . $new . "'; FLUSH PRIVILEGES;";
    $used = '';
    $lastErr = '';
    foreach (mysqlCandidates() as $label => $pass) {
        [$c, $o] = mysqlRun($pass, $sql);
        if ($c === 0) {
            $used = $label;
            break;
        }
        $lastErr = trim($o);
    }
    if ($used === '') {
        fail('无法修改 root 密码：现有凭据都被拒绝。' . ($lastErr !== '' ? '最后一条错误：' . $lastErr : ''));
    }
    [$c2, $o2] = mysqlRun($new, 'SELECT 1');
    if ($c2 !== 0) {
        fail('ALTER USER 已执行，但新密码验证失败：' . trim($o2));
    }
    if (!writeSecret(MYSQL_PASS, $new)) {
        fail('新密码已生效，但写入 ' . MYSQL_PASS . ' 失败；请用新密码登录并把该文件改成 600 root');
    }
    out(true, ['file' => MYSQL_PASS, 'via' => $used], 'root 密码已更新（旧密码立即失效，站点 .env 里的旧密码需要自己改）');
}

function actionDbList(array $p): void
{
    $skip = ['information_schema', 'performance_schema', 'mysql', 'sys'];
    $sizes = [];
    [$c, $rows] = mysqlExec('SELECT table_schema, ROUND(SUM(data_length+index_length)/1024/1024,2) FROM information_schema.tables GROUP BY table_schema');
    if ($c === 0) {
        foreach (explode("\n", trim($rows)) as $line) {
            $parts = explode("\t", $line);
            if (count($parts) >= 2) {
                $sizes[$parts[0]] = (float)$parts[1];
            }
        }
    }
    $list = [];
    [$c, $dbs] = mysqlExec('SHOW DATABASES');
    if ($c === 0) {
        foreach (explode("\n", trim($dbs)) as $db) {
            $db = trim($db);
            if ($db === '' || in_array($db, $skip, true)) {
                continue;
            }
            $list[] = ['name' => $db, 'size_mb' => $sizes[$db] ?? 0];
        }
    } else {
        fail('连接 MariaDB 失败：' . $dbs);
    }
    $users = [];
    [$c, $urows] = mysqlExec("SELECT User, Host FROM mysql.user WHERE User <> 'root' ORDER BY User");
    if ($c === 0) {
        foreach (explode("\n", trim($urows)) as $line) {
            if ($line === '') {
                continue;
            }
            $parts = explode("\t", $line);
            $users[] = ['user' => $parts[0], 'host' => $parts[1] ?? 'localhost'];
        }
    }
    out(true, ['databases' => $list, 'users' => $users]);
}

function actionDbCreate(array $p): void
{
    $name = checkDbId((string)($p['name'] ?? ''));
    $charset = (string)($p['charset'] ?? 'utf8mb4');
    if (!in_array($charset, ['utf8mb4', 'utf8', 'latin1'], true)) {
        $charset = 'utf8mb4';
    }
    [$c, $msg] = mysqlExec(sprintf('CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET %s COLLATE %s_unicode_ci', $name, $charset, $charset));
    if ($c !== 0) {
        fail('建库失败：' . $msg);
    }
    out(true, ['name' => $name], '数据库已创建');
}

function actionDbDrop(array $p): void
{
    $name = checkDbId((string)($p['name'] ?? ''));
    if (empty($p['confirm'])) {
        fail('缺少删除确认');
    }
    [$c, $msg] = mysqlExec(sprintf('DROP DATABASE IF EXISTS `%s`', $name));
    if ($c !== 0) {
        fail('删库失败：' . $msg);
    }
    out(true, [], '数据库已删除');
}

function actionDbUserCreate(array $p): void
{
    $db   = checkDbId((string)($p['db'] ?? ''));
    $user = checkDbId((string)($p['user'] ?? ''));
    $pass = (string)($p['password'] ?? '');
    if (strlen($pass) < 6 || strlen($pass) > 64) {
        fail('密码长度需在 6-64 位');
    }
    if (!preg_match('/^[A-Za-z0-9_\-\.@#$%!]+$/', $pass)) {
        fail('密码只能包含字母、数字和 _ - . @ # $ % !');
    }
    $sql = sprintf(
        "CREATE USER IF NOT EXISTS '%s'@'localhost' IDENTIFIED BY '%s'; GRANT ALL PRIVILEGES ON `%s`.* TO '%s'@'localhost'; FLUSH PRIVILEGES;",
        $user, $pass, $db, $user
    );
    [$c, $msg] = mysqlExec($sql);
    if ($c !== 0) {
        fail('创建账号失败：' . $msg);
    }
    out(true, ['user' => $user, 'db' => $db], '数据库账号已创建并授权到该库');
}

function actionDbUserDrop(array $p): void
{
    $user = checkDbId((string)($p['user'] ?? ''));
    if (empty($p['confirm'])) {
        fail('缺少删除确认');
    }
    [$c, $msg] = mysqlExec(sprintf("DROP USER IF EXISTS '%s'@'localhost'", $user));
    if ($c !== 0) {
        fail('删除账号失败：' . $msg);
    }
    out(true, [], '账号已删除');
}

/** 环境自检：把最容易出问题的点一次性摊开 */
function actionDiag(array $p): void
{
    $cfg    = runtimeEnv();
    $checks = [];
    $add = static function (string $name, bool $ok, string $detail) use (&$checks): void {
        $checks[] = ['name' => $name, 'ok' => $ok, 'detail' => $detail];
    };

    [$_, $who] = sh('id -un');
    $add('运行身份', trim($who) === 'root', 'fnwsctl 以 ' . trim($who) . ' 身份运行（应为 root）');
    $add('PHP 版本', PHP_VERSION_ID >= 80300, 'PHP ' . PHP_VERSION . '（需要 8.3）');

    $sd = stateDir();
    $add('状态目录', is_dir($sd) && is_writable($sd),
        $sd . (is_dir($sd) ? (is_writable($sd) ? '（可写）' : '（不可写）') : '（不存在）'));
    $free = @disk_free_space($sd);
    $add('数据盘剩余空间', $free === false ? false : $free > 200 * 1048576,
        $free === false ? '无法读取' : round($free / 1048576, 1) . ' MB');

    $jsonOk = true;
    $jsonDetail = '';
    try {
        $sites = loadSites();
        $jsonDetail = '已解析，' . count($sites['sites']) . ' 个站点';
    } catch (Throwable $e) {
        $jsonOk = false;
        $jsonDetail = $e->getMessage();
    }
    $add('站点清单', $jsonOk, stateSites() . ' — ' . $jsonDetail);

    $wwwD = wwwDir();
    $add('站点根目录', is_dir($wwwD) && is_writable($wwwD),
        $wwwD . (is_dir($wwwD) ? (is_writable($wwwD) ? '（可写）' : '（不可写）') : '（不存在）'));

    // pcntl：队列、Workerman、Laravel queue 等常驻进程需要
    [$_, $cliMods] = sh('php -m 2>/dev/null');
    $cliPcntl = preg_match('/^pcntl$/mi', (string)$cliMods) === 1;
    $fpmPcntl = false;
    $fpmDetail = '未安装 php-fpm8.3';
    if (is_executable('/usr/sbin/php-fpm8.3') || is_executable('/usr/bin/php-fpm8.3')) {
        [$fc, $fpmMods] = sh('PHP_INI_SCAN_DIR=/etc/php/8.3/fpm/conf.d php -m 2>/dev/null');
        $fpmPcntl = $fc === 0 && preg_match('/^pcntl$/mi', (string)$fpmMods) === 1;
        $fpmDetail = $fpmPcntl ? 'FPM 已加载' : 'FPM 未加载';
    }
    $add('pcntl 扩展', $cliPcntl || $fpmPcntl,
        'CLI ' . ($cliPcntl ? '已启用' : '缺失') . '，' . $fpmDetail
        . '（队列/Workerman 类应用需要 CLI 侧可用）');

    $rewOk = is_dir(stateRewrite()) && is_writable(stateRewrite());
    $add('伪静态目录', $rewOk, stateRewrite() . ($rewOk ? ' 可用' : ' 缺失或不可写'));

    $vhOk = is_dir(stateVhost()) && is_writable(stateVhost());
    $add('站点 vhost 目录', $vhOk, stateVhost() . ($vhOk ? ' 可用' : ' 缺失或不可写'));

    $incFile = NGINX_CONF_D . '/fn-webstack-sites.conf';
    $inc = is_file($incFile) ? trim((string)file_get_contents($incFile)) : '';
    $add('Nginx 站点包含', is_file($incFile), $incFile . ($inc !== '' ? ' → ' . $inc : '（缺失，站点不会生效）'));

    [$c, $nt] = sh('nginx -t');
    $add('nginx -t', $c === 0, trim($nt));

    $dataOk = $cfg['DATA_DIR'] !== '' && is_dir($cfg['DATA_DIR']) && is_writable($cfg['DATA_DIR']);
    $add('数据目录', $dataOk,
        $cfg['DATA_DIR'] === '' ? 'runtime.env 未提供 DATA_DIR' : $cfg['DATA_DIR'] . (is_dir($cfg['DATA_DIR']) ? '' : ' 不存在'));

    $add('/etc/fnwebstack 可写', is_writable(CONF_DIR),
        CONF_DIR . (is_writable(CONF_DIR) ? '' : '（不可写；运行期已改用数据盘，不影响使用）'));
    $add('sudoers 白名单', is_file('/etc/sudoers.d/fnwebstack'), '/etc/sudoers.d/fnwebstack');
    $add('助手已安装', is_executable('/usr/local/bin/fnwsctl'), '/usr/local/bin/fnwsctl');

    [$c, $ping] = sh('MYSQL_PWD=' . escapeshellarg(is_readable(MYSQL_PASS) ? trim((string)file_get_contents(MYSQL_PASS)) : '') . ' mysqladmin --protocol=socket -u root ping');
    $add('MariaDB 连接', $c === 0, trim($ping));

    foreach (SVC_WHITELIST as $s) {
        [$sc] = sh('systemctl is-active --quiet ' . escapeshellarg($s));
        $add('服务 ' . $s, $sc === 0, $sc === 0 ? 'active' : '未运行');
    }

    $vhosts = glob(stateVhost() . '/*.conf') ?: [];
    $offs   = glob(stateVhost() . '/*.conf.off') ?: [];
    $add('站点 vhost 数量', true, count($vhosts) . ' 个启用 / ' . count($offs) . ' 个停用');

    out(true, [
        'version' => FNWSCTL_VERSION,
        'checks'  => $checks,
        'env'     => $cfg,
        'state'   => $sd,
    ], '自检完成');
}

/* ---------------------------- dispatch ---------------------------- */

$action  = '';
$payload = [];

$raw = stream_get_contents(STDIN);
if ($raw !== false && trim($raw) !== '') {
    $req = json_decode($raw, true);
    if (!is_array($req) || !isset($req['action'])) {
        fail('请求格式错误');
    }
    $action  = (string)$req['action'];
    $payload = is_array($req['payload'] ?? null) ? $req['payload'] : [];
}

function isRoot(): bool
{
    if (function_exists('posix_getuid')) {
        return posix_getuid() === 0;
    }
    return trim((string)shell_exec('id -u')) === '0';
}

if (!isRoot()) {
    fail('fnwsctl 需要 root 权限运行');
}

try {
    switch ($action) {
        case 'status':          actionStatus($payload);        break;
        case 'svc.action':      actionSvc($payload);           break;
        case 'diag':            actionDiag($payload);          break;
        case 'site.list':       actionSiteList($payload);      break;
        case 'site.dirs':       actionSiteDirs($payload);      break;
        case 'site.create':     actionSiteCreate($payload);    break;
        case 'site.update':     actionSiteUpdate($payload);    break;
        case 'site.toggle':     actionSiteToggle($payload);    break;
        case 'site.delete':     actionSiteDelete($payload);    break;
        case 'rewrite.list':    actionRewriteList($payload);   break;
        case 'db.root.get':     actionDbRootGet($payload);     break;
        case 'db.root.reset':   actionDbRootReset($payload);   break;
        case 'db.list':         actionDbList($payload);        break;
        case 'db.create':       actionDbCreate($payload);      break;
        case 'db.drop':         actionDbDrop($payload);        break;
        case 'db.user.create':  actionDbUserCreate($payload);  break;
        case 'db.user.drop':    actionDbUserDrop($payload);    break;
        default:
            fail('未知操作：' . $action);
    }
} catch (Throwable $e) {
    fail($e->getMessage());
}
