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

$pgtitle = [gettext('Services'), gettext('DDNS-Go')];
include("head.inc");

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

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

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

    return match ($action) {
        'start' => startService(),
        'stop' => stopService(),
        'restart' => restartService(),
    };
}

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

    if (!prepareLogDirectory()) {
        return gettext("日志目录创建失败！");
    }

    $command = sprintf(
        'nohup %s > %s 2>&1 & echo $! > %s',
        escapeshellarg(DDNSGO_BINARY),
        escapeshellarg(DDNSGO_LOG_FILE),
        escapeshellarg(DDNSGO_PID_FILE)
    );
    exec($command);

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

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

    $pid = @file_get_contents(DDNSGO_PID_FILE);
    if ($pid && is_numeric($pid)) {
        exec(sprintf('kill %d', (int)$pid), $output, $return_var);
        if ($return_var === 0) {
            unlink(DDNSGO_PID_FILE);
            return gettext("DDNS-Go 服务已停止！");
        }
    }

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

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

// 检查服务是否运行
function isServiceRunning(): bool
{
    $pid = @file_get_contents(DDNSGO_PID_FILE);
    return $pid && is_numeric($pid) && posix_kill((int) $pid, 0);
}

// 准备日志目录
function prepareLogDirectory(): bool
{
    $logDir = dirname(DDNSGO_LOG_FILE);
    if (!is_dir($logDir)) {
        return mkdir($logDir, 0755, true);
    }
    return true;
}

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

// 获取日志内容
function getLogOutput(): string
{
    return file_exists(DDNSGO_LOG_FILE) ? @file_get_contents(DDNSGO_LOG_FILE) : gettext("日志文件不存在或无法读取。");
}

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

$status = getServiceStatus();
?>

<div>
    <?php if (!empty($message)): ?>
        <div class="alert alert-info">
            <?= htmlspecialchars($message); ?>
        </div>
    <?php endif; ?>
</div>

<!-- 状态显示 -->
<div class="panel panel-default">
    <div class="panel-heading">
        <h2 class="panel-title">服务状态</h2>
    </div>
    <div class="panel-body">
        <div id="ddnsgo-status" class="alert alert-secondary">
            <i class="fa fa-circle-notch fa-spin"></i> 检查中...
        </div>
    </div>
</div>

<!-- 服务控制 -->
<div class="panel panel-default">
    <div class="panel-heading">
        <h2 class="panel-title">服务控制</h2>
    </div>
    <div class="form-group">
        <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-sync"></i> 重启
            </button>
        </form>
    </div>
</div>

<!-- 日志查看 -->
<div class="panel panel-default">
    <div class="panel-heading">
        <h2 class="panel-title">运行日志</h2>
    </div>
    <div class="form-group">
        <pre
            style="background-color: #f8f9fa; padding: 10px; border: 1px solid #ddd; height: 300px; overflow-y: scroll;">
<?= htmlspecialchars(getLogOutput()); ?>
        </pre>
    </div>
</div>

<script>
    function checkDdnsgoStatus() {
        fetch('/status_ddnsgo.php')
            .then(response => 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";
                }
            });
    }

    // 页面加载时初始化
    document.addEventListener('DOMContentLoaded', () => {
        checkDdnsgoStatus();
        setInterval(checkDdnsgoStatus, 3000); // 每3秒检查一次状态
    });
</script>

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