<?php
require_once("guiconfig.inc");
$pgtitle = [gettext("VPN"), gettext("Netbird")];
include("head.inc");

// Netbird 配置
$nb_bin = '/usr/local/bin/netbird';
$validActions = ['up', 'down', 'restartsvc', 'statusd'];

// 处理用户操作
$action = $_GET['action'] ?? null;
$output = '';
if (in_array($action, $validActions)) {
    switch ($action) {
        case 'up':
            $command = "$nb_bin up";
            break;
        case 'down':
            $command = "$nb_bin down";
            break;
        case 'restartsvc':
            $command = '/usr/sbin/service netbird restart';
            break;
        case 'statusd':
            $command = "$nb_bin status -d";
            break;
    }

    exec($command, $execOutput, $return_var);
    $output = $return_var === 0 ? implode("\n", $execOutput) : '执行命令时出错，请检查日志。';
}
?>
<!-- 服务控制面板 -->
<div class="panel panel-default">
    <div class="panel-heading">
        <h2 class="panel-title">服务控制</h2>
    </div>
    <div class="form-group">
        <form method="get">
            <button type="submit" name="action" value="up" class="btn btn-success"><i class="fa fa-play"></i>
                启动</button>
            <button type="submit" name="action" value="down" class="btn btn-danger"><i class="fa fa-stop"></i>
                停止</button>
            <button type="submit" name="action" value="restartsvc" class="btn btn-warning"><i class="fa fa-sync"></i>
                重启</button>
        </form>
    </div>
</div>

<!-- 节点状态 -->
<div class="panel panel-default">
    <div class="panel-heading">
        <h2 class="panel-title">节点状态</h2>
    </div>
    <div class="panel-body">
        <div id="node-status">
            <p>正在加载节点状态...</p>
        </div>
    </div>
</div>

<!-- 命令输出 -->
<div class="panel panel-default">
    <div class="panel-heading">
        <h2 class="panel-title">状态信息</h2>
    </div>
    <div class="form-group">
        <?php if (empty($output)): ?>
            <form method="get">
                <button type="submit" name="action" value="statusd" class="btn btn-info"><i class="fa fa-info-circle"></i>
                    查询</button>
            </form>
        <?php endif; ?>
        <?php if (!empty($output)): ?>
            <pre><?= htmlspecialchars($output); ?></pre>
        <?php endif; ?>
    </div>
</div>

<!-- 动态刷新节点状态 -->
<script>
    function fetchNodeStatus() {
        fetch('vpn_netbird_status.php') // 调用状态接口
            .then(response => response.text())
            .then(data => {
                document.getElementById('node-status').innerHTML = data;
            })
            .catch(error => {
                console.error("节点状态刷新失败:", error);
                document.getElementById('node-status').innerHTML = "<p>加载节点状态时出错。</p>";
            });
    }

    document.addEventListener('DOMContentLoaded', () => {
        fetchNodeStatus(); // 初次加载
        setInterval(fetchNodeStatus, 5000); // 每5秒刷新
    });
</script>

<?php include("foot.inc"); ?>