#!/bin/sh
set -eu

usage() {
  cat <<'EOF'
Usage: scripts/build-sender-runtime-pack [options]

Build the external Tribes Sender runtime Guix pack from this checkout.

Options:
  --guix=PATH       Guix command to use (default: guix)
  --output=PATH     Copy resulting .tar.zst pack 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}
output=

for arg in "$@"; do
  case "$arg" in
    --guix=*)
      guix_bin=${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
}

pack_path=$("$guix_bin" pack \
  -L "$root_dir" \
  -f tarball \
  -C zstd \
  --save-provenance \
  -S /opt/tribes-sender-runtime/bin=bin \
  -S /opt/tribes-sender-runtime/sbin=sbin \
  -S /opt/tribes-sender-runtime/share=share \
  -m "$root_dir/manifests/packs/sender-runtime.scm" | tail -n 1)

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

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