'use strict';
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.BOOT_PROPS_FILE_PATH = void 0;
exports.getHdbBasePath = getHdbBasePath;
exports.setHdbBasePath = setHdbBasePath;
exports.get = get;
exports.setProperty = setProperty;
exports.initSync = initSync;
exports.initTestEnvironment = initTestEnvironment;
const fs = __importStar(require("fs-extra"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const properties_reader_1 = __importDefault(require("properties-reader"));
const harper_logger_ts_1 = __importDefault(require("../logging/harper_logger.js"));
const commonUtils = __importStar(require("../common_utils.js"));
const hdbTerms = __importStar(require("../hdbTerms.js"));
const configUtils = __importStar(require("../../config/configUtils.js"));
const node_fs_1 = require("node:fs");
const INIT_ERR = 'Error initializing environment manager';
const BOOT_PROPS_FILE_PATH = 'BOOT_PROPS_FILE_PATH';
exports.BOOT_PROPS_FILE_PATH = BOOT_PROPS_FILE_PATH;
let propFileExists = false;
const installPropsToSave = {
    [hdbTerms.HDB_SETTINGS_NAMES.INSTALL_USER]: true,
    [hdbTerms.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY]: true,
    [hdbTerms.HDB_SETTINGS_NAMES.HDB_ROOT_KEY]: true,
    BOOT_PROPS_FILE_PATH: true,
};
let installProps = {};
/**
 * The base path of the HDB install is often referenced, but is referenced as a const variable at the top of many
 * modules.  This is a problem during install, as the path may not yet be defined.  We offer a function to get the
 * currently known base path here to help with this case.
 */
function getHdbBasePath() {
    return installProps[hdbTerms.HDB_SETTINGS_NAMES.HDB_ROOT_KEY];
}
/**
 * Sets the HDB base path in the install props object that this module maintains.
 * This is mainly used by install during a stage where the config file doesn't exist.
 * @param hdbPath
 */
function setHdbBasePath(hdbPath) {
    installProps[hdbTerms.HDB_SETTINGS_NAMES.HDB_ROOT_KEY] = hdbPath;
}
/**
 * Gets a Harper configuration value.
 * @param propName
 * @returns {*}
 */
function get(propName) {
    const value = configUtils.getConfigValue(propName);
    if (value === undefined) {
        return installProps[propName];
    }
    return value;
}
/**
 * Will update install props if provided prop is part of that object.
 * Will also update the config object configUtils maintains.
 * Note - this function will NOT update the config file. If you want to update the file
 * use the updateConfigValue method in configUtils.
 *
 * This function should only be used by the installer and unit tests.
 * @param propName
 * @param value
 */
function setProperty(propName, value) {
    if (installPropsToSave[propName]) {
        installProps[propName] = value;
    }
    configUtils.updateConfigObject(propName, value);
}
/**
 * Checks to see if the Harper boot props file exists.
 * If it does, it grabs the install user and settings path for future reference.
 * @returns {boolean}
 */
function doesPropFileExist() {
    let bootPropPath;
    try {
        bootPropPath = commonUtils.getPropsFilePath();
        fs.accessSync(bootPropPath, fs.constants.F_OK | fs.constants.R_OK);
        propFileExists = true;
        const hdbPropsFile = (0, properties_reader_1.default)(bootPropPath);
        installProps[hdbTerms.HDB_SETTINGS_NAMES.INSTALL_USER] = hdbPropsFile.get(hdbTerms.HDB_SETTINGS_NAMES.INSTALL_USER);
        installProps[hdbTerms.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY] = hdbPropsFile.get(hdbTerms.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY);
        installProps[BOOT_PROPS_FILE_PATH] = bootPropPath;
        return true;
    }
    catch {
        harper_logger_ts_1.default.trace(`Environment manager found no properties file at ${bootPropPath}`);
        return false;
    }
}
/**
 * Synchronously initializes our config environment.
 * @param force
 */
function initSync(force = false) {
    try {
        if (propFileExists || doesPropFileExist() || commonUtils.noBootFile() || force) {
            configUtils.initConfig(force);
            const configHdbRoot = configUtils.getConfigValue(hdbTerms.HDB_SETTINGS_NAMES.HDB_ROOT_KEY);
            // Only overwrite if we actually got a value from config
            if (configHdbRoot !== undefined) {
                installProps[hdbTerms.HDB_SETTINGS_NAMES.HDB_ROOT_KEY] = configHdbRoot;
            }
        }
    }
    catch (err) {
        harper_logger_ts_1.default.error(INIT_ERR);
        harper_logger_ts_1.default.error(err);
        console.error(err);
        // Use _realExit so this fatal startup error still terminates the worker
        // even with the worker process guard installed. Inline fallback (rather
        // than importing the helper) avoids a utility -> server layer
        // dependency; safe because both alternatives are real exit primitives.
        (process._realExit ?? process.exit)(1);
    }
}
/**
 * Initializes a test environment.
 * Most of this is legacy code from before the yaml config refactor.
 * @param testConfigObj
 */
function initTestEnvironment(testConfigObj = {}) {
    try {
        const { keep_alive_timeout, headers_timeout, server_timeout, https_enabled, cors_enabled, cors_accesslist, local_studio_on, } = testConfigObj;
        // __dirname is dist/utility/environment when running tests, so go up 3 levels to reach project root
        const propsPath = path.join(__dirname, '../../../', 'unitTests');
        installProps[BOOT_PROPS_FILE_PATH] = path.join(propsPath, 'hdb_boot_properties.file');
        const TEST_HDB_PATH = path.join(propsPath, 'envDir', process.pid.toString());
        try {
            (0, node_fs_1.mkdirSync)(TEST_HDB_PATH, { recursive: true });
        }
        catch { }
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.SETTINGS_PATH_KEY, path.join(propsPath, 'settings.test'));
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.INSTALL_USER, os.userInfo() ? os.userInfo().username : undefined);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.LOG_LEVEL_KEY, `debug`);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.LOG_PATH_KEY, path.join(TEST_HDB_PATH, 'log'));
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.LOG_DAILY_ROTATE_KEY, false);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.HDB_ROOT_KEY, TEST_HDB_PATH);
        setProperty(hdbTerms.CONFIG_PARAMS.STORAGE_PATH, TEST_HDB_PATH);
        const systemPath = typeof globalThis.databases !== 'undefined' &&
            globalThis.databases.system?.hdb_user?.primaryStore?.path;
        if (systemPath) {
            setProperty(hdbTerms.CONFIG_PARAMS.DATABASES, { system: { path: path.dirname(systemPath) } });
        }
        if (https_enabled) {
            setProperty(hdbTerms.CONFIG_PARAMS.HTTP_SECUREPORT, get(hdbTerms.CONFIG_PARAMS.HTTP_PORT));
            setProperty(hdbTerms.CONFIG_PARAMS.HTTP_PORT, null);
        }
        setProperty(hdbTerms.CONFIG_PARAMS.CUSTOMFUNCTIONS_NETWORK_HTTPS, Boolean(https_enabled));
        setProperty(hdbTerms.CONFIG_PARAMS.HTTP_PORT, 9926);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.SERVER_PORT_KEY, 9925);
        setProperty(hdbTerms.CONFIG_PARAMS.OPERATIONSAPI_NETWORK_PORT, 9925);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.CORS_ENABLED_KEY, commonUtils.isEmpty(cors_enabled) ? false : cors_enabled);
        setProperty(hdbTerms.CONFIG_PARAMS.HTTP_CORS, commonUtils.isEmpty(cors_enabled) ? false : cors_enabled);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.MAX_CUSTOM_FUNCTION_PROCESSES, 2);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.MAX_HDB_PROCESSES, 4);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_PORT_KEY, 9926);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_ENABLED_KEY, true);
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.CUSTOM_FUNCTIONS_DIRECTORY_KEY, path.join(propsPath, 'server/fastifyRoutes/custom_functions'));
        setProperty(hdbTerms.HDB_SETTINGS_NAMES.LOCAL_STUDIO_ON, commonUtils.isEmpty(local_studio_on) ? false : local_studio_on);
        if (cors_accesslist) {
            setProperty('CORS_ACCESSLIST', cors_accesslist);
            setProperty(hdbTerms.CONFIG_PARAMS.HTTP_CORSACCESSLIST, cors_accesslist);
        }
        if (server_timeout) {
            setProperty(hdbTerms.HDB_SETTINGS_NAMES.SERVER_TIMEOUT_KEY, server_timeout);
            setProperty(hdbTerms.CONFIG_PARAMS.HTTP_TIMEOUT, server_timeout);
        }
        if (keep_alive_timeout) {
            setProperty(hdbTerms.HDB_SETTINGS_NAMES.SERVER_KEEP_ALIVE_TIMEOUT_KEY, keep_alive_timeout);
            setProperty(hdbTerms.CONFIG_PARAMS.HTTP_KEEPALIVETIMEOUT, keep_alive_timeout);
        }
        if (headers_timeout) {
            setProperty(hdbTerms.HDB_SETTINGS_NAMES.SERVER_HEADERS_TIMEOUT_KEY, headers_timeout);
            setProperty(hdbTerms.CONFIG_PARAMS.HTTP_HEADERSTIMEOUT, headers_timeout);
        }
    }
    catch (err) {
        let msg = `Error reading in HDB environment variables from path ${BOOT_PROPS_FILE_PATH}.  Please check your boot props and settings files`;
        harper_logger_ts_1.default.fatal(msg);
        harper_logger_ts_1.default.error(err);
    }
}
//# sourceMappingURL=environmentManager.js.map