// SPDX-License-Identifier: Apache-2.0
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
import { spawn } from 'node:child_process';
import chalk from 'chalk';
import { inject, injectable } from 'tsyringe-neo';
import { patchInject } from './dependency-injection/container-helper.js';
import { InjectTokens } from './dependency-injection/inject-tokens.js';
let ShellRunner = class ShellRunner {
    logger;
    constructor(logger) {
        this.logger = logger;
        this.logger = patchInject(logger, InjectTokens.SoloLogger, this.constructor.name);
    }
    /** Returns a promise that invokes the shell command */
    async run(cmd, arguments_ = [], verbose = false, detached = false) {
        // eslint-disable-next-line @typescript-eslint/typedef,unicorn/no-this-assignment
        const self = this;
        const callStack = new Error('INFO').stack; // capture the callstack to be included in error
        self.logger.info(`Executing command: '${cmd}'`);
        return new Promise((resolve, reject) => {
            const child = spawn(cmd, arguments_, {
                shell: true,
                detached,
                stdio: detached ? 'ignore' : undefined,
            });
            if (detached) {
                child.unref(); // allow the parent process to exit independently of this child
                resolve([]);
                return;
            }
            const output = [];
            child.stdout.on('data', (data) => {
                const items = data.toString().split(/\r?\n/);
                for (const item of items) {
                    if (item) {
                        output.push(item);
                    }
                }
            });
            const errorOutput = [];
            child.stderr.on('data', (data) => {
                const items = data.toString().split(/\r?\n/);
                for (const item of items) {
                    if (item) {
                        errorOutput.push(item.trim());
                    }
                }
            });
            child.on('exit', (code, signal) => {
                if (code) {
                    const error = new Error(`Command exit with error code ${code}, [command: '${cmd}'], [message: '${errorOutput.join('\n')}']`);
                    // include the callStack to the parent run() instead of from inside this handler.
                    // this is needed to ensure we capture the proper callstack for easier debugging.
                    error.stack = callStack;
                    if (verbose) {
                        for (const m of errorOutput) {
                            self.logger.showUser(chalk.red(m));
                        }
                    }
                    self.logger.error(`Error executing: '${cmd}'`, {
                        commandExitCode: code,
                        commandExitSignal: signal,
                        commandOutput: output,
                        errOutput: errorOutput,
                        error: { message: error.message, stack: error.stack },
                    });
                    reject(error);
                }
                self.logger.debug(`Finished executing: '${cmd}'`, {
                    commandExitCode: code,
                    commandExitSignal: signal,
                    commandOutput: output,
                    errOutput: errorOutput,
                });
                resolve(output);
            });
        });
    }
    async sudoRun(sudoRequested, sudoGranted, cmd, arguments_ = [], verbose = false, detached = false) {
        // Use Promise.race to handle sudo whoami and timeout
        let whoamiResolved = false;
        const whoamiPromise = this.run('sudo whoami').then(async (result) => {
            whoamiResolved = true;
            sudoGranted('Root access granted.');
            return result;
        });
        // eslint-disable-next-line no-async-promise-executor
        const timeoutPromise = new Promise(async (resolve) => {
            await new Promise(callback => setTimeout(callback, 500));
            if (!whoamiResolved) {
                sudoRequested('Please provide root permissions to proceed...');
            }
            resolve([]);
        });
        await Promise.race([whoamiPromise, timeoutPromise]);
        return this.run(`sudo ${cmd}`, arguments_, verbose, detached);
    }
};
ShellRunner = __decorate([
    injectable(),
    __param(0, inject(InjectTokens.SoloLogger)),
    __metadata("design:paramtypes", [Object])
], ShellRunner);
export { ShellRunner };
//# sourceMappingURL=shell-runner.js.map