#!/usr/bin/env bash

# NOTE: This script has been slightly adopted to suite the Apache Arrow / crossbow CI
# 	setup. The next time this is updated to the current version on conda-forge,
#       you will also make this additions afterwards.

# PLEASE NOTE: This script has been automatically generated by conda-smithy. Any changes here
# will be lost next time ``conda smithy rerender`` is run. If you would like to make permanent
# changes to this script, consider a proposal to conda-smithy so that other feedstocks can also
# benefit from the improvement.

set -xeo pipefail

build_dir=${1}

THISDIR="$( cd "$( dirname "$0" )" >/dev/null && pwd )"
ARROW_ROOT=$(cd "$THISDIR/../../.."; pwd;)
FEEDSTOCK_ROOT=$THISDIR

docker info

# In order for the conda-build process in the container to write to the mounted
# volumes, we need to run with the same id as the host machine, which is
# normally the owner of the mounted volumes, or at least has write permission
export HOST_USER_ID=$(id -u)
# Check if docker-machine is being used (normally on OSX) and get the uid from
# the VM
if hash docker-machine 2> /dev/null && docker-machine active > /dev/null; then
    export HOST_USER_ID=$(docker-machine ssh $(docker-machine active) id -u)
fi

if [ -z "$CONFIG" ]; then
    set +x
    FILES=`ls .ci_support/linux_*`
    CONFIGS=""
    for file in $FILES; do
        CONFIGS="${CONFIGS}'${file:12:-5}' or ";
    done
    echo "Need to set CONFIG env variable. Value can be one of ${CONFIGS:0:-4}"
    exit 1
fi

if [ -z "${DOCKER_IMAGE}" ]; then
    SHYAML_INSTALLED="$(shyaml -h || echo NO)"
    if [ "${SHYAML_INSTALLED}" == "NO" ]; then
        echo "WARNING: DOCKER_IMAGE variable not set and shyaml not installed. Falling back to condaforge/linux-anvil-comp7"
        DOCKER_IMAGE="condaforge/linux-anvil-comp7"
    else
        DOCKER_IMAGE="$(cat "${FEEDSTOCK_ROOT}/.ci_support/${CONFIG}.yaml" | shyaml get-value docker_image.0 condaforge/linux-anvil-comp7 )"
    fi
fi

mkdir -p "${build_dir}"
DONE_CANARY="${build_dir}/conda-forge-build-done-${CONFIG}"
rm -f "$DONE_CANARY"

if [ -z "${CI}" ]; then
    DOCKER_RUN_ARGS="-it "
fi

export UPLOAD_PACKAGES="${UPLOAD_PACKAGES:-True}"
docker run ${DOCKER_RUN_ARGS} \
           --shm-size=2G \
           -v "${ARROW_ROOT}":/arrow:rw,z \
           -v "${build_dir}":/build:rw \
           -e FEEDSTOCK_ROOT="/arrow/dev/tasks/conda-recipes" \
           -e CONFIG \
           -e R_CONFIG \
           -e HOST_USER_ID \
           -e UPLOAD_PACKAGES \
           -e ARROW_VERSION \
           -e CI \
           $DOCKER_IMAGE \
           bash /arrow/dev/tasks/conda-recipes/build_steps.sh /build

# verify that the end of the script was reached
test -f "$DONE_CANARY"
