import { glob, changed, exec_i } from "../lib/builderator.js";
import gen_players from "./gen_players.js";

export const description = "Deploys new changes to the app.";

export const options = [
  ['--dry-run', "Don't actually update, just pretend."],
  ['--no-content', "DO NOT deploy the render content, not the app."],
  ['--no-app', "DO NOT deploy the app, not the content."],
];

export const required = [
  ['--target <dir>', "rsync the results to this directory"],
];

export const main = (opts) => {
  exec_i("git pull");

  const dry_run = opts.dryRun ? "--dry-run" : "";

  if(opts.app) {
    exec_i("npm run knex migrate:latest");
    exec_i("npm run build");
    // reset the icons because we need them all for the demo
    exec_i("node bando.js icons");
    exec_i(`rsync -av --delete admin/bando public/`);
  }

  if(opts.content) {
    gen_players.main();
    exec_i("node ./bando.js rendered");
  }

  const ext_list = ["html", "css", "js", "svg", "xml", "md"];

  for(let ext of ext_list) {
    const files = glob(`./public/**/*.${ext}`);

    for(let fname of files) {
      if(changed(fname, `${fname}.br`)) {
        // compress the files with brotli
        exec_i(`brotli -Zfk "${fname}"`);
      }

      // compress the files with gzip
      if(changed(fname, `${fname}.gz`)) {
        exec_i(`gzip -9fk "${fname}"`);
      }
    }
  }

  // sync the files
  exec_i(`rsync ${dry_run} -av --exclude media --delete public/* ${ opts.target }`);

  process.exit(0);
}
