Source: libs/constants/cli-args.js

let build_arguments = require('commander');
let _ = require('lodash');
const fse = require('fs-extra');
const path = require('path');
const os = require('os');

/** @class cli-args */

/**
 *
 */
build_arguments
    .version(require('./../../package.json').version)
    .option('-b, --branch [branch]', 'Commit sha or branch to build, either work')
    .option('-p, --platform [platform]', 'Platform to build [ios,android,web,api]')
    .option('-t, --target [target]', 'Target environment settings for build')
    .option('-g, --getCurl', 'Returns command to execute job, and does not execute', false)
    .option('-r, --release', 'Delivers build to Google Play or iTunes store',false,false)
    .option('-j', '--jiraIds', 'Command must be ran in a repository directory, and will return Jira ids found between two command sha\'s',false)


module.exports = (()=>{
    /**
     * Looks at file system for settings.json matching request build arguments @ ~/.droneup/TARGET/PLATFORM/settings.json
     * @memberOf cli-args
     * @property arguments {instance.arguments} Parsed command line arguments into object
     * @property build_settings {instance.build_settings} Read json build settings from %HOME%/.droneup/environments/TARGET/PLATFORM/settings.json
     */
    let buildSettingExist = (instance,callback) => {
        if (_.isNil(instance.arguments)){
            instance.arguments = build_arguments.parse(process.argv);
            if (validArgs()){
                let base_path = path.resolve(os.homedir(),'.droneup','environments',instance.arguments.target,instance.arguments.platform,'settings.json')
                fse.pathExists(base_path, (err, exists) => {
                    if (exists === true) {

                        let cliArgs='';
                            _.compact(_.map(instance.arguments.rawArgs,(arg,index)=>{
                            if (index >>1){
                                cliArgs+=instance.arguments.rawArgs[index] + ' ';
                            }
                        }));
                        console.log('Executing build with the following arguments:', cliArgs)
                        console.log('Found settings for target', instance.arguments.target, 'for platform', instance.arguments.platform);
                            instance.build_settings = require(base_path);
                            checkUseDefaultBranch(instance.build_settings.default_branch);
                            callback(null);
                    } else {
                        console.log('Unable to find settings for target', instance.arguments.target, 'for platform', instance.arguments.platform);
                        process.exit(1);
                    }
                });
                /**
                 * Checks for USE_SETTINGS_DEFAULT_BRANCH in process.arv, if found it assigns default_branch from settings
                 * Fixes #1
                 */
                function checkUseDefaultBranch (settingsDefaultBranch){
                    let foundIndex = -1;
                    let requestedDefaultBranch = _.filter(process.argv,(arg,index)=>{
                        if (arg === '##USE_SETTINGS_DEFAULT_BRANCH##'){
                            foundIndex = index;
                            return arg;
                        }
                    })

                    let computedBranch = function(){
                        if (requestedDefaultBranch.length===1 && foundIndex !== -1){
                            process.argv[foundIndex] = settingsDefaultBranch;
                        }
                    }
                    return computedBranch();
                }
            } else {
                process.exit(0);
            }

        }

    }

    /**
     * Verifies cli was given all required arguments.
     * @memberOf cli-args
     * @returns {boolean}
     */
    function validArgs(){
        /** Verify cli execution has all required options. [target] [platform] [branch] */
        if (_.isNil(build_arguments.target) || _.isNil(build_arguments.platform) || _.isNil(build_arguments.branch)) {
            return false
        } else {
            return true;
        }
    }

    /**
     * Evaluates all cli arguments given to function and returns {@link commander} object
     * @memberOf cli-args
     * @returns {build_arguments} object
     * {@link https://www.npmjs.com/package/commander commander}.
     */
    let processArguments = (options)  =>{
        try{
            build_arguments.parse(options);
            if (_.isNil(build_arguments.target) || _.isNil(build_arguments.platform) || _.isNil(build_arguments.branch)) {
                build_arguments.outputHelp();
            } else {
                return build_arguments;
            }
        }
        catch(err){
            build_arguments.outputHelp();
            console.log('');
            process.exit(0);
        }
    }
    return {
        processArguments: processArguments,
        buildSettingExist: buildSettingExist
    }
})();