#!/usr/bin/env bash
# Builds the release build environment image (build-image/Dockerfile)
# locally, tagged with build-image/VERSION and :latest. Does not push —
# test it with ./run-image.sh first, then publish with ./upload-image.sh.
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"

[ -f "$ROOT/registry.env" ] \
    || fail "registry.env not found — copy registry.env.example to registry.env and fill in your cr.ladkau.de credentials"

# shellcheck disable=SC1091
source "$ROOT/registry.env"

: "${REGISTRY_IMAGE:?registry.env must set REGISTRY_IMAGE}"

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

echo "== Building $REGISTRY_IMAGE:$VERSION =="
# Context is the repo root (not build-image/) so the Dockerfile's
# gradle-cache-warm stage can COPY in the companion app's real Gradle
# project files — see .dockerignore for what's excluded from that context.
docker build \
    -t "$REGISTRY_IMAGE:$VERSION" \
    -t "$REGISTRY_IMAGE:latest" \
    -f "$ROOT/build-image/Dockerfile" \
    "$ROOT"

echo "== Done =="
echo "Image: $REGISTRY_IMAGE:$VERSION (and :latest)"
echo "Test it with ./run-image.sh, then publish with ./upload-image.sh"
