#!/bin/bash -e

# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                                         #
#  Copyright (C) 2018 Simon Stürz <simon.stuerz@guh.io>                   #
#                                                                         #
#  This file is part of lambdabuilder.                                    #
#                                                                         #
#  Lambdabuilder is free software: you can redistribute it and/or modif   #
#  it under the terms of the GNU General Public License as published by   #
#  the Free Software Foundation, version 2 of the License.                #
#                                                                         #
#  Lambdabuilder is distributed in the hope that it will be useful,       #
#  but WITHOUT ANY WARRANTY; without even the implied warranty of         #
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the           #
#  GNU General Public License for more details.                           #
#                                                                         #
#  You should have received a copy of the GNU General Public License      #
#  along with lambdabuilder. If not, see <http://www.gnu.org/licenses/>.  #
#                                                                         #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #



VERSION=0.1.0
APPLICATION=$(basename $0)

#------------------------------------------------------------------------------------------
function usage() {
  cat <<EOF
Usage: $(basename $0) [OPTIONS] [COMMAND]

This tool should help building and deploying node based AWS lambda function inside an lxd container.

Copyright © 2018 Simon Stürz <simon.stuerz@guh.io>
Version: ${VERSION}

Note: Only one command is accepted each call.

COMMANDS:
  shell                   Log into shell from builder container
  info                    Print information about the current build environment
  start                   Start the builder container
  stop                    Stop the builder container
  delete                  Delete the container
  clean                   Clean all build and test data
  deploy                  Build, test and deploy the lambda function to development account
  deploy-production       Build, test and deploy the lambda function to production account
  help                    Show this help message
  create-image            Create the lxc build image for the aws lambda builder

OPTIONS:
  -t, --test-data [DIR]   The directory where the aws test user credentials are located
  -a, --aws-dir [DIR]     The directory where the aws configration and credentials are located
  -s, --ssh-dir [DIR]     The directory where the ssh configration and credentials are located. Default $HOME/.ssh
  -n, --node [VERSION]    The node version to use for building the lambda function
                          Available versions can be found here: https://nodejs.org/download/release/
  --no-colors             Disable colorfull output
  -h, --help              Show this help message
  -v, --version           Show the version of the tool

EOF
}

#------------------------------------------------------------------------------------------
# bash colors
BASH_GREEN="\e[1;32m"
BASH_ORANGE="\e[33m"
BASH_RED="\e[1;31m"
BASH_NORMAL="\e[0m"

printGreen() {
    if ${COLORS}; then
        echo -e "${BASH_GREEN}[+] AWS lambda builder: $1${BASH_NORMAL}"
    else
        echo -e "[+] AWS lambda builder: $1"
    fi
}

printOrange() {
    if ${COLORS}; then
        echo -e "${BASH_ORANGE}[-] AWS lambda builder: $1${BASH_NORMAL}"
    else
        echo -e "[-] AWS lambda builder: $1"
    fi
}

printRed() {
    if ${COLORS}; then
        echo -e "${BASH_RED}[!] AWS lambda builder: $1${BASH_NORMAL}"
    else
        echo -e "[!] AWS lambda builder: $1"
    fi
}

#------------------------------------------------------------------------------------------
createContainer() {
    if lxc info ${CONTAINERNAME} > /dev/null 2>&1 ; then
        #printOrange "--> Container ${CONTAINERNAME} already exists."
        startContainer
        return 0
    fi

    printGreen "Create lxc container ${CONTAINERNAME}"
    lxc remote --public=true --accept-certificate=true add nymea https://jenkins.nymea.io || true

    lxc init nymea:${IMAGENAME} ${CONTAINERNAME}
    lxc config set ${CONTAINERNAME} security.privileged true

    # Start container
    startContainer
    waitContainerNetwork

    # Set up user
    USERNAME_CONTAINER=`lxc exec ${CONTAINERNAME} grep ":$USERID:" /etc/passwd | cut -f 1 -d ":"`
    if [ ! -z "$USERNAME_CONTAINER" ]; then
        # Note remove the current container user only if the user id is the same
        printGreen "Removing user in container with the same user id: $USERNAME_CONTAINER"
        lxc exec --env GROUPID=$GROUPID --env GROUPNAME=$GROUPNAME ${CONTAINERNAME} -- userdel $USERNAME_CONTAINER || true
        lxc exec --env GROUPID=$GROUPID --env GROUPNAME=$GROUPNAME ${CONTAINERNAME} -- delgroup $USERNAME_CONTAINER || true
    fi

    printGreen "Create user $USERNAME in the container"
    lxc exec --env GROUPID=$GROUPID --env GROUPNAME=$GROUPNAME ${CONTAINERNAME} -- addgroup --gid $GROUPID $GROUPNAME
    lxc exec --env GROUPID=$GROUPID --env USERNAME=$USERNAME --env USERID=$USERID ${CONTAINERNAME} -- adduser --disabled-password \
             --gecos "" --uid $USERID --gid $GROUPID $USERNAME

    execContainerRoot adduser $USERNAME sudo
    execContainerRoot passwd --delete $USERNAME

    # Mount source directory into folder
    if ! lxc config device get ${CONTAINERNAME} current_dir_mount disk 2> /dev/null ; then
        printGreen "Mounting build directory ${BUILDDIR} into container."
        lxc config device add ${CONTAINERNAME} current_dir_mount disk source=$BUILDDIR path=$BUILDDIR_MOUNT
    else
        lxc config device set ${CONTAINERNAME} current_dir_mount source $BUILDDIR
    fi

    # Mount aws directory into container
    if ! lxc config device get ${CONTAINERNAME} aws_dir_mount disk 2> /dev/null ; then
        printGreen "Mounting aws-dir ${AWS_SECRETS} into container."
        lxc config device add ${CONTAINERNAME} aws_dir_mount disk source=$AWS_SECRETS path=$AWS_SECRETS_MOUNT
    else
        lxc config device set ${CONTAINERNAME} aws_dir_mount source $AWS_SECRETS
    fi

    # Mount test-data directory into container
    if ! lxc config device get ${CONTAINERNAME} test-data_dir_mount disk 2> /dev/null ; then
        printGreen "Mounting test-data ${AWS_TESTDATA} into container."
        lxc config device add ${CONTAINERNAME} test-data_dir_mount disk source=$AWS_TESTDATA path=$AWS_TESTDATA_MOUNT
    else
        lxc config device set ${CONTAINERNAME} test-data_dir_mount source $AWS_TESTDATA
    fi

    # Mount ssh directory into container
    if ! lxc config device get ${CONTAINERNAME} ssh_dir_mount disk 2> /dev/null ; then
        printGreen "Mounting ssh folder ${SSH_DIRECTOY} into container."
        lxc config device add ${CONTAINERNAME} ssh_dir_mount disk source=$SSH_DIRECTOY path=$SSH_DIRECTOY_MOUNT
    else
        lxc config device set ${CONTAINERNAME} ssh_dir_mount source $SSH_DIRECTOY
    fi
}

#------------------------------------------------------------------------------------------
# Note: this is only needed if you want to create the base
createBaseImage() {
    printGreen "Create base image for aws lambda builder:"

    CONTAINERNAME=${IMAGENAME}-base

    # Check if there is an image
    if lxc image info ${IMAGENAME} > /dev/null 2>&1; then
        printRed "There is already an image with the name ${IMAGENAME}. Please rename or delete the existing image."
        exit 1
    fi

    # Check if there is a container
    if lxc info ${CONTAINERNAME} > /dev/null 2>&1 ; then
        printRed "--> Container ${CONTAINERNAME} already exists. Please rename or delete the existing container."
        return 1
    fi

    # Get the bionic image
    printGreen "Create base container ${CONTAINERNAME}"
    lxc init ubuntu:18.04 ${CONTAINERNAME}

    startContainer
    waitContainerNetwork

    # Update
    execContainerRoot apt -y update
    execContainerRoot apt -y upgrade

    # Install packages
    execContainerRoot apt -y install python unzip sudo socat git

    # install aws-cli
    printGreen "Install aws-cli"
    execContainerRoot wget https://s3.amazonaws.com/aws-cli/awscli-bundle.zip
    execContainerRoot unzip awscli-bundle.zip
    execContainerRoot ./awscli-bundle/install -i /usr/local/aws -b /usr/local/bin/aws
    execContainerRoot rm -r awscli-bundle*
    execContainerRoot aws --version

    # Setup preinstalled node versions
    installNode "v12.16.1"

    # Clean up container
    execContainerRoot apt -y autoremove
    execContainerRoot apt -y clean

    # Create the image out of this container
    stopContainer
    printGreen "Create image ${IMAGENAME} out of the container ${CONTAINERNAME}"
    lxc publish ${CONTAINERNAME} --alias ${IMAGENAME}
    deleteContainer
    lxc image list | grep ${IMAGENAME}
}

#------------------------------------------------------------------------------------------
waitContainerNetwork() {
    printGreen "Wait for container getting online..."
    NETWORK_UP=0
    for i in `seq 1 20`; do
        if lxc info ${CONTAINERNAME} | grep -e "eth0.*inet\b" > /dev/null 2>&1 ; then
            NETWORK_UP=1
            printGreen "Container is online"
            break
        fi
        sleep 1
    done

    if [ $NETWORK_UP -ne 1 ] ; then
        printRed "Container is not connected to the Internet."
        exit 1
    fi
}

#------------------------------------------------------------------------------------------
waitDpkgAvailable() {
    printGreen "Wait for container dpkg getting available..."
    DPKG_AVAILABLE=0

    for i in `seq 1 60`
    do
        #echo "${ERROR_COLOR} /var/lib/dpkg/lock exists... Waiting for it to disappear...${NC}"
        if execContainerRoot test ! -e /var/lib/dpkg/lock; then
            DPKG_AVAILABLE=1
            printGreen "The update manager is available now."
            break
        fi
        sleep 1
    done
    if [ $DPKG_AVAILABLE -ne 1 ] ; then
        #echo "${ERROR_COLOR} /var/lib/dpkg/lock still exists after one minute. Assuming it is stale. Deleting it...${NC}"
        execContainerRoot rm /var/lib/dpkg/lock
    fi
}


#------------------------------------------------------------------------------------------
forwardSshAgent() {
    if [ -z $SSH_AUTH_SOCK ]; then
        printOrange "There is ssh-agent authentication socket available. Skipping ssh-agent forwarding."
        unset SSH_AGENT_PID
        return 0
    fi

    if [ ! -z $SSH_AGENT_PID ]; then
        printOrange "The ssh-agent is already forwarded. Skipping ssh-agent forwarding."
        return 0
    fi

    SSH_AGENT_SCRIPT=$(cat << EOF
echo "Setup ssh-agent forward"
trap "echo 'Stop ssh-agent forward'; exit 0" SIGINT SIGTERM
lxc exec ${CONTAINERNAME} -- "rm ${SSH_AGENT_SOCKET} || true"
while :; do
    socat UNIX:$SSH_AUTH_SOCK EXEC:"lxc exec ${CONTAINERNAME} -- /usr/bin/socat STDIN UNIX-LISTEN\:${SSH_AGENT_SOCKET}";
done
EOF
)
    # Execute the pipe and store the PID for clean up
    bash -e -x -c "${SSH_AGENT_SCRIPT}" &
    SSH_AGENT_PID=$!
    printGreen "Forward ssh-agent ${SSH_AUTH_SOCK} successfully info container. Forward PID: $SSH_AGENT_PID"
}

#------------------------------------------------------------------------------------------
containerRunning() {
    lxc list | grep ${CONTAINERNAME} | grep RUNNING > /dev/null 2>&1
    return $?
}

#------------------------------------------------------------------------------------------
installNode() {
    cleanNodeLinks
    NODE_VERSION=$1
    printGreen "Set up node version ${NODE_VERSION}"
    if  execContainerRoot ls /usr/local/node-${NODE_VERSION}-linux-x64  > /dev/null 2>&1; then
        printGreen "node version ${NODE_VERSION} already installed."
        createNodeLinks
        printBuildVersions
        return 0
    fi

    printGreen "Installing node version ${NODE_VERSION}"

    # Download node
    printGreen "Download node ${NODE_VERSION} ..."
    execContainerRoot wget https://nodejs.org/download/release/${NODE_VERSION}/node-${NODE_VERSION}-linux-x64.tar.gz
    execContainerRoot ls -lh node-${NODE_VERSION}-linux-x64.tar.gz
    printGreen "Extract node-${NODE_VERSION}-linux-x64.tar.gz to /usr/local/"
    execContainerRoot tar xf node-${NODE_VERSION}-linux-x64.tar.gz -C /usr/local/
    execContainerRoot rm -v node-${NODE_VERSION}-linux-x64.tar.gz

    createNodeLinks

    # install serverless
    printGreen "Install serverless"
    execContainerRoot npm i -g serverless

    createNodeLinks
    printBuildVersions
}

#------------------------------------------------------------------------------------------
printBuildVersions() {
    echo "Node version: $(execContainerRoot node --version)"
    echo "npm version: $(execContainerRoot npm --version)"
    echo "serverless version: $(execContainerRoot serverless --version)"
    execContainerRoot aws --version
}


#------------------------------------------------------------------------------------------
createNodeLinks() {
    cleanNodeLinks
    execContainerRoot ln -s /usr/local/node-${NODE_VERSION}-linux-x64 /usr/local/node
    execContainerRoot ln -s /usr/local/node/bin/node /usr/local/bin/node
    execContainerRoot ln -s /usr/local/node/bin/npm /usr/local/bin/npm
    execContainerRoot ln -s /usr/local/node/bin/serverless /usr/local/bin/serverless || true
}

#------------------------------------------------------------------------------------------
cleanNodeLinks() {
    execContainerRoot rm -v /usr/local/bin/npm > /dev/null 2>&1 || true
    execContainerRoot rm -v /usr/local/bin/node > /dev/null 2>&1 || true
    execContainerRoot rm -v /usr/local/bin/serverless > /dev/null 2>&1 || true
    execContainerRoot rm -v /usr/local/node > /dev/null 2>&1 || true
}

#------------------------------------------------------------------------------------------
startContainer() {
    if ! containerRunning; then
        printGreen "Start container ${CONTAINERNAME}"
        lxc start ${CONTAINERNAME};
    fi

    #forwardSshAgent
}

#------------------------------------------------------------------------------------------
stopContainer() {
    printGreen "Stop container ${CONTAINERNAME}"
    lxc stop ${CONTAINERNAME} --force || true
}

#------------------------------------------------------------------------------------------
deleteContainer() {
    printGreen "Delete container ${CONTAINERNAME}"
    lxc delete ${CONTAINERNAME} --force || true
}

#------------------------------------------------------------------------------------------
enterShell() {
    printGreen "Enter shell in container ${CONTAINERNAME}"
    #execContainer bash
    lxc exec ${CONTAINERNAME} -- su --login ${USERNAME}
    #lxc exec ${CONTAINERNAME} bash
}

#------------------------------------------------------------------------------------------
execContainerRoot() {
    EXECUTION="$@"
    ENVIRONMENT=$(containerEnvironment)
    #printGreen "Execute command in container as root: $ENVIRONMENT $EXECUTION"
    #printGreen "Environment: $ENVIRONMENT"
    lxc exec ${CONTAINERNAME} -- su -c "$ENVIRONMENT $EXECUTION"
}

#------------------------------------------------------------------------------------------
execContainer() {
    EXECUTION="$@"
    ENVIRONMENT=$(containerEnvironment)
    #printGreen "Execute command in container: $EXECUTION"
    #printGreen "Environment: $ENVIRONMENT"
    lxc exec ${CONTAINERNAME} -- su -l -c \
    "cd $BUILDDIR_MOUNT; $ENVIRONMENT $EXECUTION" $USERNAME
}

#------------------------------------------------------------------------------------------
containerEnvironment() {
    cat <<EOF
export CHANNEL=${CURRENT_CHANNEL};
export TESTDATA=${AWS_TESTDATA_MOUNT};
export JUNIT_REPORT_PATH=${TEST_XML_OUTPUT};
export SSH_AUTH_SOCK=${SSH_AGENT_SOCKET};

EOF
}


#------------------------------------------------------------------------------------------
build() {
    installNode ${NODE_VERSION}
    execContainer npm config set color ${COLORS}

    printGreen "Build environment"
    execContainer env

    cleanBuild

    printGreen "Building ${PROJECTNAME} (commit: ${COMMITHASH}) using node $(execContainer node --version) | npm install"
    execContainer npm install
}

#------------------------------------------------------------------------------------------
buildProduction() {
    installNode ${NODE_VERSION}
    execContainer npm config set color ${COLORS}

    cleanBuild

    printGreen "Building ${PROJECTNAME} (commit: ${COMMITHASH}) using node $(execContainer node --version) | npm install --production"
    execContainer npm install --production
}

#------------------------------------------------------------------------------------------
cleanBuild() {
    printGreen "Clean build"
    execContainer rm -rf node_modules/ || true
}

#------------------------------------------------------------------------------------------
cleanAll() {
    printGreen "Clean all data"
    cleanBuild
    printGreen "Clean test results"
    execContainer rm -v *report.xml || true
}

#------------------------------------------------------------------------------------------
testLocal() {
    printGreen "Run local tests..."
#    TEST_XML_OUTPUT=${BUILDDIR_MOUNT}/test-local-result.xml
#    execContainer npm config set color ${COLORS}
#    execContainer npm run test-jenkins test/local-tests.js
}

#------------------------------------------------------------------------------------------
testRemote() {
    printGreen "Run remote tests..."
#    TEST_XML_OUTPUT=${BUILDDIR_MOUNT}/test-remote-result.xml
#    execContainer npm config set color ${COLORS}
#    execContainer npm run test-jenkins test/remote-tests.js
}

#------------------------------------------------------------------------------------------
deploy() {
    buildProduction

    # Deploy
    printGreen "Serverless information of AWS development environemnt"
    execContainer serverless info -s dev || true

    printGreen "Deploy to AWS development environemnt"
    execContainer serverless deploy -s dev

    printGreen "Serverless information of AWS development environemnt"
    execContainer serverless info -s dev

    build
    testRemote
}

#------------------------------------------------------------------------------------------
deployProduction() {
    printOrange "======================================================================="
    printOrange "Deploy to production. Use this function with caution!"
    printOrange "======================================================================="

    # Deploy
    printGreen "Serverless information of AWS development environemnt"
    execContainer serverless info -s prod || true

    printGreen "Deploy to AWS development environemnt"
    execContainer serverless deploy -s prod

    printGreen "Serverless information of AWS development environemnt"
    execContainer serverless info -s prod

    build
    testRemote
}

#------------------------------------------------------------------------------------------
initEnv() {

    PROJECTNAME=$(basename `git rev-parse --show-toplevel`)
    COMMITHASH=$(git rev-parse --short HEAD)

    # Container user
    USERNAME=`id --user --name`
    GROUPNAME=$USERNAME
    USERID=`id --user`
    GROUPID=`id --group`

    # Directories
    BUILDDIR=$(pwd)
    USERDIR=/home/${USERNAME}
    BUILDDIR_MOUNT=${USERDIR}/${PROJECTNAME}
    AWS_SECRETS="/home/${USERNAME}/.aws"
    SSH_DIRECTOY="/home/${USERNAME}/.ssh"
    SSH_DIRECTOY_MOUNT="/home/${USERNAME}/.ssh"
    AWS_TESTDATA="/home/${USERNAME}/.test-data"
    AWS_SECRETS_MOUNT="/home/${USERNAME}/.aws"
    AWS_TESTDATA_MOUNT="/home/${USERNAME}/.test-data"
    TEST_XML_OUTPUT=${BUILDDIR_MOUNT}/test-local-result.xml

    # Container stufff
    IMAGENAME=nymea-aws-lambda-builder
    CONTAINERNAME=builder-${PROJECTNAME}-${IMAGENAME}

    # Build options
    PRODUCTION=false
    DEPLOY=false
    CURRENT_CHANNEL=development
    NODE_VERSION=v12.16.1

    # Script options
    COLORS=true
    CONFIGDIR=${BUILDDIR}/.lambdabuilder
    CONFIG=${CONFIGDIR}/config

    # ssh-agent
    unset SSH_AGENT_PID
    SSH_AGENT_SOCKET=/tmp/ssh-agent-sock

    loadConfiguration
}

#------------------------------------------------------------------------------------------
loadConfiguration() {
    if [ -e ${CONFIG} ]; then
        . ${CONFIG}
    else
        # Save default configuration
        saveConfiguration
    fi
}

#------------------------------------------------------------------------------------------
saveConfiguration() {
    if [ ! -d ${CONFIGDIR} ]; then mkdir ${CONFIGDIR}; fi
    if [ -e ${CONFIG} ]; then rm ${CONFIG}; fi
    touch ${CONFIG}

    echo "# AWS lambda builder configuration for ${PROJECTNAME}" >> ${CONFIG}
    echo "COLORS=${COLORS}" >> ${CONFIG}
    echo "NODE_VERSION=${NODE_VERSION}" >> ${CONFIG}
    echo "AWS_SECRETS=${AWS_SECRETS}" >> ${CONFIG}
    echo "AWS_TESTDATA=${AWS_TESTDATA}" >> ${CONFIG}
    echo "SSH_DIRECTOY=${SSH_DIRECTOY}" >> ${CONFIG}
}

#------------------------------------------------------------------------------------------
printInfo() {
    echo "Project name: ${PROJECTNAME}"
    echo "- Directories:"
    echo "    Build directory: ${BUILDDIR}"
    echo "    Build mount directory: ${BUILDDIR_MOUNT}"
    echo "    AWS secret directoriy: ${AWS_SECRETS}"
    echo "    AWS secret mount directoriy: ${AWS_SECRETS_MOUNT}"
    echo "    AWS test data directoriy: ${AWS_TESTDATA}"
    echo "    AWS test data mount directoriy: ${AWS_TESTDATA_MOUNT}"
    echo "    SSH directoriy: ${SSH_DIRECTOY}"
    echo "    SSH mount directoriy: ${SSH_DIRECTOY_MOUNT}"

    echo "- User information:"
    echo "    Username: ${USERNAME}"
    echo "    User group: ${GROUPNAME}"
    echo "    User id: ${USERID}"
    echo "    Group id: ${GROUPID}"
    echo "    User directory: ${USERDIR}"

    echo "- Container information:"
    echo "    Image: nymea:${IMAGENAME}"
    echo "    Container: ${CONTAINERNAME}"

    echo "- Configuration:"
    echo "    Config directory: ${CONFIGDIR}"
    echo "    Config file: ${CONFIG}"

    echo "- Build information:"
    echo "    Commit hash: ${COMMITHASH}"
    echo "    Node version: ${NODE_VERSION}"
    echo "    Channel: ${CURRENT_CHANNEL}"
}

#------------------------------------------------------------------------------------------
verifyGitRepository() {
    # Verify we have a git repository
    if ! git status > /dev/null 2>&1 ; then
        printRed "Could not find any git repositor in this folder. Please run $(basename $0) in the source directory of a lambda function code."
        exit 1
    fi
}

#------------------------------------------------------------------------------------------
verifyCommandCount() {
    # Check if there is already a command specified
    if [ "${COMMAND}" != "" ]; then
        printRed "Multiple commands passed. Please pass only one command to ${APPLICATION}."
        #usage
        exit 1
    fi
}

#------------------------------------------------------------------------------------------
finish() {
    # Kill all child processes
    kill 0
}

#------------------------------------------------------------------------------------------
# Main
#------------------------------------------------------------------------------------------

# Clean up if the script exit
trap finish EXIT

initEnv

COMMAND=""

while [ "$1" != "" ]; do
    case $1 in
        shell )
            verifyCommandCount && COMMAND="enterShell";;
        clean )
            verifyCommandCount && COMMAND="cleanAll";;
        start )
            verifyCommandCount && COMMAND="startContainer";;
        stop )
            verifyCommandCount && COMMAND="stopContainer";;
        delete )
            verifyCommandCount && COMMAND="deleteContainer";;
        info )
            verifyCommandCount && COMMAND="printInfo";;
        deploy )
            verifyCommandCount && COMMAND="deploy";;
        deploy-production )
            verifyCommandCount && COMMAND="deployProduction";;
        help )
            verifyCommandCount && COMMAND="usage";;
        create-image )
            verifyCommandCount && COMMAND="create-image";;
        -t | --test-data )
            AWS_TESTDATA=$2
            shift;;
        -a | --aws-dir )
            AWS_SECRETS=$2
            shift;;
        -s | --ss-dir )
            SSH_DIRECTOY=$2
            shift;;
        -n | --node )
            NODE_VERSION=$2
            shift;;
        -n | --no-colors )
            COLORS=false;;
        -h | --help )
            usage && exit 0;;
        -v | --version )
            echo ${VERSION} && exit 0;;
        * )
            usage && exit 1;;
    esac
    shift
done

# Note: these commands should always work
if [ "${COMMAND}" == "create-image" ]; then createBaseImage; exit 0; fi
if [ "${COMMAND}" == "usage" ]; then usage; exit 0; fi

# Init configurations
verifyGitRepository
saveConfiguration
loadConfiguration

# Note: these commands should only work in a valid source directory
# Execute the command
if [ "${COMMAND}" == "enterShell" ]; then createContainer && enterShell; exit 0; fi
if [ "${COMMAND}" == "cleanAll" ]; then cleanAll; exit 0; fi
if [ "${COMMAND}" == "startContainer" ]; then startContainer; exit 0; fi
if [ "${COMMAND}" == "stopContainer" ]; then stopContainer; exit 0; fi
if [ "${COMMAND}" == "deleteContainer" ]; then deleteContainer; exit 0; fi
if [ "${COMMAND}" == "printInfo" ]; then printInfo; exit 0; fi

# If no command passed, just build and test local
printInfo
createContainer
cleanAll
build
testLocal

# Deploy commands
if [ "${COMMAND}" == "deploy" ]; then deploy; exit 0; fi
if [ "${COMMAND}" == "deployProduction" ]; then deployProduction; exit 0; fi


