#! /bin/bash

set -xe

# Save the dir from which the script was called
ORG_DIR=$(pwd)

# Find cctools src directory
CCTOOLS_SRC="$(cd "$(dirname "${BASH_SOURCE[0]}")"/../.. && pwd)"

# Ensure we end up in the directory we started regardless of how the script
# ends.
function finish {
    cd ${ORG_DIR}
}
trap finish EXIT


cd ${CCTOOLS_SRC}

# disable perl bindings (to compile as we do in conda)
perl_option='--with-perl-path no'

if [[ -n "${CCTOOLS_DOCKER_GITHUB}" ]]
then
    # ensure both python2 and python3 are built for centos7
    python_option='--with-python3-path /usr'
    if [[ "${CCTOOLS_DOCKER_GITHUB}" = centos7 ]]
    then
        python_option='--with-python2-path /usr --with-python3-path /usr'
    fi
fi

# if we are not in a docker container but the base VM,
# then pip is available so install python packages
if [[ -z "${CCTOOLS_DOCKER_GITHUB}" ]]
then
    pip install cloudpickle packaging conda-pack
fi

# compile everything
./configure --strict $DEP_ARGS ${perl_option} ${python_option} ${cvmfs_option} "$@"
[[ -f config.mk ]] && make clean
echo === Contents of config.mk ===
cat config.mk

make

if [[ "${STATIC_WORKER}" = 1 ]]
then
    # set the static binaries for test and installation
    mv work_queue_{worker,status,example} work_queue/src
    touch work_queue/src/work_queue_{worker,status,example}
fi

make install

if ! make test
then
    echo === Contents of cctools.test.fail ===
    cat cctools.test.fail
    exit 1
else
    exit 0
fi


