import { execSync, ExecSyncOptions } from "child_process";
import os from "os";

export type ExportMariaDBDatabaseParam = {
    dbFullName: string;
    targetFilePath: string;
    mariadbUser?: string;
    mariadbHost?: string;
    mariadbPass?: string;
};

export default function exportMariadbDatabase({
    dbFullName,
    targetFilePath,
    mariadbHost,
    mariadbPass,
    mariadbUser,
}: ExportMariaDBDatabaseParam) {
    const mysqlDumpPath = os.platform().match(/win/i)
        ? "'" +
          "C:\\Program Files\\MySQL\\MySQL Server 8.0\\bin\\mysqldump.exe" +
          "'"
        : "mysqldump";

    const finalMariadbUser = mariadbUser || process.env.DSQL_DB_USERNAME;
    const finalMariadbHost = mariadbHost || process.env.DSQL_DB_HOST;
    const finalMariadbPass = mariadbPass || process.env.DSQL_DB_PASSWORD;

    const cmd = `${mysqlDumpPath} -u ${finalMariadbUser} -h ${finalMariadbHost} -p${finalMariadbPass} ${dbFullName} > ${targetFilePath}`;

    let execSyncOptions: ExecSyncOptions = {
        encoding: "utf-8",
    };

    const dumpDb = execSync(cmd, execSyncOptions);

    return dumpDb;
}
