#!/usr/bin/env bash
set -euo pipefail

ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
GATE="$ROOT/curl-timeout-gate.mjs"

run_gate() {
  local command=$1
  jq -cn --arg command "$command" '{tool_name:"Bash",tool_input:{command:$command}}' | node "$GATE"
}

assert_allowed() {
  local command=$1
  local output
  output=$(run_gate "$command")
  [[ -z "$output" ]] || {
    printf 'expected allow: %s\noutput: %s\n' "$command" "$output" >&2
    exit 1
  }
}

assert_denied() {
  local command=$1
  local output
  output=$(run_gate "$command")
  jq -e '.hookSpecificOutput.permissionDecision == "deny"' <<<"$output" >/dev/null || {
    printf 'expected deny: %s\noutput: %s\n' "$command" "$output" >&2
    exit 1
  }
}

assert_allowed 'printf ok'
assert_allowed 'printf curl'
assert_allowed 'which curl'
assert_allowed 'grep curl settings.json'
assert_allowed 'curl --max-time 10 https://example.com'
assert_allowed 'curl --max-time=10 https://example.com'
assert_allowed '/usr/bin/curl -m 10 https://example.com'
assert_allowed 'curl -m10 https://example.com'
assert_allowed 'curl -sm10 https://example.com'
assert_allowed "bash -c 'curl -m 10 https://example.com'"
assert_denied 'curl https://example.com'
assert_denied 'env TOKEN=value curl https://example.com'
assert_denied 'command curl https://example.com'
assert_denied 'timeout 30s curl https://example.com'
assert_denied '/usr/bin/curl -s https://example.com'
assert_denied 'printf ok && curl https://example.com'
assert_denied 'curl -m 10 https://example.com && curl https://example.org'
assert_denied "bash -c 'curl https://example.com'"

malformed_output=$(printf 'not-json' | node "$GATE")
jq -e '.hookSpecificOutput.permissionDecision == "deny"' <<<"$malformed_output" >/dev/null || {
  printf 'expected malformed input denial\noutput: %s\n' "$malformed_output" >&2
  exit 1
}

printf 'PASS: curl timeout gate\n'
