<?php
session_start();
header("Access-Control-Allow-Credentials: true");
header("Content-Type:application/json;charset=utf-8");

$SECRET_RAW = "DockerAdminPlatform2026SecretKey123456789";

$uidGet = $_GET['uid'] ?? '';
if (!empty($uidGet) && empty($_SESSION['user_id'])) {
    $_SESSION['user_id'] = $uidGet;
    $_SESSION['login_time'] = time();
}

$debug = [
    "sid" => session_id(),
    "session_data" => $_SESSION
];

$expire = 1800;
if (empty($_SESSION['user_id']) || (time() - $_SESSION['login_time'] > $expire)) {
    session_destroy();
    echo json_encode([
        "code"=>401,
        "msg"=>"未登录",
        "debug"=>$debug
    ],JSON_UNESCAPED_UNICODE);
    exit;
}

$user = $_SESSION['user_id'];
$role = $_SESSION['role'];
$ts = time();
$rawSignStr = $user . "|" . $role . "|" . $ts;
$sign = hash_hmac("sha256", $rawSignStr, $SECRET_RAW);
$clientIp = $_SERVER['REMOTE_ADDR'];

$act = $_POST['act'] ?? $_GET['act'] ?? 'list';
$cid = $_POST['container_id'] ?? $_GET['container_id'] ?? '';
$imageId = $_POST['image_id'] ?? $_GET['image_id'] ?? '';
$lines = $_POST['lines'] ?? $_GET['lines'] ?? 200;
$postRaw = file_get_contents("php://input");
$apiBase = "http://10.150.117.190:8090";

$authHeaders = [
    "X-User: {$user}",
    "X-Role: {$role}",
    "X-Time: {$ts}",
    "X-Sign: {$sign}",
    "X-Client-Ip: {$clientIp}",
    "Content-Type: application/json; charset=utf-8"
];
$headerStr = implode("\r\n", $authHeaders);

$getMap = [
    'list' => '/list',
    'image_list' => '/image_list',
    'restart' => '/restart/%s',
    'stop' => '/stop/%s',
    'rm' => '/rm/%s',
    'remove_image' => '/remove_image/%s',
    'logs' => '/logs/%s/%d',
    'network' => '/network/%s',
    'stats' => '/stats/%s',
    'detail' => '/detail/%s'
];

$postMap = [
    'exec' => '/exec/%s',
    'create' => '/create',
    'bind_repo' => '/bind_repo',
];

if (isset($getMap[$act])) {
    $path = $getMap[$act];
    $url = '';
    switch ($act) {
        case 'restart':
        case 'stop':
        case 'rm':
        case 'network':
        case 'stats':
        case 'detail':
            if (empty($cid)) {
                echo json_encode(["code"=>400,"msg"=>"缺少容器ID","debug"=>$debug],JSON_UNESCAPED_UNICODE);
                exit;
            }
            $url = $apiBase . sprintf($path, urlencode($cid));
            break;
        case 'remove_image':
            if (empty($imageId)) {
                echo json_encode(["code"=>400,"msg"=>"缺少镜像ID","debug"=>$debug],JSON_UNESCAPED_UNICODE);
                exit;
            }
            $url = $apiBase . sprintf($path, urlencode($imageId));
            break;
        case 'logs':
            if (empty($cid)) {
                echo json_encode(["code"=>400,"msg"=>"缺少容器ID","debug"=>$debug],JSON_UNESCAPED_UNICODE);
                exit;
            }
            $url = $apiBase . sprintf($path, urlencode($cid), (int)$lines);
            break;
        default:
            $url = $apiBase . $path;
            break;
    }
    $ctx = stream_context_create([
        'http' => [
            'method' => 'GET',
            'header' => $headerStr,
            'timeout' => 30
        ]
    ]);
    $resp = @file_get_contents($url, false, $ctx);
    if ($resp === false) {
        echo json_encode([
            "code" => 503,
            "msg" => "后端Docker接口连接失败，请检查服务是否启动",
            "debug" => $debug
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    echo $resp;
    exit;
}

if (isset($postMap[$act])) {
    $path = $postMap[$act];
    $url = '';
    if ($act === 'exec') {
        if (empty($cid)) {
            echo json_encode(["code"=>400,"msg"=>"缺少容器ID","debug"=>$debug],JSON_UNESCAPED_UNICODE);
            exit;
        }
        $url = $apiBase . sprintf($path, urlencode($cid));
    } else {
        $url = $apiBase . $path;
    }
    $ctx = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => $headerStr,
            'content' => $postRaw,
            'timeout' => 30
        ]
    ]);
    $resp = @file_get_contents($url, false, $ctx);
    if ($resp === false) {
        echo json_encode([
            "code" => 503,
            "msg" => "后端Docker接口连接失败，请检查服务是否启动",
            "debug" => $debug
        ], JSON_UNESCAPED_UNICODE);
        exit;
    }
    echo $resp;
    exit;
}

echo json_encode([
    "code"=>400,
    "msg"=>"无效操作act参数",
    "debug"=>$debug
],JSON_UNESCAPED_UNICODE);
exit;
