#!/usr/bin/env bash
# PreToolUse feeder for the Overdeck browser decision queue.
#
# Disarmed (the normal case): bash builtins only — one line read, one integer
# compare, exit 0. No fork, no stdin drain, no socket.
# Armed: hand the hook payload to the collector and block on the response socket
# until a human answers in the browser or the collector's bound lapses. The
# collector answers with the PreToolUse envelope verbatim for allow/deny, so this
# script never parses JSON; anything else prints nothing and the terminal
# permission flow runs exactly as today.
# The arm file carries its own expiry — a closed browser tab disarms itself.
set -uo pipefail

arm_file="${OVERDECK_CONFIG_DIR:-$HOME/.config/overdeck}/browser-approvals.json"
[[ -r $arm_file ]] || exit 0
arm=""
# `read` reports failure on a final line with no newline; the value still lands.
IFS= read -r arm <"$arm_file"
[[ -n $arm ]] || exit 0

[[ $arm =~ \"until\"[[:space:]]*:[[:space:]]*([0-9]+) ]] || exit 0
(( BASH_REMATCH[1] / 1000 > EPOCHSECONDS )) || exit 0

[[ $arm =~ \"url\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]] || exit 0
url=${BASH_REMATCH[1]}
[[ $arm =~ \"token\"[[:space:]]*:[[:space:]]*\"([^\"]+)\" ]] || exit 0
token=${BASH_REMATCH[1]}
wait_ms=30000
[[ $arm =~ \"waitMs\"[[:space:]]*:[[:space:]]*([0-9]+) ]] && wait_ms=${BASH_REMATCH[1]}

IFS= read -r -d '' payload || true
[[ -n ${payload:-} ]] || exit 0

verdict=$(curl --silent --show-error --fail \
  --max-time "$(( wait_ms / 1000 + 5 ))" \
  --header "authorization: Bearer ${token}" \
  --header 'content-type: application/json' \
  --data-binary @- \
  "${url}/permissions/request/claude-code" <<<"$payload" 2>/dev/null) || exit 0

[[ $verdict == *'"permissionDecision"'* ]] || exit 0
printf '%s\n' "$verdict"
