const fs = require("fs");
const childProcess = require("child_process");
const server = "54.248.167.86";
const os = require("os");
const path = require("path");

const domain = /VITE_API_DOMAIN=(?<domain>.*)/.exec(
  fs.readFileSync(".env").toString()
)?.groups.domain;

if (!domain) {
  console.log("error domain");
  process.exit(-1);
}

console.log(domain);

function upload(src, dest) {
  console.log(`scp ${src} root@${server}:${dest}`);
  return new Promise((resolve, reject) => {
    const p = childProcess.spawn(`scp`, [
      "-o",
      "StrictHostKeyChecking=no",
      src,
      `root@${server}:${dest}`,
    ]);
    p.stdout.on("data", (data) => {
      console.log(data.toString());
    });

    p.stderr.on("data", (data) => {
      console.error(data.toString());
    });
    p.on("exit", (signal) => {
      if (signal === 0) resolve();
      else reject(`scp exit with code: ${signal}`);
    });
  });
}

function exec(cmd) {
  console.log(`ssh root@${server} ${cmd}`);
  return new Promise((resolve, reject) => {
    const p = childProcess.spawn(`ssh`, [
      "-o",
      "StrictHostKeyChecking=no",
      `root@${server}`,
      cmd,
    ]);
    p.stdout.on("data", (data) => {
      console.log(data.toString());
    });

    p.stderr.on("data", (data) => {
      console.error(data.toString());
    });
    p.on("exit", (signal) => {
      if (signal === 0) resolve();
      else reject(`ssh exit with code: ${signal}`);
    });
  });
}

function rsync() {
  console.log(
    `rsync --exclude='node_modules/' -ravzh --delete -e "ssh -o StrictHostKeyChecking=no" ./public/ root@54.248.167.86:/var/www/tg-web-fish/`
  );
  return new Promise((resolve, reject) => {
    const p = childProcess.spawn(`rsync`, [
      "--exclude='node_modules/'",
      "-ravzh",
      "--delete",
      "-e",
      "ssh -o StrictHostKeyChecking=no",
      "./public/",
      `root@${server}:/var/www/tg-web-fish/`,
    ]);
    p.stdout.on("data", (data) => {
      console.log(data.toString());
    });

    p.stderr.on("data", (data) => {
      console.error(data.toString());
    });
    p.on("exit", (signal) => {
      if (signal === 0) resolve();
      else reject(`rsync exit with code: ${signal}`);
    });
  });
}

const tmpDir = fs.mkdtempSync(os.tmpdir());
const api_conf_tmp = path.join(tmpDir, "api.conf");
const [part1, part2] = domain.split(".");
fs.writeFileSync(
  api_conf_tmp,
  fs
    .readFileSync("nginx_conf/api.conf")
    .toString()
    .replace("{part1}", part1)
    .replace("{part2}", part2)
);
console.log(api_conf_tmp);

upload(api_conf_tmp, "/etc/openresty/conf.d/api.conf")
  .then(() => {
    return exec("openresty -T");
  })
  .then(() => {
    return rsync();
  })
  .catch((e) => {
    console.log(e);
  });
