import { build, context } from "esbuild";
import { existsSync } from "fs";
import { rm, copyFile, mkdir } from "fs/promises";

const build_dir = "./build/";

const isBuild = process.argv.includes("--build");
const isServe = process.argv.includes("--serve");

if (existsSync(build_dir)) await rm(build_dir, { recursive: true });
await mkdir(build_dir, { recursive: true, mode: 0o755 });
await copyFile("./src/index.html", `${build_dir}/index.html`);

if (isBuild) {
  await build({
    bundle: true,
    entryPoints: ["./src/App.jsx"],
    logLevel: "info",
    minify: true,
    outfile: `${build_dir}/bundle.js`,
    sourcemap: false,
    target: ["es2019", "edge18", "firefox60", "chrome61", "safari11"],
    loader: {
      '.js': 'jsx',
      '.jpg': 'file',
    }
  });
}

if (isServe) {
  let ctx = await context({
    bundle: true,
    entryPoints: ["./src/App.jsx"],
    logLevel: "info",
    minify: false,
    outfile: `${build_dir}/bundle.js`,
    sourcemap: true,
    target: ["esnext"],
    loader: {
      '.js': 'jsx',
      '.jpg': 'file',
    }
  });

  const server = await ctx.serve({ servedir: build_dir });

  console.log(server);
}
