#! /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


# dependencies to be included statically in parrot live in /opt/vc3 in the
# container images.
DEPS_DIR=/opt/vc3/cctools-deps
DEPS=$(/bin/ls "$DEPS_DIR" || true)
DEP_ARGS=""
for dep in $DEPS; do
    DEP_ARGS="$DEP_ARGS --with-$dep-path $DEPS_DIR/$dep"
done

cd ${CCTOOLS_SRC}

if [[ -d /opt/vc3/cctools-deps ]]
then
    # compile work_queue binaries statically
    [[ -f config.mk ]] && make clean
    CFLAGS=-D__MUSL__ CC=/opt/vc3/cctools-deps/musl/bin/musl-gcc LD=/opt/vc3/cctools-deps/musl/bin/musl-gcc ./configure --without-system-{doc,apps,chirp} --with-readline-path=no --static  --with-zlib-path=/opt/vc3/cctools-deps/musl-zlib "$@"
    (cd dttools/src && make)
    (cd work_queue/src && make)
    (cp work_queue/src/work_queue_{worker,status,example} .)
    STATIC_WORKER=1
fi

# disable perl bindings in osx (to compile as we do in conda)
perl_option=''
if [[ "${TRAVIS_OS_NAME}" = osx ]]
then
    perl_option='--with-perl-path no'
fi

# compile everything
./configure --debug --strict $DEP_ARGS ${perl_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


