96 lines
2.6 KiB
PHP
96 lines
2.6 KiB
PHP
<?php
|
|
// === Handle API requests ===
|
|
$requestUri = $_SERVER['REQUEST_URI'];
|
|
if (str_starts_with($requestUri, '/api/')) {
|
|
require __DIR__ . '/api/public/index.php';
|
|
exit;
|
|
}
|
|
|
|
// === Setup ===
|
|
require __DIR__ . "/api/vendor/autoload.php";
|
|
require __DIR__ . "/api/src/Services/LxdService.php";
|
|
|
|
use Dotenv\Dotenv;
|
|
use Zounar\PHPProxy\Proxy;
|
|
use App\Services\LxdService;
|
|
// 🔹 Load .env config
|
|
$dotenv = Dotenv::createImmutable(__DIR__ . '/api/');
|
|
$dotenv->load();
|
|
|
|
$host = $_SERVER['HTTP_HOST'] ?? '';
|
|
$method = $_SERVER['REQUEST_METHOD'];
|
|
|
|
// Load container mapping from domain config
|
|
$config = json_decode(file_get_contents(__DIR__ . '/api/config.json'), true);
|
|
$container = $config[$host] ?? null;
|
|
$lxd = new LxdService();
|
|
|
|
// === Helper URLs ===
|
|
$redirectBase = parseUrl("$host/app?auth=ok&redirect=" . urlencode(getFullUrl()));
|
|
$waitingPage = parseUrl("$host/app/waiting?name=$container&redirect=" . urlencode(getFullUrl()));
|
|
// === If container is missing or invalid ===
|
|
if (!$container || !$lxd->containerExists($container)) {
|
|
redirect($redirectBase);
|
|
}
|
|
|
|
// === Check container status ===
|
|
$state = $lxd->getContainerState($container)['metadata']['status'] ?? 'Stopped';
|
|
|
|
if ($state !== 'Running') {
|
|
redirect($redirectBase);
|
|
}
|
|
|
|
// === Get container IP ===
|
|
$ip = $lxd->getContainerIP($container);
|
|
|
|
$nginx = $lxd->getContainerServiceStatus($container, 'nginx');
|
|
$mysql = $lxd->getContainerServiceStatus($container, 'mariadb');
|
|
|
|
if (!$ip || $nginx !== 'active' || $mysql !== 'active') {
|
|
redirect($waitingPage);
|
|
}
|
|
|
|
// === Proxy to container ===
|
|
proxy($container, "http://{$host}{$requestUri}");
|
|
exit;
|
|
|
|
|
|
// === Functions ===
|
|
|
|
function redirect(string $to): void {
|
|
header("Location: $to", true, 302);
|
|
exit;
|
|
}
|
|
|
|
function proxy(string $name, string $targetUrl): void {
|
|
Proxy::$ENABLE_AUTH = false;
|
|
Proxy::$HEADER_HTTP_PROXY_AUTH = 'HTTP_PROXY_AUTH';
|
|
|
|
$_SERVER['HTTP_PROXY_TARGET_URL'] = $targetUrl;
|
|
|
|
$responseCode = Proxy::run();
|
|
writeLog($name, $targetUrl);
|
|
}
|
|
|
|
function getFullUrl(): string {
|
|
$protocol = (!empty($_SERVER['HTTPS']) || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
|
|
$host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'];
|
|
return $protocol . $host . $_SERVER['REQUEST_URI'];
|
|
}
|
|
|
|
function parseUrl(string $url = ''): string {
|
|
$scheme = $_SERVER['REQUEST_SCHEME'] ?? 'http';
|
|
return "$scheme://$url";
|
|
}
|
|
|
|
function writeLog(string $name, string $uri): void {
|
|
$logDir = __DIR__ . '/api/public/last-access-logs';
|
|
|
|
if (!is_dir($logDir)) {
|
|
mkdir($logDir, 0777, true);
|
|
}
|
|
|
|
$logLine = date("Y-m-d H:i:s") . " : " . $uri . "\n";
|
|
file_put_contents("$logDir/$name.txt", $logLine, FILE_APPEND);
|
|
}
|