#!/usr/bin/env bash
# nerf-git-commit-amend -- Amend the most recent commit with a new Conventional Commits subject and an optional body. Fails if the commit has already been pushed to any remote. Use only to fix the last local commit. Subject must be at most 72 characters; put longer explanations in the body positional. Must not contain Co-Authored-By trailers.
# Generated from git manifest. Do not edit directly.
# nerf:threat:read=workspace
# nerf:threat:write=workspace

if [[ "${BASH_VERSINFO[0]:-0}" -lt 4 ]]; then
  echo "error: nerf-git-commit-amend 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-git-commit-amend [-C <directory>] <subject> [<body>]

Options:
  -C <directory>
      Subdirectory of the workspace to run git in (must be under cwd)

Arguments:
  <subject> (required)
      Commit subject line: type[(scope)][!]: description (max 72 chars)
      Must match: ^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-zA-Z0-9._,-]+\))?!?: .+
  <body>
      Optional commit body (rendered as a separate paragraph). Use for longer explanations.

Amend the most recent commit with a new Conventional Commits subject and an optional body. Fails if the commit has already been pushed to any remote. Use only to fix the last local commit. Subject must be at most 72 characters; put longer explanations in the body positional. Must not contain Co-Authored-By trailers.
EOF
  exit 1
}

DIRECTORY=""
_DIRECTORY_SET=""

while [[ $# -gt 0 ]]; do
  case "$1" in
    -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

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

if [[ -z "${SUBJECT}" ]]; then
  echo "error: nerf-git-commit-amend: missing required argument <subject>" >&2
  echo "  hint: provide a value for <subject>" >&2
  usage
fi

_NERF_PATTERN='^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-zA-Z0-9._,-]+\))?!?: .+$'
if [[ -n "${_SUBJECT_SET}" ]] && ! [[ "${SUBJECT}" =~ $_NERF_PATTERN ]]; then
  echo "error: nerf-git-commit-amend: argument <subject> does not match required pattern" >&2
  echo "  value:   \"${SUBJECT}\"" >&2
  echo "  pattern: ^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-zA-Z0-9._,-]+\))?!?: .+" >&2
  echo "  hint: value must match ^(feat|fix|docs|style|refactor|perf|test|build|ci|chore|revert)(\([a-zA-Z0-9._,-]+\))?!?: .+" >&2
  exit 1
fi

if [[ -n "${_BODY_SET}" ]] && [[ "${BODY}" == -* ]]; then
  echo "error: nerf-git-commit-amend: <body> cannot start with '-'" >&2
  echo "  hint: use -- before positional arguments if needed" >&2
  exit 1
fi

( [ ${#SUBJECT} -le 72 ] ) || { echo 'error: nerf-git-commit-amend: Commit subject must be at most 72 characters.' >&2; exit 1; }
( ! printf '%s\n%s' "${SUBJECT}" "${BODY:-}" | grep -qi 'co-authored-by:' ) || { echo 'error: nerf-git-commit-amend: Commit message must not contain Co-Authored-By trailers.' >&2; exit 1; }

_nerf_pre() {
  if ! git ${DIRECTORY:+-C} ${DIRECTORY:+"${DIRECTORY}"} rev-parse HEAD > /dev/null 2>&1; then
    echo "error: no commits to amend" >&2
    return 1
  fi
  REMOTE_BRANCHES=$(git ${DIRECTORY:+-C} ${DIRECTORY:+"${DIRECTORY}"} branch -r --contains HEAD 2>/dev/null)
  if [ -n "$REMOTE_BRANCHES" ]; then
    echo "error: HEAD exists on remote branches -- amending would require a force push" >&2
    echo "  remote branches: $(echo "$REMOTE_BRANCHES" | tr -s ' \n' ', ' | sed 's/,$//')" >&2
    return 1
  fi
}

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

if [[ "$_NERF_DRY_RUN" == "true" ]]; then
  echo "dry-run: nerf-git-commit-amend would run inline script"
  exit 0
fi

if [ -n "${BODY:-}" ]; then
  exec git ${DIRECTORY:+-C} ${DIRECTORY:+"${DIRECTORY}"} commit --amend -m "${SUBJECT}" -m "${BODY}"
else
  exec git ${DIRECTORY:+-C} ${DIRECTORY:+"${DIRECTORY}"} commit --amend -m "${SUBJECT}"
fi
