#!/usr/bin/env bash
# Runs dist.sh inside the local build-image container, mirroring what the
# Gitea Actions release workflow does — useful for testing build-image
# changes (or dist.sh/build_vice.sh/build_nibtools.sh changes) locally
# before pushing anything to cr.ladkau.de.
#
# Usage: ./run-image.sh [VERSION]
#   VERSION is passed through to dist.sh; omit it for dist.sh's own
#   git-tag-based default (see dist.sh's header comment).
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}"

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

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

VERSION="${1:-${VERSION:-}}"

echo "== Running dist.sh inside $IMAGE =="
docker run --rm \
    -v "$ROOT:/workspace" \
    -w /workspace \
    -e VERSION="$VERSION" \
    "$IMAGE" \
    bash -c 'git config --global --add safe.directory /workspace && ./dist.sh'

echo "== Done — artifacts in dist/ =="
ls -la "$ROOT/dist"
