import { spawn, ChildProcess } from "child_process";
import colors from "./console-colors";

let redeployments = 0;

const KILL_SIGNAL: NodeJS.Signals | number = "SIGTERM";

const pTitle = "nodecid";
process.title = pTitle;

/**
 * ## Preflight Function
 * @param {string} command
 * @returns {ChildProcess | null}
 */
export default function run(command: string): ChildProcess | null {
    console.log("\n******************************");
    console.log(
        `****** ${colors.FgGreen}Starting App ...${colors.Reset} ******`
    );
    console.log("******************************\n");

    const startCommandArray = command.split(" ").filter((str) => str.trim());

    try {
        const firstCommand = startCommandArray.shift();

        if (!firstCommand) {
            throw new Error("No Starting Command Found in command string!");
        }

        let childProcess = spawn(firstCommand, startCommandArray, {
            stdio: "inherit",
            killSignal: KILL_SIGNAL,
        });

        redeployments++;

        return childProcess;
    } catch (error: any) {
        console.log(
            `${colors.FgRed}Error:${colors.Reset} running start command => ${error.message}`
        );
        return null;
    }
}
