import { Client } from "ssh2";

type Param = {
    ssh: Client;
    cmd: string;
    debug?: boolean;
};

export default async function execSSH({
    ssh,
    cmd,
    debug,
}: Param): Promise<string | undefined> {
    if (!ssh) {
        console.log(`No SSH object passed into execSSH function`);

        return undefined;
    }
    return new Promise((resolve) => {
        let finalData = "";
        let stdErrData = "";

        ssh.exec(cmd, (err, stream) => {
            if (err) throw err;

            stream
                .on("close", (code?: number, signal?: string) => {
                    if (code || signal) {
                        resolve(undefined);
                    } else {
                        resolve(finalData);
                    }
                })
                .on("data", (data: any) => {
                    finalData += data;
                })
                .stderr.on("data", (data) => {
                    stdErrData += data;
                })
                .on("close", () => {
                    if (stdErrData.match(/./)) {
                        if (debug) {
                            console.log("SSH Error code:", stdErrData);
                        }

                        resolve(undefined);
                    }
                });
        });
    });
}
