#!/usr/bin/env bash
# Builds and pushes the release build environment image (build-image/Dockerfile)
# to the container registry. The Gitea Actions release workflow pulls this
# image to run dist.sh. Bump build-image/VERSION whenever the Dockerfile
# changes so the workflow can pin a stable tag.
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:?registry.env must set REGISTRY}"
: "${REGISTRY_IMAGE:?registry.env must set REGISTRY_IMAGE}"
: "${REGISTRY_USER:?registry.env must set REGISTRY_USER}"
: "${REGISTRY_PASSWORD:?registry.env must set REGISTRY_PASSWORD}"

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

echo "== Logging in to $REGISTRY =="
echo "$REGISTRY_PASSWORD" | docker login "$REGISTRY" -u "$REGISTRY_USER" --password-stdin

echo "== Building $REGISTRY_IMAGE:$VERSION =="
docker build \
    -t "$REGISTRY_IMAGE:$VERSION" \
    -t "$REGISTRY_IMAGE:latest" \
    -f "$ROOT/build-image/Dockerfile" \
    "$ROOT/build-image"

echo "== Pushing $REGISTRY_IMAGE:$VERSION and :latest =="
docker push "$REGISTRY_IMAGE:$VERSION"
docker push "$REGISTRY_IMAGE:latest"

echo "== Done =="
echo "Image: $REGISTRY_IMAGE:$VERSION"
