<?php
require_once("guiconfig.inc");

include("head.inc");
include("fbegin.inc");

// 配置
define('DDNSGO_BINARY', '/usr/local/bin/ddns-go');
define('DDNSGO_LOG_FILE', '/var/log/ddnsgo.log');
define('DDNSGO_PID_FILE', '/var/run/ddnsgo.pid');
$allowedActions = ['start', 'stop', 'restart'];

// 服务控制函数
function handleServiceAction($action)
{
    global $allowedActions;

    if (!in_array($action, $allowedActions)) {
        return gettext("无效的操作！");
    }

    switch ($action) {
        case 'start':
            return startService();
        case 'stop':
            return stopService();
        case 'restart':
            return restartService();
    }
}

// 启动服务
function startService()
{
    if (isServiceRunning()) {
        return gettext("DDNS-Go 已在运行！");
    }

    // 创建日志目录（如果不存在）
    if (!is_dir(dirname(DDNSGO_LOG_FILE))) {
        mkdir(dirname(DDNSGO_LOG_FILE), 0755, true);
    }

    // 启动 ddns-go 并将输出重定向到日志文件
    $command = sprintf(
        'nohup %s > %s 2>&1 & echo $! > %s',
        escapeshellarg(DDNSGO_BINARY),
        escapeshellarg(DDNSGO_LOG_FILE),
        escapeshellarg(DDNSGO_PID_FILE)
    );

    exec($command, $output, $return_var);
    sleep(2); // 等待服务完全启动

    return isServiceRunning() ? gettext("DDNS-Go 服务启动成功！") : gettext("DDNS-Go 服务启动失败！");
}

// 停止服务
function stopService()
{
    if (!isServiceRunning()) {
        return gettext("DDNS-Go 未运行！");
    }

    // 获取 PID 并终止进程
    exec(sprintf('kill $(cat %s)', escapeshellarg(DDNSGO_PID_FILE)), $output, $return_var);
    sleep(2); // 等待服务完全停止

    if (isServiceRunning()) {
        return gettext("DDNS-Go 服务停止失败！");
    }

    unlink(DDNSGO_PID_FILE);
    return gettext("DDNS-Go 服务已停止！");
}

// 重启服务
function restartService()
{
    $stopMessage = stopService();
    return $stopMessage . ' ' . startService();
}

// 检查进程是否运行
function isServiceRunning()
{
    $pid = @file_get_contents(DDNSGO_PID_FILE);
    if ($pid === false || !is_numeric($pid)) {
        return false;
    }

    exec("ps -p " . escapeshellarg((int) $pid), $output, $return_var);
    return $return_var === 0;
}

// 获取服务运行状态
function getServiceStatus()
{
    return isServiceRunning() ? gettext("运行中") : gettext("已停止");
}

// 获取实时日志
function getLogOutput()
{
    if (file_exists(DDNSGO_LOG_FILE)) {
        return file_get_contents(DDNSGO_LOG_FILE);
    }
    return gettext("日志文件不存在或无法读取。");
}

// 表单提交处理
$message = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $message = handleServiceAction($action);
}

$status = getServiceStatus();
?>
<script>
    function checkDdnsgoStatus() {
        fetch('/status_ddnsgo.php?ts=' + new Date().getTime()) // 防止缓存
            .then(response => {
                if (!response.ok) {
                    throw new Error("网络错误或状态接口不可用");
                }
                return response.json();
            })
            .then(data => {
                const statusElement = document.getElementById('ddnsgo-status');
                if (data.status === "running") {
                    statusElement.innerHTML = '<i class="fa fa-check-circle text-success"></i> DDNS-Go正在运行';
                    statusElement.className = "alert alert-success";
                } else {
                    statusElement.innerHTML = '<i class="fa fa-times-circle text-danger"></i> DDNS-Go已停止';
                    statusElement.className = "alert alert-danger";
                }
            })
            .catch(error => {
                console.error("检查状态失败:", error);
            });
    }

    document.addEventListener('DOMContentLoaded', () => {
        checkDdnsgoStatus();
        setInterval(checkDdnsgoStatus, 3000); // 每3秒检查一次状态
    });
</script>

<div>
    <?php if (!empty($message)): ?>
        <div class="alert alert-info">
            <?= htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>
</div>
<!-- 服务状态 -->
<section class="page-content-main">
    <div class="container-fluid">
        <div class="row">
            <section class="col-xs-12">
                <div class="content-box tab-content table-responsive __mb">
                    <table class="table table-striped">
                        <tbody>
                            <tr>
                                <td><strong>服务状态</strong></td>
                            </tr>
                            <tr>
                                <td>
                                    <div id="ddnsgo-status" class="alert alert-secondary">
                                        <i class="fa fa-circle-notch fa-spin"></i> 检查中...
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </section>
            <!-- 服务控制 -->
            <section class="col-xs-12">
                <div class="content-box tab-content table-responsive __mb">
                    <table class="table table-striped">
                        <tbody>
                            <tr>
                                <td><strong>服务控制</strong></td>
                            </tr>
                            <tr>
                                <td>
                                    <form method="post" class="form-inline">
                                        <button type="submit" name="action" value="start" class="btn btn-success">
                                            <i class="fa fa-play"></i> 启动
                                        </button>
                                        <button type="submit" name="action" value="stop" class="btn btn-danger">
                                            <i class="fa fa-stop"></i> 停止
                                        </button>
                                        <button type="submit" name="action" value="restart" class="btn btn-warning">
                                            <i class="fa fa-refresh"></i> 重启
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </section>
            <!-- 实时日志 -->
            <section class="col-xs-12">
                <div class="content-box tab-content table-responsive __mb">
                    <table class="table table-striped">
                        <tbody>
                            <tr>
                                <td>
                                    <strong>实时日志</strong>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <pre
                                        style="background-color: #f8f9fa; padding: 10px; border: 1px solid #ddd; height: 300px; overflow-y: scroll;">
<?= htmlspecialchars(getLogOutput()); ?>
                                    </pre>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </section>
        </div>
    </div>
</section>
<?php include("foot.inc"); ?>