#!/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/Android" ]]; 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"

cargo_check_locked() {
  local -a cargo_path_prefixes
  local home_dir user_name
  cargo_path_prefixes=()
  home_dir="${HOME:-}"
  if [[ -n "$home_dir" ]]; then
    cargo_path_prefixes+=("$home_dir/.cargo/bin")
  fi
  user_name="$(id -un 2>/dev/null || true)"
  if [[ -n "$user_name" ]]; then
    cargo_path_prefixes+=(
      "/Users/${user_name}/.cargo/bin"
      "/home/${user_name}/.cargo/bin"
      "/etc/profiles/per-user/${user_name}/bin"
    )
  fi
  cargo_path_prefixes+=("/opt/homebrew/bin" "/usr/local/bin" "/nix/var/nix/profiles/default/bin" "/run/current-system/sw/bin")
  export PATH="$(IFS=:; printf '%s' "${cargo_path_prefixes[*]}"):$PATH"

  if command -v cargo >/dev/null 2>&1; then
    cargo check --locked -p burrow-mobile-ffi
    return
  fi

  if [[ "${BURROW_ANDROID_BAZEL_USE_NIX:-0}" == "1" ]] && command -v nix >/dev/null 2>&1; then
    nix develop .#ci -c cargo check --locked -p burrow-mobile-ffi
    return
  fi

  echo "cargo or nix is required to check the Android Rust core stub" >&2
  exit 127
}

case "$command" in
  check-stub)
    test -f Android/settings.gradle.kts
    test -f Android/app/src/main/java/net/burrow/android/MainActivity.kt
    test -f crates/burrow-core/src/lib.rs
    test -f crates/burrow-mobile-ffi/src/lib.rs
    cargo_check_locked
    ;;
  *)
    echo "unknown Android runner command: ${command}" >&2
    exit 64
    ;;
esac
