#!/usr/bin/env bash
# Build (and optionally push) the CI builder images.
#
#   scripts/build-builder-image.sh                 # build both, no push
#   scripts/build-builder-image.sh --push          # build both and push
#   scripts/build-builder-image.sh --only arch     # just the Arch image
#   scripts/build-builder-image.sh --only main     # just the Ubuntu image
#
# Two images, because the jobs genuinely need different distributions:
#   main — Ubuntu: tests, Linux desktop bundle, Android APK (Dockerfile.builder)
#   arch — Arch:   the .pkg.tar.zst, which needs makepkg (Dockerfile.arch)
#
# The workflows in .gitea/workflows pin these by tag, so a change to either
# Dockerfile only reaches CI once this has run with --push.
set -euo pipefail

REGISTRY="${REGISTRY:-gitea.tourolle.paris}"
NAMESPACE="${NAMESPACE:-$REGISTRY/dtourolle}"
TAG="${TAG:-latest}"

PUSH=0
ONLY=both
while [ $# -gt 0 ]; do
  case "$1" in
    --push) PUSH=1 ;;
    --only) shift; ONLY="${1:-}" ;;
    -h|--help) sed -n '2,16p' "${BASH_SOURCE[0]}"; exit 0 ;;
    *) echo "❌ Unknown option: $1 (try --help)" >&2; exit 2 ;;
  esac
  shift
done

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

build_one() {
  local dockerfile="$1" image="$NAMESPACE/$2:$TAG"
  echo "🐳 Building $image from $dockerfile"
  docker build -f "$dockerfile" -t "$image" .
  if [ "$PUSH" = 1 ]; then
    echo "⬆️  Pushing $image"
    docker push "$image"
  fi
}

case "$ONLY" in
  main) build_one Dockerfile.builder bikecontrol-builder ;;
  arch) build_one Dockerfile.arch bikecontrol-arch-builder ;;
  both)
    build_one Dockerfile.builder bikecontrol-builder
    build_one Dockerfile.arch bikecontrol-arch-builder
    ;;
  *) echo "❌ --only takes main, arch or both" >&2; exit 2 ;;
esac

[ "$PUSH" = 1 ] || echo "ℹ️  Not pushed. Re-run with --push when you are happy with it."
