#!/bin/sh
set -eu

usage() {
  cat <<'EOF'
Usage: scripts/build-tribes-docker-image [options]

Build the pinned debug Tribes Docker image from this guix-tribes checkout.

Options:
  --guix=PATH          Guix command to use (default: guix)
  --image-tag=TAG     Docker image tag (default: tribes-guix-debug:latest)
  --output=PATH       Copy resulting image tarball to PATH
  -h, --help          Show this help
EOF
}

script_dir=$(CDPATH= cd -- "$(dirname "$0")" && pwd)
root_dir=$(CDPATH= cd -- "$script_dir/.." && pwd)
guix_bin=${GUIX:-guix}
image_tag=tribes-guix-debug:latest
output=

for arg in "$@"; do
  case "$arg" in
    --guix=*)
      guix_bin=${arg#*=}
      ;;
    --image-tag=*)
      image_tag=${arg#*=}
      ;;
    --output=*)
      output=${arg#*=}
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "unknown argument: $arg" >&2
      usage >&2
      exit 2
      ;;
  esac
done

command -v "$guix_bin" >/dev/null 2>&1 || {
  echo "guix command not found: $guix_bin" >&2
  exit 1
}

image_path=$("$guix_bin" pack \
  -L "$root_dir" \
  -f docker \
  --image-tag="$image_tag" \
  -S /bin=bin \
  --entry-point=/bin/tribes \
  -e '(@ (tribes packages docker) tribes-debug-docker-package)' | tail -n 1)

case "$image_path" in
  /gnu/store/*) ;;
  *)
    echo "guix pack did not produce a /gnu/store path: ${image_path:-<empty>}" >&2
    exit 1
    ;;
esac

if [ -n "$output" ]; then
  cp "$image_path" "$output"
  printf '%s\n' "$output"
else
  printf '%s\n' "$image_path"
fi
