"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.start = void 0;
// The dirs module has to be imported in the start of the script, before
// anyone has a chance to change the current working directory
const dirs = require("./lib/dirs");
// The config loader has to be imported before most other modules,
// to make sure the config file is loaded and available to use
const configLoader = require("./lib/config-loader");
const buildInfo = require("./lib/build-info");
const dbManager = require("./lib/db-manager");
const actorHelper = require("./lib/actor-helper");
const expressApp = require("./express-app");
const fs = require("fs");
const http = require("http");
const notifier = require("./lib/websocket-notifier");
const sessionHelper = require("./lib/session-helper");
const path = require("path");
const testRepo = require("./lib/test-repo");
function start(options = {}) {
    if (options.workDir) {
        dirs.setWorkingDir(options.workDir);
    }
    const buildInfoObj = buildInfo.getBuildInfo();
    console.log(`\nOpenTest server ${buildInfoObj.version}, commit ${buildInfoObj.commitSha}\n`);
    console.log(`Running in working directory "${dirs.workingDir()}"`);
    try {
        configLoader.loadConfig('server.yaml');
    }
    catch (err) {
        console.error('ERROR: Configuration error!');
        console.error('ERROR: ' + err.message + '\n');
        process.exit(1);
    }
    dbManager.initDb();
    process.on('unhandledRejection', err => {
        console.log('ERROR: We detected an unhandled promise rejection. The server will be terminated. The error was: ', JSON.stringify(err), '\n');
        process.exit(1);
    });
    process.on('uncaughtException', err => {
        console.log('ERROR: We detected an unhandled exception. The server will be terminated. The error message was: ', JSON.stringify(err), '\n');
        process.exit(1);
    });
    const config = configLoader.getConfig();
    console.log(`Using test repo directory "${path.normalize(config.testRepoDir)}"`);
    testRepo.parseTestRepo()
        .then(() => {
        if (config.watchTestRepo) {
            testRepo.setupTestRepoWatcher();
        }
    })
        .catch((err) => {
        console.error("ERROR: Failed parsing the test repo. " + err.message + '\n');
        process.exit(1);
    });
    actorHelper.startCleanupInterval();
    sessionHelper.startCleanupInterval();
    const server = http.createServer(expressApp.createApp());
    notifier.initialize(server);
    // Write server process ID to disk. This can be used later to easily kill
    // the process from a CI pipeline or other automation tools.
    const pid = process.pid || 0;
    try {
        fs.writeFileSync(path.join(dirs.workingDir(), 'server.pid'), String(pid));
    }
    catch (_a) {
        // Nothing to do here
    }
    console.log(`Server PID: ${pid}`);
    const port = config.serverPort;
    server.listen(port, function () {
        process.title = `OpenTest server (${port})`;
        console.log(`The OpenTest server is listening on port ${port}`);
        console.log(`Open a browser and navigate to http://localhost:${port}\n`);
    });
    if (config.readOnlyPort) {
        const readOnlyServer = http.createServer(expressApp.createApp({ readOnly: true }));
        const readOnlyPort = config.readOnlyPort;
        readOnlyServer.listen(readOnlyPort, function () {
            console.log(`The read-only view is running on port ${readOnlyPort}`);
        });
    }
    return pid;
}
exports.start = start;
//# sourceMappingURL=service.js.map