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

find_nix_bin() {
  local candidate
  for candidate in \
    "${NIX_BIN:-}" \
    "$(command -v nix 2>/dev/null || true)" \
    "${HOME:-}/.nix-profile/bin/nix" \
    "${HOME:-}/.local/state/nix/profile/bin/nix" \
    "/nix/var/nix/profiles/per-user/${USER:-runner}/profile/bin/nix" \
    /nix/var/nix/profiles/default/bin/nix \
    /run/current-system/sw/bin/nix \
    /etc/profiles/per-user/runner/bin/nix \
    /Users/runner/.nix-profile/bin/nix \
    /Users/runner/.local/state/nix/profile/bin/nix \
    /home/runner/.nix-profile/bin/nix \
    /home/runner/.local/state/nix/profile/bin/nix \
    /nix/profile/bin/nix; do
    if [[ -n "$candidate" && -x "$candidate" ]]; then
      printf '%s\n' "$candidate"
      return 0
    fi
  done

  candidate="$(
    find \
      "${HOME:-/nonexistent}" \
      /Users/runner \
      /home/runner \
      /nix/var/nix/profiles \
      /etc/profiles/per-user \
      -path '*/bin/nix' -type f 2>/dev/null | head -n 1 || true
  )"
  if [[ -n "$candidate" && -x "$candidate" ]]; then
    printf '%s\n' "$candidate"
    return 0
  fi

  return 1
}

if nix_bin="$(find_nix_bin)"; then
  printf '%s\n' "$nix_bin"
  exit 0
fi

if bash Scripts/ci/ensure-nix.sh >/dev/null 2>&1; then
  if nix_bin="$(find_nix_bin)"; then
    printf '%s\n' "$nix_bin"
    exit 0
  fi
fi

echo "::error ::nix is required but is not on PATH and no standard install path exists" >&2
exit 1
