#!/usr/bin/env bash
# nerf-az-repos-pr-comments -- List all comment threads on a pull request as JSON. Project and repository are auto-detected from the git remote (origin) in the current directory; pass -C <directory> to read the remote from a different repo under the workspace, or --project to override just the project (the repository is always taken from the remote URL).
# Generated from az-repos manifest. Do not edit directly.
# nerf:threat:read=remote
# nerf:threat:write=none

if [[ "${BASH_VERSINFO[0]:-0}" -lt 4 ]]; then
  echo "error: nerf-az-repos-pr-comments requires bash 4+. Found bash ${BASH_VERSION:-unknown}" >&2
  echo "  hint: on macOS, install a newer bash via 'brew install bash'" >&2
  exit 1
fi

set -euo pipefail

_NERF_DRY_RUN=""

usage() {
  cat >&2 <<'EOF'
Usage: nerf-az-repos-pr-comments [--project|-p <project>] [-C <directory>] <pr_id>

Options:
  --project, -p <project>
      Azure DevOps project name or ID (overrides auto-detection from the origin remote)
  -C <directory>
      Read the origin remote from this directory instead of cwd (must be under cwd)

Arguments:
  <pr_id> (required)
      Pull request ID (numeric)
      Must match: ^[0-9]+$

List all comment threads on a pull request as JSON. Project and repository are auto-detected from the git remote (origin) in the current directory; pass -C <directory> to read the remote from a different repo under the workspace, or --project to override just the project (the repository is always taken from the remote URL).
EOF
  exit 1
}

PROJECT=""
_PROJECT_SET=""
DIRECTORY=""
_DIRECTORY_SET=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --project|-p) if [[ -n "${_PROJECT_SET}" ]]; then echo "error: --project can only be specified once" >&2; exit 1; fi; PROJECT="$2"; _PROJECT_SET=true; shift 2 ;;
    -C) if [[ -n "${_DIRECTORY_SET}" ]]; then echo "error: -C can only be specified once" >&2; exit 1; fi; DIRECTORY="$2"; _DIRECTORY_SET=true; shift 2 ;;
    --nerf-dry-run) _NERF_DRY_RUN="true"; shift 1 ;;
    -h|--help) usage ;;
    --) shift; break ;;
    *) break ;;
  esac
done

_PR_ID_SET=""
if [[ $# -gt 0 ]]; then
  PR_ID="$1"
  _PR_ID_SET=true
  shift
else
  PR_ID=""
fi
if [[ $# -gt 0 ]]; then
  echo "error: nerf-az-repos-pr-comments: unexpected extra arguments: $*" >&2
  echo "  hint: switches and options must come before positional arguments" >&2
  exit 1
fi

_nerf_check_path() {
  local _label=$1 _input=$2 _tests=$3
  local _cwd _canonical
  case "$_input" in
    *$'\n'*|*$'\r'*|*$'\t'*)
      echo "error: nerf-az-repos-pr-comments: ${_label}: contains illegal control character" >&2
      echo "  hint: paths must not contain newlines, carriage returns, or tabs" >&2
      return 1 ;;
  esac
  _cwd=$(realpath -- "$PWD") || {
    echo "error: nerf-az-repos-pr-comments: failed to canonicalize cwd '$PWD'" >&2
    echo "  hint: invoke from a valid directory" >&2
    return 1
  }
  _canonical=$(realpath -m -- "$_input") || {
    echo "error: nerf-az-repos-pr-comments: ${_label}: failed to canonicalize '${_input}'" >&2
    echo "  hint: pass a syntactically valid path" >&2
    return 1
  }
  if [[ ",$_tests," == *",under_cwd,"* ]]; then
    # Skip the prefix check when cwd is root: every absolute path qualifies, and the
    # naive prefix comparison would build "//" and reject otherwise-valid paths.
    if [[ "$_cwd" != "/" && "$_canonical" != "$_cwd" && "$_canonical" != "$_cwd"/* ]]; then
      echo "error: nerf-az-repos-pr-comments: ${_label}: 'under_cwd' failed: '${_input}'" >&2
      echo "  resolves to '${_canonical}', not under '${_cwd}'" >&2
      echo "  hint: pass a path inside the current workspace" >&2
      echo "  hint: symlinks are followed -- if the link's target is outside the workspace it is rejected" >&2
      return 1
    fi
  fi
  if [[ ",$_tests," == *",exists,"* ]] && [[ ! -e "$_input" ]]; then
    echo "error: nerf-az-repos-pr-comments: ${_label}: 'exists' failed: '${_input}' does not exist" >&2
    echo "  hint: create the path or pass an existing one" >&2
    return 1
  fi
  if [[ ",$_tests," == *",not_exists,"* ]] && [[ -e "$_input" ]]; then
    echo "error: nerf-az-repos-pr-comments: ${_label}: 'not_exists' failed: '${_input}' already exists" >&2
    echo "  hint: choose a different path or remove the existing one first" >&2
    return 1
  fi
  if [[ ",$_tests," == *",file,"* ]] && [[ ! -f "$_input" ]]; then
    echo "error: nerf-az-repos-pr-comments: ${_label}: 'file' failed: '${_input}' is not a regular file" >&2
    echo "  hint: pass a regular file path (not a directory, symlink-to-dir, device, or missing path)" >&2
    return 1
  fi
  if [[ ",$_tests," == *",dir,"* ]] && [[ ! -d "$_input" ]]; then
    echo "error: nerf-az-repos-pr-comments: ${_label}: 'dir' failed: '${_input}' is not a directory" >&2
    echo "  hint: pass a directory path (not a regular file or missing path)" >&2
    return 1
  fi
  if [[ ",$_tests," == *",symlink,"* ]] && [[ ! -L "$_input" ]]; then
    echo "error: nerf-az-repos-pr-comments: ${_label}: 'symlink' failed: '${_input}' is not a symlink" >&2
    echo "  hint: pass a symbolic link (the test does not follow the link)" >&2
    return 1
  fi
  if [[ ",$_tests," == *",not_symlink,"* ]] && [[ -L "$_input" ]]; then
    echo "error: nerf-az-repos-pr-comments: ${_label}: 'not_symlink' failed: '${_input}' is a symlink" >&2
    echo "  hint: pass a real path, not a symlink (the test does not follow the link)" >&2
    return 1
  fi
  if [[ ",$_tests," == *",readable,"* ]] && [[ ! -r "$_input" ]]; then
    echo "error: nerf-az-repos-pr-comments: ${_label}: 'readable' failed: '${_input}' is not readable" >&2
    echo "  hint: check filesystem permissions for the current user" >&2
    return 1
  fi
  if [[ ",$_tests," == *",writable,"* ]] && [[ ! -w "$_input" ]]; then
    echo "error: nerf-az-repos-pr-comments: ${_label}: 'writable' failed: '${_input}' is not writable" >&2
    echo "  hint: check filesystem permissions for the current user" >&2
    return 1
  fi
  if [[ ",$_tests," == *",executable,"* ]] && [[ ! -x "$_input" ]]; then
    echo "error: nerf-az-repos-pr-comments: ${_label}: 'executable' failed: '${_input}' is not executable" >&2
    echo "  hint: check filesystem permissions for the current user" >&2
    return 1
  fi
}

if [[ -n "${_DIRECTORY_SET}" ]]; then
  _nerf_check_path 'option -C' "${DIRECTORY}" 'under_cwd' || exit 1
fi

if [[ -n "${_PR_ID_SET}" ]] && [[ "${PR_ID}" == -* ]]; then
  echo "error: nerf-az-repos-pr-comments: <pr_id> cannot start with '-'" >&2
  echo "  hint: use -- before positional arguments if needed" >&2
  exit 1
fi

if [[ -z "${PR_ID}" ]]; then
  echo "error: nerf-az-repos-pr-comments: missing required argument <pr_id>" >&2
  echo "  hint: provide a value for <pr_id>" >&2
  usage
fi

_NERF_PATTERN='^[0-9]+$'
if [[ -n "${_PR_ID_SET}" ]] && ! [[ "${PR_ID}" =~ $_NERF_PATTERN ]]; then
  echo "error: nerf-az-repos-pr-comments: argument <pr_id> does not match required pattern" >&2
  echo "  value:   \"${PR_ID}\"" >&2
  echo "  pattern: ^[0-9]+$" >&2
  echo "  hint: value must match ^[0-9]+$" >&2
  exit 1
fi

_nerf_pre() {
  if [[ -n "${_DIRECTORY_SET}" ]]; then _GIT_DIR="${DIRECTORY}"; else _GIT_DIR="."; fi
  REMOTE_URL=$(git -C "${_GIT_DIR}" remote get-url origin 2>/dev/null || true)
  if [ -z "$REMOTE_URL" ]; then
    echo "error: could not detect git remote 'origin' in '${_GIT_DIR}'" >&2
    return 1
  fi
  # Extract project and repo from Azure DevOps remote URL. Three shapes are supported:
  #   HTTPS (modern):  https://dev.azure.com/{org}/{project}/_git/{repo}
  #   HTTPS (legacy):  https://{org}.visualstudio.com/[DefaultCollection/]{project}/_git/{repo}
  #   SSH:             git@ssh.dev.azure.com:v3/{org}/{project}/{repo}
  DETECTED_PROJECT=$(echo "$REMOTE_URL" | sed -nE '
    s|.*dev\.azure\.com/[^/]+/([^/]+)/_git/.*|\1|p
    s|.*://[^/]*visualstudio\.com/(DefaultCollection/)?([^/]+)/_git/.*|\2|p
    s|.*:v3/[^/]+/([^/]+)/.*|\1|p')
  DETECTED_PROJECT="${DETECTED_PROJECT//%20/ }"
  if echo "$REMOTE_URL" | grep -q '/_git/'; then
    REPO_NAME=$(echo "$REMOTE_URL" | sed -E 's|.*/_git/([^?/]+).*|\1|; s|\.git$||')
  elif echo "$REMOTE_URL" | grep -q ':v3/'; then
    REPO_NAME=$(echo "$REMOTE_URL" | sed -E 's|.*:v3/[^/]+/[^/]+/([^/]+).*|\1|; s|\.git$||')
  else
    echo "error: unrecognized Azure DevOps remote URL format: '$REMOTE_URL'" >&2
    return 1
  fi
  REPO_NAME="${REPO_NAME//%20/ }"
  # User-supplied --project overrides the auto-detected project (use the
  # _PROJECT_SET sentinel so '--project ""' is respected as-set, not
  # silently overwritten); repo is always taken from origin.
  if [[ -z "${_PROJECT_SET}" ]]; then
    PROJECT="$DETECTED_PROJECT"
    _PROJECT_SET=true
  fi
  if [ -z "$PROJECT" ] || [ -z "$REPO_NAME" ]; then
    echo "error: could not extract project/repo from remote URL '$REMOTE_URL'" >&2
    return 1
  fi
}

_nerf_pre_rc=0
_nerf_pre || _nerf_pre_rc=$?
if [ $_nerf_pre_rc -ne 0 ]; then
  echo "error: nerf-az-repos-pr-comments: pre-hook failed (exit code $_nerf_pre_rc)" >&2
  exit $_nerf_pre_rc
fi

if [[ "$_NERF_DRY_RUN" == "true" ]]; then
  echo "dry-run: nerf-az-repos-pr-comments would run inline script"
  exit 0
fi

exec az devops invoke \
  --area git \
  --resource pullRequestThreads \
  --route-parameters "project=$PROJECT" "repositoryId=$REPO_NAME" "pullRequestId=$PR_ID" \
  --output json
