#!/usr/bin/env node
"use strict";

const cp = require("child_process");
const yargs = require("yargs");
const argv = yargs.options({
        "b": {
            alias: "build",
            describe: "Build the project using prod build settings",
            boolean: true
        },
        "d": {
            alias: "deploy",
            describe: "Deploy the project to gh-pages",
            boolean: true
        },
        "q": {
            alias: "quiet",
            describe: "Minimal output from commands",
            boolean: true
        }
    })
    .help("h").alias("h", "help")
    .usage("Usage: $0 [-b] [-d]")
    .argv;

// Local variables:
let runBuild = argv.b;
let runDeploy = argv.d;
let quiet = argv.q;

if (!(runBuild || runDeploy)) {
    yargs.showHelp();
    process.exit();
}

if (runBuild) {
    console.log("Building for production...");
    runCommand("npm", ["run", "build:prod"]);
}

if (runDeploy) {
    // Fail if there are uncommitted changes
    let exitCode = runCommand("git", ["diff-index", "--quiet", "--cached", "HEAD"]);
    if (exitCode !== 0) {
        // TODO: automatically stash changes
        console.error("There are uncommitted changes in your index. Please commit or stash them first.");
        process.exit();
    }

    console.log("Adding dist to repository...");
    runCommand("git", ["add", "dist"]);
    runCommand("git", ["commit", "-m", "'Update prod build'"]);
    console.log("Pushing to gh-pages...");
    runCommand("git", ["subtree", "push", "--prefix", "dist", "origin", "gh-pages"]);
}

console.log("Done!");


// Helper functions:
function runCommand(command, args) {
    let options = {};
    if (!quiet) {
        options["stdio"] = "inherit";
    }
    let result = cp.spawnSync(command, args, options);
    return result.status;
}

@@ -1150,16 +1150,36 @@
 .error(%22
+Deployment failure: 
 There ar
@@ -1282,16 +1282,297 @@
 );%0A    %7D
+%0A    // Fail if unpushed commits%0A    exitCode = runCommand(%22git%22, %5B%22diff-tree%22, %22@%7Bu%7D%22, %22HEAD%22, %22--quiet%22%5D);%0A    if (exitCode !== 0) %7B%0A        console.error(%22Deployment failure: There are unpushed changes in your local repo. Please push them first.%22);%0A        process.exit();%0A    %7D
 %0A%0A    co

Update deploy script