#!/usr/bin/env node
const rl = require('readline');
const exec = require('child_process').exec;
const prompts = rl.createInterface(process.stdin, process.stdout);

const q = msg => new Promise((resolve) => prompts.question(msg, resolve));

const ex = cmd => new Promise((resolve, reject) => {
    exec(cmd, (err, stdout, stderr) => {
        resolve({ok: !err, data: stdout, error: stderr});
    });
});

const validVersions = ['patch', 'minor', 'major'];

const log = (...args) => console.log(...args);

const logError = (...args) => console.error(...args);

(async () => {
    try {
        let branch = await q('branch: (default: "origin master")');

        branch = branch || 'origin master';

        let msg = await q('message for git commit: (default: ".")');

        msg = msg || ".";

        let version = await q('add npm version bump: (default: "patch")');

        version = validVersions.includes(version) ? version : 'patch';

        log('running build');

        const build = await ex('npm run build');

        if (!build.ok) {
            logError('error running build');
            logError(build.error);
            process.exit();
        }

        log('build finished');

        log('git adding');

        await ex('git add .');

        await ex(`git commit -m "${msg}"`);

        log('git committed');

        const versionResults = await ex(`npm version ${version}`);

        log(`${versionResults.data}`.trim())

        log('publishing to npm');

        await ex('npm publish');

        log('published');

        log('pushing to git')

        await ex(`git push ${branch}`);

        log('done');

        process.exit()

    } catch (e) {
        logError(e);
        process.exit();
    }
})();
