#!/usr/bin/env bash
# PostToolUse: shellcheck a shell script the moment it is edited.
#
# The scripts under infra/deploy/ run as root over SSH against live hosts with no
# test suite in front of them — a quoting bug or an unset-variable typo is found on
# the host, or not at all. shell-lint.yml already guards this, but only after a
# push: a five-minute round trip to learn about a missing quote, by which point the
# context that produced it is gone.
#
# Findings are fed back to the model rather than blocking the edit. The file is
# already written; the useful move is to fix it now, in the same turn.
#
# Matches shell-lint.yml's pinned shellcheck when one is on PATH. If shellcheck is
# not installed this exits quietly — CI is still the backstop, and a missing local
# tool must not break editing.
set -uo pipefail

payload=$(cat)
command -v jq        >/dev/null 2>&1 || exit 0
command -v shellcheck >/dev/null 2>&1 || exit 0

path=$(printf '%s' "$payload" | jq -r '.tool_response.filePath // .tool_input.file_path // ""')
[ -n "$path" ] || exit 0
case "$path" in *.sh) ;; *) exit 0 ;; esac
[ -f "$path" ] || exit 0

if out=$(shellcheck -f gcc "$path" 2>&1); then
  exit 0
fi

# Keep the feedback small: findings only, capped.
out=$(printf '%s' "$out" | head -30)
jq -n --arg p "$path" --arg o "$out" \
  '{decision:"block", reason:("shellcheck findings in \($p) — shell-lint CI will fail on these, so fix them now:\n\($o)")}'
