"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHermitEnvs = exports.findHermitCwd = exports.isHermit = void 0;
const tslib_1 = require("tslib");
const os_1 = tslib_1.__importDefault(require("os"));
const upath_1 = tslib_1.__importDefault(require("upath"));
const global_1 = require("../../config/global");
const logger_1 = require("../../logger");
const fs_1 = require("../fs");
const common_1 = require("./common");
function isHermit() {
    const { binarySource } = global_1.GlobalConfig.get();
    return binarySource === 'hermit';
}
exports.isHermit = isHermit;
async function findHermitCwd(cwd) {
    const relativeCwd = upath_1.default.relative(global_1.GlobalConfig.get('localDir') ?? '', cwd);
    const hermitFile = await (0, fs_1.findUpLocal)('bin/hermit', relativeCwd);
    if (hermitFile === null) {
        throw new Error(`hermit not found for ${cwd}`);
    }
    return upath_1.default.join(global_1.GlobalConfig.get('localDir'), upath_1.default.dirname(hermitFile));
}
exports.findHermitCwd = findHermitCwd;
async function getHermitEnvs(rawOptions) {
    const cwd = rawOptions.cwd ?? '';
    const hermitCwd = await findHermitCwd(cwd);
    logger_1.logger.debug({ cwd, hermitCwd }, 'fetching hermit environment variables');
    // with -r will output the raw unquoted environment variables to consume
    const hermitEnvResp = await (0, common_1.rawExec)('./hermit env -r', {
        ...rawOptions,
        cwd: hermitCwd,
    });
    const lines = hermitEnvResp.stdout.split(os_1.default.EOL);
    const out = {};
    for (const line of lines) {
        const trimmedLine = line.trim();
        if (trimmedLine === '') {
            continue;
        }
        const equalIndex = trimmedLine.indexOf('=');
        const name = trimmedLine.substring(0, equalIndex);
        out[name] = trimmedLine.substring(equalIndex + 1);
    }
    return out;
}
exports.getHermitEnvs = getHermitEnvs;
//# sourceMappingURL=hermit.js.map