#!/usr/bin/env bash
set -euo pipefail
# secretcurl hands its config over as `-K <file>` (a /dev/fd pipe), not stdin.
cfg=""
while [ "$#" -gt 0 ]; do
  if [ "$1" = "-K" ] && [ "$#" -gt 1 ]; then cfg=$(cat "$2"); shift; fi
  shift
done
# secretcurl runs curl with a near-empty environment, so the test hands its
# settings over as files under $HOME (one of the few variables kept).
state="$HOME/fake-curl-state"
FAKE_CURL_HTTP=$(cat "$HOME/fake-curl-http" 2>/dev/null || true)
attempt=0
[ -f "$state" ] && attempt=$(cat "$state")
next=$((attempt + 1))
echo "$next" > "$state"
out=$(printf '%s\n' "$cfg" | sed -n 's/^-o "\(.*\)"$/\1/p' | head -1)
if [ -n "${FAKE_CURL_HTTP:-}" ]; then
  [ -z "$out" ] || printf '%s' '{"error":"client"}' > "$out"
  printf '%s' "$FAKE_CURL_HTTP"
  exit 0
fi
if [ "$attempt" -eq 0 ]; then
  [ -z "$out" ] || printf '%s' '{"error":"transient"}' > "$out"
  printf '503'
else
  [ -z "$out" ] || printf '%s' '{"output":[{"type":"message","content":[{"type":"output_text","text":"ok"}]}]}' > "$out"
  printf '200'
fi
