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

echo "Preparing Kaleidoscope and the bundle..."

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

tar  -cf "${XFER_DIR}/kaleidoscope.tar"  \
	--exclude .arduino/data \
	--exclude bin/arduino-cli \
	--exclude .docker_xfer \
	--exclude .git \
	--exclude _build \
	--exclude testing/googletest/build  \
	.

echo "The bundle is coming from ${ARDUINO_DIRECTORIES_USER}/hardware/keyboardio"
(cd "${ARDUINO_DIRECTORIES_USER}/hardware/keyboardio" && tar  -cf "${XFER_DIR}/bundle.tar" \
	--exclude .git --exclude avr/libraries/Kaleidoscope .)

echo "Building the docker image..."
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 \
       --mount type=tmpfs,destination=/kaleidoscope:exec \
       --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/ \
       kaleidoscope/docker "$*"


exit 0