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."],
  ['--target', "rsync the results to this directory", "/var/www/learnjsthehardway.com"],
];

const config = {
  source_dir: "../ljsthw-private"
};

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

  // update the modules git too
  const cwd = process.cwd();
  process.chdir(config.source_dir);
  exec_i("git pull");
  process.chdir(cwd)

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

  if(opts.app) {
    exec_i("npm run knex migrate:latest");
    exec_i("npm run build");
  }

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

  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);
}
