"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_http_1 = require("node:http");
const node_os_1 = require("node:os");
const node_url_1 = require("node:url");
const next_1 = __importDefault(require("next"));
const auth_1 = require("./src/server/auth");
const job_scheduler_1 = require("./src/server/job-scheduler");
const session_manager_1 = require("./src/server/session-manager");
const singleton_1 = require("./src/server/singleton");
const ws_handler_1 = require("./src/server/ws-handler");
const dev = process.env.NODE_ENV !== "production";
const port = parseInt(process.env.PORT || "3001", 10);
const host = process.env.HOST || "0.0.0.0";
const app = (0, next_1.default)({ dev, hostname: host, port });
const handle = app.getRequestHandler();
function getLanAddresses() {
    const addresses = [];
    const ifaces = (0, node_os_1.networkInterfaces)();
    for (const name of Object.keys(ifaces)) {
        for (const iface of ifaces[name] || []) {
            if (iface.family === "IPv4" && !iface.internal) {
                addresses.push(iface.address);
            }
        }
    }
    return addresses;
}
function logStartupBanner() {
    console.log(`Cockpit listening on ${host}:${port}`);
    console.log("");
    console.log("Connect via:");
    const isWildcard = host === "0.0.0.0" || host === "::";
    const isLoopback = host === "127.0.0.1" || host === "localhost" || host === "::1";
    if (isWildcard) {
        console.log(`  Local:    http://localhost:${port}`);
        const network = getLanAddresses();
        if (network.length > 0) {
            console.log(`  Network:  http://${network[0]}:${port}`);
            for (let i = 1; i < network.length; i++) {
                console.log(`            http://${network[i]}:${port}`);
            }
        }
    }
    else if (isLoopback) {
        console.log(`  Local:    http://localhost:${port}`);
    }
    else {
        console.log(`  Network:  http://${host}:${port}`);
    }
    console.log("");
}
async function main() {
    // Handle password reset flag
    if (process.env.COCKPIT_RESET_PASSWORD === "true") {
        await (0, auth_1.deletePasswordFile)();
        console.log("Password has been reset. You will be prompted to set a new password.");
    }
    await app.prepare();
    const sessionManager = new session_manager_1.SessionManager();
    (0, singleton_1.setSessionManager)(sessionManager);
    const jobScheduler = new job_scheduler_1.JobScheduler(sessionManager);
    (0, singleton_1.setJobScheduler)(jobScheduler);
    jobScheduler.start();
    const server = (0, node_http_1.createServer)((req, res) => {
        const parsedUrl = (0, node_url_1.parse)(req.url || "", true);
        handle(req, res, parsedUrl);
    });
    (0, ws_handler_1.createWebSocketHandler)(server, sessionManager);
    server.listen(port, host, () => {
        logStartupBanner();
        if ((0, auth_1.needsSetup)()) {
            console.log("No password set. Visit the UI to create one.");
        }
    });
}
main().catch((err) => {
    console.error("Failed to start server:", err);
    process.exit(1);
});
