#!/usr/bin/env node
const unzip = require("unzipper");
const http = require("http");
const fs = require("fs");
const { Client } = require("minio");
const replace = require("replace-in-file");

const {
  VERSION,
  REPLACE_ENVS,
  MINIO_ACCESS_KEY,
  MINIO_SECRET_KEY,
  WORKING_DIR,
} = process.env;

async function main() {
  const message = VERSION ? "loading package" : "waiting for first deploy";
  const server = http.createServer((req, res) => {
    switch (req.url) {
      case "/":
        return res.writeHead(200).end(message);
      case "/health-live":
        return res.writeHead(200).end();
      case "/health-read":
        return res.writeHead(VERSION ? 400 : 200).end();
      default:
        return res.writeHead(404).end("not found");
    }
  });

  server.listen(process.env.PORT || 8080, () =>
    console.log("tmp-server:", message)
  );
  if (VERSION) {
    await downloadVersion(VERSION);
    if (REPLACE_ENVS) {
      await replaceEnv();
    }
    server.close();
  }
}
async function downloadVersion(version) {
  const client = new Client({
    endPoint: "minio.cloudticon.com",
    useSSL: true,
    port: 443,
    accessKey: MINIO_ACCESS_KEY,
    secretKey: MINIO_SECRET_KEY,
  });

  const stream = await client.getObject(
    process.env.NAMESPACE,
    version + ".zip"
  );
  stream.pipe(unzip.Extract({ path: WORKING_DIR }));
}

async function replaceEnv() {
  const dotenv = fs.readFileSync(`${WORKING_DIR}/.env`, "utf8");
  const envs = dotenv
    .split("\n")
    .filter((e) => !!e)
    .map((e) => {
      const [key, value] = e.split("=");
      return { key, value };
    });

  for (let env of envs) {
    if (process.env[env.key]) {
      console.log(`ENV ${env.key} replaced:`);
      const results = replace.sync({
        files: `${WORKING_DIR}/**/*`,
        from: env.value,
        to: process.env[env.key],
      });
      console.log(results.filter((r) => r.hasChanged).map((r) => r.file));
    } else {
      console.log(`ENV ${env.key} not found`);
    }
  }
}

main();
