#!/usr/bin/env bash
# nerf-nx-run -- Run an Nx target on a project in project:target format (e.g. myapp:build).
# Generated from nx manifest. Do not edit directly.
# nerf:threat:read=workspace
# nerf:threat:write=workspace

if [[ "${BASH_VERSINFO[0]:-0}" -lt 4 ]]; then
  echo "error: nerf-nx-run 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-nx-run <target>

Arguments:
  <target> (required)
      Target in project:target format (e.g. myapp:build, myapp:test, myapp:lint)
      Must match: ^[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+$

Maps to: npx nx run <target>

Run an Nx target on a project in project:target format (e.g. myapp:build).
EOF
  exit 1
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --nerf-dry-run) _NERF_DRY_RUN="true"; shift 1 ;;
    -h|--help) usage ;;
    --) shift; break ;;
    *) break ;;
  esac
done

_TARGET_SET=""
if [[ $# -gt 0 ]]; then
  TARGET="$1"
  _TARGET_SET=true
  shift
else
  TARGET=""
fi
if [[ $# -gt 0 ]]; then
  echo "error: nerf-nx-run: unexpected extra arguments: $*" >&2
  echo "  hint: switches and options must come before positional arguments" >&2
  exit 1
fi

if [[ -n "${_TARGET_SET}" ]] && [[ "${TARGET}" == -* ]]; then
  echo "error: nerf-nx-run: <target> cannot start with '-'" >&2
  echo "  hint: use -- before positional arguments if needed" >&2
  exit 1
fi

if [[ -z "${TARGET}" ]]; then
  echo "error: nerf-nx-run: missing required argument <target>" >&2
  echo "  hint: provide a value for <target>" >&2
  usage
fi

_NERF_PATTERN='^[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+$'
if [[ -n "${_TARGET_SET}" ]] && ! [[ "${TARGET}" =~ $_NERF_PATTERN ]]; then
  echo "error: nerf-nx-run: argument <target> does not match required pattern" >&2
  echo "  value:   \"${TARGET}\"" >&2
  echo "  pattern: ^[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+$" >&2
  echo "  hint: value must match ^[a-zA-Z0-9_-]+:[a-zA-Z0-9_-]+$" >&2
  exit 1
fi

test -f nx.json > /dev/null 2>&1 || { echo 'error: nerf-nx-run: Not in an Nx workspace root (nx.json not found). Run from the repo root.' >&2; exit 1; }

if [[ "$_NERF_DRY_RUN" == "true" ]]; then
  _NERF_DRY_CMD=(npx nx run "${TARGET}")
  printf 'dry-run:'
  for _a in "${_NERF_DRY_CMD[@]}"; do printf " %q" "$_a"; done
  echo
  exit 0
fi

exec npx nx run "${TARGET}"
