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

command="${1:-}"

resolve_repo_root() {
  if [[ -n "${BUILD_WORKSPACE_DIRECTORY:-}" && -f "${BUILD_WORKSPACE_DIRECTORY}/MODULE.bazel" ]]; then
    printf '%s\n' "$BUILD_WORKSPACE_DIRECTORY"
    return 0
  fi

  local dir="$PWD"
  while [[ "$dir" != "/" ]]; do
    if [[ -f "$dir/MODULE.bazel" && -d "$dir/Apple" ]]; then
      printf '%s\n' "$dir"
      return 0
    fi
    dir="$(dirname "$dir")"
  done

  echo "unable to resolve Burrow repository root" >&2
  return 1
}

repo_root="$(resolve_repo_root)"
cd "$repo_root"

case "$command" in
  release-ios)
    Scripts/ci/package-apple-artifacts.sh ios
    ;;
  release-macos)
    Scripts/ci/package-apple-artifacts.sh macos
    ;;
  release-all)
    Scripts/ci/package-apple-artifacts.sh all
    ;;
  *)
    echo "unknown apple runner command: ${command}" >&2
    exit 64
    ;;
esac
