import { exec } from "../lib/builderator.js";


export const description = "Runs various services needed for development";

export const options = [
  ['--stop', `Stop the ${process.platform} OS services.`],
  ['--start', `Start the ${process.platform} OS services (the default).`],
  ['--noexit', `When used in other commands, don't call process.exit. Used when calling from other commands.`],
  ['--os <platform>', 'Force the process.platform to specific one']
]

const windows = (opts) => {
  if(opts.stop) {
    console.log("Stopping redis...");
    exec("wsl -u root /etc/init.d/redis-server stop");
  } else {
    console.log("Starting redis...")
    exec("wsl -u root /etc/init.d/redis-server start");
  }
}

const darwin = (opts) => {
  if(opts.stop) {
    console.log("Stopping pm2...");
    exec("npx pm2 stop scripts/osx.config.cjs");
  } else {
    console.log("Starting pm2...")
    exec("npx pm2 start scripts/osx.config.cjs");
    console.log("Use npx pm2 for more options.");
  }
}

const linux = (opts) => {
  if(opts.os === "linux") {
    darwin(opts);
  } else {
    console.error("On Linux you should run redis-server using systemctl or similar.  If you really want to use pm2 to manage redis then rerun this command with: --os linux");
    if(!opts.noexit) process.exit(1);
  }
}

export const main = (opts) => {
  const platform = opts.os ? opts.os : process.platform;

  if(process.platform === "win32") {
    windows(opts);
  } else if(process.platform === "linux") {
    linux(opts);
  } else if(process.platform === "darwin") {
    darwin(opts);
  } else {
    console.error(`ERROR: invalid OS ${platform} given, must be win32, linux, or darwin`);

    if(opts.noexit) {
      throw new Error("invalid OS error.");
    } else {
      if(!opts.noexit) process.exit(1);
    }
  }

  if(!opts.noexit) process.exit(0); // for some reason exec hangs on windows
}
