#!/bin/bash

# This is the build script that can be executed within a Lambda build Docker container.
# Usage from host OS:
#
# docker run -it \
# --volume <repo home>:/reporoot <Lambda image> \
# /home/jenkins/build.sh \
# <environment> \
# /reporoot/<path to Lambda root in repo> \
# <Lambda dir name>
#
# This script and the Docker process will exit with code 0 upon successful installation
# of dependencies, packaging of function, and execution of unit tests.


export PROJECT_HOME="$1"
export LAMBDA_NAME="$2"

if [ -z "$PROJECT_HOME" -o -z "$LAMBDA_NAME"  ]
then
    echo "Please provide PROJECT_HOME, LAMBDA_NAME" >&2
    exit 1
fi

export VIRT_NAME="virt_env"
export LAMBDA_HOME="$PROJECT_HOME/$LAMBDA_NAME"
export VIRT_HOME="$PROJECT_HOME/$VIRT_NAME"
export DEPLOY_ZIP="$LAMBDA_HOME/deploy.zip"


rm -rf "./$VIRT_NAME"
# Clean up previous deploy file if existed.
rm "$DEPLOY_ZIP"

cd "$PROJECT_HOME" || exit 1
virtualenv "$VIRT_NAME" -p "$(which python3.6)"
source "$VIRT_HOME/bin/activate"
cd "$VIRT_HOME" || exit 1
pip install -r "$LAMBDA_HOME/requirements.txt"

# Zip up dependencies.
cd "$VIRT_HOME" || exit 1
cd "$VIRT_HOME/lib/python3.6/site-packages" || exit 1
zip -r "$DEPLOY_ZIP" *


# If available, zip up shared Lambda modules.
if [ -e "$LAMBDA_HOME/common" ]
then
    export PYTHONPATH="$PYTHONPATH:$LAMBDA_HOME/common"
    cd "$LAMBDA_HOME/common" || exit 1
    find . -name '*.py' | xargs zip "$DEPLOY_ZIP"
fi
cd
# Uninstall some packages that may conflict with those provided by Lambda runtime
deactivate

# Zip up Lambda function itself.
cd "$LAMBDA_HOME"
find . -name '*' | xargs zip "$DEPLOY_ZIP"

echo "Done!"


