#!/bin/bash

# This is the script for run common directory unit tests.
# Usage from host OS:
#
# docker run -it \
# --volume <repo home>:/reporoot <Lambda image> \
# /home/jenkins/common-module-tests.sh \
# <LAMBDAS_HOME>
#
#
# This script and the Docker process will exit with code 0 upon successful
# of dependencies and execution of unit tests.


export LAMBDAS_HOME="$1"

if [ -z "$LAMBDAS_HOME" ]
then
    echo "Please provide lambda home dir." >&2
    exit 1
fi

if [ -e "$LAMBDAS_HOME/common" ]
then
    export VIRT_NAME="virt_common"
    export VIRT_HOME="/home/jenkins/$VIRT_NAME"

    rm -rf "./$VIRT_NAME"
    cd "/home/jenkins" || exit 1
    virtualenv "$VIRT_NAME" -p "$(which python3)"
    source "$VIRT_HOME/bin/activate"

    cd "$LAMBDAS_HOME/common"

    if [ -f "$LAMBDAS_HOME/common/requirements.txt" ]
    then
        pip install -r "$LAMBDAS_HOME/common/requirements.txt"
    fi
    pip install -r "$LAMBDAS_HOME/common/requirements-dev.txt"
    python -m pytest tests/

    TEST_COMMON_EXIT_CODE="0"
    # We need to ignore import order, because flake8 treats modules imported from
    # 'common' as external packages.
    # flake8 --ignore=I100
    # LINT_COMMON_EXIT_CODE="$?"
    cd "$LAMBDAS_HOME" || exit 1
    deactivate
    exit $[ $TEST_COMMON_EXIT_CODE + $LINT_COMMON_EXIT_CODE ]
else
    echo "'common' directory not found in the lambdas home directory: '$LAMBDAS_HOME'" >&2
    exit 0
fi
