#!/usr/bin/env bash
# nerf-az-boards-mywi-update -- Update state or title on a work item assigned to you. Verifies that System.AssignedTo matches the current user; refuses items assigned to anyone else (use az-boards-wi-update for those). To reassign, use az-boards-wi-update.
# Generated from az-boards manifest. Do not edit directly.
# nerf:threat:read=remote
# nerf:threat:write=remote

if [[ "${BASH_VERSINFO[0]:-0}" -lt 4 ]]; then
  echo "error: nerf-az-boards-mywi-update 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-boards-mywi-update [--state <state>] [--title <title>] [--project|-p <project>] [-C <directory>] <wi_id>

Options:
  --state <state>
      New work item state (e.g. Active, Resolved, Closed)
  --title <title>
      New work item title
  --project, -p <project>
      Azure DevOps project name or ID (auto-detected from the git remote if omitted)
  -C <directory>
      Resolve the Azure DevOps project from the git remote of this directory instead of cwd (must be under cwd)

Arguments:
  <wi_id> (required)
      Work item ID (numeric, must be assigned to you)
      Must match: ^[0-9]+$

Update state or title on a work item assigned to you. Verifies that System.AssignedTo matches the current user; refuses items assigned to anyone else (use az-boards-wi-update for those). To reassign, use az-boards-wi-update.
EOF
  exit 1
}

STATE=""
_STATE_SET=""
TITLE=""
_TITLE_SET=""
PROJECT=""
_PROJECT_SET=""
DIRECTORY=""
_DIRECTORY_SET=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    --state) if [[ -n "${_STATE_SET}" ]]; then echo "error: --state can only be specified once" >&2; exit 1; fi; STATE="$2"; _STATE_SET=true; shift 2 ;;
    --title) if [[ -n "${_TITLE_SET}" ]]; then echo "error: --title can only be specified once" >&2; exit 1; fi; TITLE="$2"; _TITLE_SET=true; shift 2 ;;
    --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

_WI_ID_SET=""
if [[ $# -gt 0 ]]; then
  WI_ID="$1"
  _WI_ID_SET=true
  shift
else
  WI_ID=""
fi
if [[ $# -gt 0 ]]; then
  echo "error: nerf-az-boards-mywi-update: 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-boards-mywi-update: ${_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-boards-mywi-update: failed to canonicalize cwd '$PWD'" >&2
    echo "  hint: invoke from a valid directory" >&2
    return 1
  }
  _canonical=$(realpath -m -- "$_input") || {
    echo "error: nerf-az-boards-mywi-update: ${_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-boards-mywi-update: ${_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-boards-mywi-update: ${_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-boards-mywi-update: ${_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-boards-mywi-update: ${_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-boards-mywi-update: ${_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-boards-mywi-update: ${_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-boards-mywi-update: ${_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-boards-mywi-update: ${_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-boards-mywi-update: ${_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-boards-mywi-update: ${_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 "${_WI_ID_SET}" ]] && [[ "${WI_ID}" == -* ]]; then
  echo "error: nerf-az-boards-mywi-update: <wi_id> cannot start with '-'" >&2
  echo "  hint: use -- before positional arguments if needed" >&2
  exit 1
fi

if [[ -z "${WI_ID}" ]]; then
  echo "error: nerf-az-boards-mywi-update: missing required argument <wi_id>" >&2
  echo "  hint: provide a value for <wi_id>" >&2
  usage
fi

_NERF_PATTERN='^[0-9]+$'
if [[ -n "${_WI_ID_SET}" ]] && ! [[ "${WI_ID}" =~ $_NERF_PATTERN ]]; then
  echo "error: nerf-az-boards-mywi-update: argument <wi_id> does not match required pattern" >&2
  echo "  value:   \"${WI_ID}\"" >&2
  echo "  pattern: ^[0-9]+$" >&2
  echo "  hint: value must match ^[0-9]+$" >&2
  exit 1
fi

which jq > /dev/null 2>&1 || { echo 'error: nerf-az-boards-mywi-update: jq is required but not installed (e.g. apt-get install jq, brew install jq).' >&2; exit 1; }
( [[ -n "${STATE}" || -n "${TITLE}" ]] ) || { echo 'error: nerf-az-boards-mywi-update: at least one of --state or --title is required' >&2; exit 1; }

_nerf_pre() {
  if [[ -n "${_DIRECTORY_SET}" && -z "${_PROJECT_SET}" ]]; then
    _URL=$(git -C "${DIRECTORY}" remote get-url origin 2>/dev/null) \
      || { echo "error: -C: no 'origin' remote in '${DIRECTORY}'" >&2; return 1; }
    _PROJ=$(echo "${_URL}" | sed -nE 's|.*dev\.azure\.com/[^/]+/([^/]+)/_git/.*|\1|p; s|.*://[^/]*visualstudio\.com/(DefaultCollection/)?([^/]+)/_git/.*|\2|p; s|.*:v3/[^/]+/([^/]+)/.*|\1|p')
    _PROJ="${_PROJ//%20/ }"
    if [[ -z "${_PROJ}" ]]; then
      echo "error: -C: could not parse Azure DevOps project from remote URL '${_URL}'" >&2
      return 1
    fi
    PROJECT="${_PROJ}"
    _PROJECT_SET=true
  fi
}

_nerf_pre_rc=0
_nerf_pre || _nerf_pre_rc=$?
if [ $_nerf_pre_rc -ne 0 ]; then
  echo "error: nerf-az-boards-mywi-update: 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-boards-mywi-update would run inline script"
  exit 0
fi

CURRENT_USER=$(az devops invoke --area connectionData --resource connectionData --output json \
  | jq -r '.authenticatedUser.uniqueName // ""')
if [[ -z "${CURRENT_USER}" ]]; then
  echo "error: az-boards-mywi-update: could not determine current Azure DevOps user (try 'az login')" >&2
  exit 1
fi
SHOW_ARGS=(az boards work-item show --id "${WI_ID}" --output json)
[[ -n "${_PROJECT_SET}" ]] && SHOW_ARGS+=(--project "${PROJECT}")
WI_JSON=$("${SHOW_ARGS[@]}") || {
  echo "error: az-boards-mywi-update: could not fetch work item ${WI_ID}" >&2
  exit 1
}
ASSIGNED=$(printf '%s' "${WI_JSON}" | jq -r '.fields["System.AssignedTo"].uniqueName // ""')
if [[ -z "${ASSIGNED}" ]]; then
  echo "error: az-boards-mywi-update: work item ${WI_ID} is not assigned to anyone" >&2
  exit 1
fi
ASSIGNED_LC=$(printf '%s' "${ASSIGNED}" | tr '[:upper:]' '[:lower:]')
CURRENT_USER_LC=$(printf '%s' "${CURRENT_USER}" | tr '[:upper:]' '[:lower:]')
if [[ "${ASSIGNED_LC}" != "${CURRENT_USER_LC}" ]]; then
  echo "error: az-boards-mywi-update: work item ${WI_ID} is assigned to ${ASSIGNED}, not you (${CURRENT_USER}). Use az-boards-wi-update for items assigned to others." >&2
  exit 1
fi
UPDATE_ARGS=(az boards work-item update --id "${WI_ID}" --output json)
[[ -n "${STATE}" ]] && UPDATE_ARGS+=(--state "${STATE}")
[[ -n "${TITLE}" ]] && UPDATE_ARGS+=(--title "${TITLE}")
[[ -n "${_PROJECT_SET}" ]] && UPDATE_ARGS+=(--project "${PROJECT}")
"${UPDATE_ARGS[@]}"
