#!/usr/bin/env bash
set -euo pipefail

die() { echo "ERROR: $*" >&2; exit 1; }

# Resolve script path robustly (handles symlinks)
SCRIPT_PATH="$(readlink -f "$0" 2>/dev/null || realpath "$0" 2>/dev/null || echo "$0")"
SCRIPT_DIR="$(cd "$(dirname "$SCRIPT_PATH")" && pwd -P)"

# ----------------------------------------------------------------------
# Ensure script is invoked from FreeBASIC repo root
# ----------------------------------------------------------------------

# Script must live at: <root>/contrib/debian/make_all_debs.sh
if [ "$(basename "$SCRIPT_DIR")" != "debian" ] || [ "$(basename "$(dirname "$SCRIPT_DIR")")" != "contrib" ]; then
  die "this script must be located at ./contrib/debian/make_all_debs.sh"
fi

# Must be run from repo root
if [ ! -f "./makefile" ] || [ ! -d "./src" ] || [ ! -d "./contrib/debian" ]; then
  die "invoke this file from the FreeBASIC root by running ./contrib/debian/make_all_debs.sh"
fi

# ----------------------------------------------------------------------

# We are in repo root, but scripts live in contrib/debian
WORKDIR="$(pwd -P)"
DEBIAN_DIR="$WORKDIR/contrib/debian"

if [ ! -f "$DEBIAN_DIR/makedeb.sh" ]; then
  die "makedeb.sh not found at ./contrib/debian/makedeb.sh"
fi

chmod +x "$DEBIAN_DIR/makedeb.sh"

DISTROS=(
  "ubuntu:22.04:jammy"
  "ubuntu:24.04:noble"
  "ubuntu:25.04:plucky"
  "ubuntu:25.10:questing"

  "debian:11:bullseye"
  "debian:12:bookworm"
  "debian:13:trixie"
  "debian:sid:sid"
)

OUTDIR="$WORKDIR/packages"
mkdir -p "$OUTDIR"

echo "==> FreeBASIC multi-distro build starting..."
echo "==> Repo root: $WORKDIR"
echo "==> Script dir: $SCRIPT_DIR"
echo "==> Output dir: $OUTDIR"
echo

for entry in "${DISTROS[@]}"; do
  IMAGE="${entry%%:*}"
  REST="${entry#*:}"
  TAG="${REST%%:*}"
  CODENAME="${entry##*:}"

  echo "============================================================"
  echo "==> Building for: $CODENAME"
  echo "==> Docker image: $IMAGE:$TAG"
  echo "============================================================"
  echo

  mkdir -p "$OUTDIR/$CODENAME"

  docker pull "$IMAGE:$TAG"

  docker run --rm \
    -v "$WORKDIR:/work" \
    -v "$OUTDIR:/out" \
    -w /work \
    "$IMAGE:$TAG" \
    bash -lc "./contrib/debian/makedeb.sh" \
    2>&1 | tee "$OUTDIR/$CODENAME/docker_build.log"

  echo
  echo "==> Finished build for $CODENAME"
  echo
done

echo "============================================================"
echo "==> ALL BUILDS COMPLETE"
echo "============================================================"
echo
echo "Output packages stored in:"
echo "  $OUTDIR/"
echo
