const fs = require("fs-extra");
const path = require("path");
const argsParser = require("yargs-parser");
const dayjs = require("dayjs");

const packagePath = path.join(
  process.env.BUILD_WORK_DIR || ".",
  "package.json"
);

try {
  const package = JSON.parse(fs.readFileSync(packagePath, "utf-8"));
  const { version } = package;
  if (process.env && process.env.BUILD_ARGV_STR) {
    const buildArgv = argsParser(process.env.BUILD_ARGV_STR);
    if (buildArgv.def_publish_env === "daily") {
      fs.writeFileSync(
        packagePath,
        JSON.stringify(
          {
            ...package,
            version: `${version}-beta.${dayjs().format("YYYYMMDDHHmm")}`,
          },
          undefined,
          " "
        )
      );
    }
  }

  const targetDirName = path.relative(
    process.env.BUILD_WORK_DIR,
    process.env.BUILD_DEST_ABSOLUTE
  );
  for (const fileOrDir of fs.readdirSync(process.env.BUILD_WORK_DIR)) {
    if (fileOrDir !== targetDirName && fileOrDir !== "node_modules") {
      fs.copySync(
        path.join(process.env.BUILD_WORK_DIR, fileOrDir),
        path.join(process.env.BUILD_DEST_ABSOLUTE, fileOrDir)
      );
    }
  }
} catch (err) {
  console.log(err);
  process.exit(1);
}
