#! /bin/sh
## -*- mode: sh -*-
set -e

uname_S=$(uname -s 2>/dev/null || echo not)

# If we're running in a terminal and want interactive docker
# Specifically "is there a STDIN file descriptor"
if [ -t 0 ]; then
    : "${DOCKER_RUN_INTERACTIVE_OPTS:=--tty --interactive}"
fi



if [ "${uname_S}" = "Darwin" ]; then
    # This stops macos from copying resource forks into thigns like tar
    export COPYFILE_DISABLE=true
else
    ARDUINO_LOCAL_LIB_PATH="${ARDUINO_LOCAL_LIB_PATH:-${HOME}/Arduino}"
fi


if [ ! -d ./.arduino/user/hardware ]; then
	echo "Running tests in Docker requires that your Arduino environment be installed in .arduino inside the top-level Kaleidoscope directory. To set this up, run 'make setup'"
  exit 1
fi



XFER_DIR="$(pwd)/.docker_xfer"
mkdir -p "${XFER_DIR}"

if [ -z "$_NO_SYNC_KALEIDOSCOPE" ]; then 

echo "Preparing Kaleidoscope..."


echo "The bundle is coming from ${ARDUINO_DIRECTORIES_USER}/hardware/keyboardio"
tar  -cf "${XFER_DIR}/kaleidoscope.tar"  \
	--exclude .arduino/data \
	--exclude .arduino/downloads \
	--exclude .arduino/user/hardware/keyboardio/avr/libraries/Kaleidoscope \
	--exclude .arduino/user/hardware/keyboardio/gd32/libraries/Kaleidoscope \
	--exclude bin/arduino-cli \
	--exclude .docker_xfer \
	--exclude .git \
	--exclude _build \
	--exclude testing/googletest/build  \
	.

fi

if [ -z "$DOCKER_LIVE_KALEIDOSCOPE_DIR" ]; then 
	_KALEIDOSCOPE_MOUNT="--mount type=tmpfs,destination=/kaleidoscope:exec"
else
	echo "Kaleidoscope is mounted read/write inside docker"
	_KALEIDOSCOPE_MOUNT="-v $(pwd):/kaleidoscope:"
fi


echo "Building the docker image. This could take a few minutes."
docker build -q -t kaleidoscope/docker etc
# We do want word splitting since there are multiple options here
# shellcheck disable=SC2086   
docker run --rm $DOCKER_RUN_INTERACTIVE_OPTS \
       ${_KALEIDOSCOPE_MOUNT} \
       --mount type=bind,source="${XFER_DIR}",destination=/kaleidoscope-src,consistency=delegated,readonly \
       --mount type=volume,source=kaleidoscope-persist,destination=/kaleidoscope-persist,consistency=delegated \
       --mount type=volume,source=kaleidoscope-googletest-build,destination=/kaleidoscope/testing/googletest/build,consistency=delegated \
       --mount type=volume,source=kaleidoscope-build,destination=/kaleidoscope/_build,consistency=delegated \
       --env ARDUINO_DIRECTORIES_DATA=/arduino-cli/data \
       --env ARDUINO_DIRECTORIES_USER=/kaleidoscope/.arduino/user/ \
       --env _NO_SYNC_KALEIDOSCOPE=${_NO_SYNC_KALEIDOSCOPE} \
       kaleidoscope/docker "$*"


exit 0