import grabCoderankSSHPrefix from "./grab-ssh-prefix";
import { exec, execSync, type ExecSyncOptions } from "child_process";
import debugLog from "@moduletrace/datasquirel/dist/package-shared/utils/logging/debug-log";

type Param = {
    cmd: string;
    debug?: boolean;
    server?: any;
    options?: ExecSyncOptions;
    detached?: boolean;
};

export default function execRawSSH({
    cmd,
    debug,
    server,
    options,
    detached,
}: Param): string | undefined {
    function debugFn(log: any, label?: string) {
        debugLog({
            log: log,
            label: label,
            title: "execRawSSH",
            addTime: true,
        });
    }

    try {
        let cmdPrefix = grabCoderankSSHPrefix();

        let finalCmd = `${cmdPrefix}`;

        if (server) {
            finalCmd += ` ${server.username}@${server.ip}`;
        }

        finalCmd += ` << 'CDREXEC' \n\
${cmd}\n\
CDREXEC`;

        if (debug) {
            debugFn(finalCmd, "finalCmd");
        }

        const str = detached
            ? ""
            : execSync(finalCmd, {
                  stdio: "pipe",
                  ...options,
                  encoding: "utf-8",
              });

        if (detached) {
            exec(finalCmd);
        }

        if (debug) {
            debugFn(str, "commandResult");
        }

        return str.trim();
    } catch (error: any) {
        if (debug) {
            debugFn(error.message, "Raw SSh Error");
        }

        return undefined;
    }
}
