#!/bin/bash
#
#   deploy-parts - Deploy parts of an application
#
#   usage: deploy-parts --parts "api, app, web"
#
#   Parts defaults to "api, app, ui, web". Missing parts are silently ignored.
#   Parses keys.json and expands tokens using product.json and pak.json.
#   Calls bin/deploy if present, lese docker-deploy-elb if AWS_PROXY is defined, else docker-deploy-instance.
#   Invokes deploy script with same args as passed in.
#

function deployParts() {
    unset CDPATH
    local PARTS="api, app, ui, web"
    while [[ $# -gt 0 ]] ; do
        arg="$1"
        case ${arg} in
            --parts)
                PARTS="${2}"
                shift ; shift
                ;;
            *)
                break
                ;;
        esac
    done

    PARTS=$(echo ${PARTS} | tr ',' ' ')

    for part in ${PARTS} ; do
        [ ! -d "${part}" ] && continue
        echo -e "\nDeploying ${PART} ..."
        local files=""
        for f in CONFIG/keys.json ${part}/CONFIG/keys.json ${part}/product.json pak.json ; do
            [ -f ${f} ] && files="${files} ${f}"
        done
        eval $(paks/assist/json2env ${files})
        cd "./${part}"
        if [ -f bin/deploy ] ; then
            bin/deploy $*
        elif [ -f gulpfile.ts -o gulpfile.js -o gulpfile.babel.js ] ; then
            gulp deploy $*
        elif [ -f main.me ] ; then
            me deploy
        elif [ -f Makefile ] ; then
            make deploy
        fi
        [ $? != 0 ] && exit 2
        cd ..
    done
}

deployParts $*
