const cli = require('../cli-util');
const config = require('./config');

const t0 = Date.now();
const { app, version } = config;

if (cli.hasArg('--help') || !version) {
    return cli.help(app);
}

const bufferDir = config.buffer_directory;

config.REQUIRED_FIELDS.forEach(key => {
    if (!config[key]) {
        console.log(cli.error(`'${key}' is a required argument and is currently missing.`));
        console.log('See also --help.');
        process.exit(1);
    }
});

prebuild()
    .then(build)
    .then(push)
    .then(cleanup)
    .then(followup)
    .then(finalize)
    .catch(console.log);

function prebuild() {
    cli.stage('prebuild');

    let preinstallCmds = [];

    if (app) {
        const tempDir = `${bufferDir}-${Math.random().toString(36).substring(2)}`;

        // убираем из bufferDir всё, кроме папки с приложением,
        // содержимое папки с приложением поднимаем в bufferDir
        preinstallCmds = [
            `mv ${bufferDir}/${app} ${tempDir}`,
            `rm -rf ${bufferDir}`,
            `mv ${tempDir} ${bufferDir}`
        ];
    }

    return cli.cmd([
        `rm -rf ${bufferDir}`,
        `git clone --branch ${config.version_tag} ${config.app_repo} ${bufferDir}`,
        ...preinstallCmds,
        `cd ${bufferDir} && npm i${config.npm_registry ? ` --registry ${config.npm_registry}` : ''}`
    ]);
}

function build() {
    cli.stage('build');

    return cli.cmd([
        config.build_command ? `cd ${bufferDir} && ${config.apply(config.build_command)}` : null,
        `cd ${bufferDir} && npm prune --production`,
        'eval $(docker-machine env docker)',
        `docker build${config.dockerfile_path ? ` -f ${config.dockerfile_path}` : ''} -t ${config.build_registry}:${version} ${bufferDir}`,
        config.apply(config.postbuild)
    ]);
}

function push() {
    cli.stage('push');

    return cli.cmd([
        `docker push ${config.build_registry}:${version}`,
        config.apply(config.postpush)
    ]);
}

function cleanup() {
    cli.stage('cleanup');

    return cli.cmd(`rm -rf ${bufferDir}`);
}

function followup() {
    if (!config.followup) {
        return Promise.resolve();
    }

    cli.stage('followup');

    return cli.cmd(config.apply(config.followup));
}

function finalize() {
    if (app) {
        console.log(`\nDone! Build version ${cli.bold(version)} of ${cli.bold(app)} has been submitted.`);
    }
    else {
        console.log(`\nDone! Build version ${cli.bold(version)} has been submitted.`);
    }

    console.log(`Elapsed time: ${cli.elapsed(t0)}\n`);
}
