#!/bin/sh
# Run a command (default: make) for FJ1 user apps inside the Docker build environment.
# Usage: docker/fj1-sdk [command ...]   e.g. docker/fj1-sdk make -j4 install
set -eu

here=$(cd "$(dirname "$0")" && pwd -P)
root=$(cd "$here/.." && pwd -P)
image=${FJ1_SDK_IMAGE:-fj1-userapp-sdk:latest}

if [ "${FJ1_SDK_REBUILD:-0}" = 1 ] || ! docker image inspect "$image" >/dev/null 2>&1; then
	docker build --platform linux/amd64 -t "$image" "$here"
fi

cwd=$(pwd -P)
case "$cwd/" in
"$root"/*) workdir=$cwd ;;
*) workdir=$root ;;
esac

# The tree is mounted at the same absolute path so that symlinks pointing
# outside it (e.g. lib/lvgl in the source repository) still resolve.
mounts=""
for link in $(find "$root" -maxdepth 2 -type l -not -path '*/build/*'); do
	target=$(cd "$link" 2>/dev/null && pwd -P) || continue
	case "$target/" in
	"$root"/*) ;;
	*) mounts="$mounts $target" ;;
	esac
done

tty=""
if [ -t 0 ] && [ -t 1 ]; then
	tty="-it"
fi

[ $# -gt 0 ] || set -- make

if [ -n "${SIGNING_KEY:-}" ]; then
	key=$(realpath -- "$SIGNING_KEY")
	if [ ! -f "$key" ]; then
		echo "Signing key is not a regular file: $key" >&2
		exit 1
	fi
	set -- -e "SIGNING_KEY=$key" -v "$key:$key:ro" "$image" "$@"
else
	set -- "$image" "$@"
fi

# shellcheck disable=SC2086
exec docker run --rm $tty --platform linux/amd64 \
	-u "$(id -u):$(id -g)" -e HOME=/tmp \
	-v "$root:$root" \
	$(for m in $mounts; do printf ' -v %s:%s:ro' "$m" "$m"; done) \
	-w "$workdir" "$@"
