import grabCoderankSSHPrefix from "./grab-ssh-prefix";
import { execSync, type ExecSyncOptions } from "child_process";

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

export default function bunExecSSH({
    filePath,
    debug,
    server,
    options,
}: Param): string | undefined {
    try {
        let cmdPrefix = grabCoderankSSHPrefix();

        let finalCmd = `${cmdPrefix}`;

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

        finalCmd += ` bun < ${filePath}`;

        if (debug) {
            console.log("DEBUG:::", finalCmd);
        }

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

        if (debug) {
            console.log("DEBUG:::", str);
        }

        return str.trim();
    } catch (error: any) {
        if (debug) {
            console.log(`DEBUG::: Raw SSh Error: ${error.message}`);
        }

        return undefined;
    }
}
