#!/usr/bin/env bash
# Runs the build-image against the repo to compile engine/ (the vendored
# Shockolate snapshot), entirely offline - every dependency it needs
# (SDL2, SDL2_mixer, fluidsynth-lite, a MIDI soundfont) was already built
# into the image by ./build-image.sh.
#
# Output lands in engine/.build-output/ - run `make dist` afterwards to
# assemble it (together with the game assets from res/assets/ss_ee/) into
# dist/.
#
# Usage: ./run-image.sh [command...]
#   With no arguments, runs the engine build. Pass a command (e.g. `bash`)
#   to get a shell in the build environment instead, useful for debugging
#   a failed build.
set -euo pipefail

cd "$(dirname "${BASH_SOURCE[0]}")"
ROOT="$(pwd)"

fail() { echo "PREFLIGHT FAIL: $*" >&2; exit 1; }

command -v docker >/dev/null 2>&1 \
    || fail "docker not found in PATH"

IMAGE="${REGISTRY_IMAGE:-questshock/builder}"
if [ -f "$ROOT/registry.env" ]; then
    # shellcheck disable=SC1091
    source "$ROOT/registry.env"
    IMAGE="${REGISTRY_IMAGE:-$IMAGE}"
fi

IMAGE_TAG="$(<"$ROOT/build-image/VERSION")"
[ -n "$IMAGE_TAG" ] || fail "build-image/VERSION is empty"
IMAGE="$IMAGE:$IMAGE_TAG"

docker image inspect "$IMAGE" >/dev/null 2>&1 \
    || fail "$IMAGE not found locally - run ./build-image.sh first"

TTY_FLAGS="-i"
[ -t 1 ] && TTY_FLAGS="-it"

# HOST_REPO_ROOT: lets scripts running in the container (e.g.
# build-image/prepare-android-project.sh --host-paths) write paths that
# resolve on the HOST filesystem instead of this container's own
# /workspace - needed so a gradlew/Android Studio running natively on the
# host afterwards can find them.
# shellcheck disable=SC2086
docker run --rm $TTY_FLAGS \
    -v "$ROOT:/workspace" \
    -e HOST_UID="$(id -u)" \
    -e HOST_GID="$(id -g)" \
    -e HOST_REPO_ROOT="$ROOT" \
    "$IMAGE" \
    "$@"

if [ "$#" -eq 0 ]; then
    echo
    echo "This only compiled the engine (engine/.build-output/) - it does not"
    echo "create dist/ by itself. Run 'make dist' next to assemble a runnable"
    echo "copy (or 'make package' for a redistributable tarball)."
fi
