#!/usr/bin/env bash
# Test double for curl: serves fixtures from $MOCK_ROUTES (routes.tsv) and logs
# each call to $MOCK_CURL_LOG. Refuses anything that is not a plain GET.
set -uo pipefail
argv="$*"
out="" ; hdr="" ; wfmt="" ; url="" ; is_get=0 ; cfg=0
log="${MOCK_CURL_LOG:-/dev/null}"
while [[ $# -gt 0 ]]; do
  case "$1" in
    -X|--request|-d|--data|--data-raw|--data-binary|-F|--form|-T|--upload-file|--json|-I|--head)
      echo "WRITE_ATTEMPT $*" >>"$log"; exit 99 ;;
    --output|-o) out="$2"; shift 2 ;;
    --dump-header|-D) hdr="$2"; shift 2 ;;
    --write-out|-w) wfmt="$2"; shift 2 ;;
    --config|-K) [[ "$2" == "-" ]] && cfg=1; shift 2 ;;
    --header|-H|--max-time|-m) shift 2 ;;
    --get|-G) is_get=1; shift ;;
    --silent|-s|--show-error|-S) shift ;;
    http://*|https://*) url="$1"; shift ;;
    *) echo "UNKNOWN_ARG $1" >>"$log"; shift ;;
  esac
done
auth="no"
if [[ $cfg -eq 1 ]]; then
  conf="$(cat)"
  [[ "$conf" == *"Authorization: Bearer "* ]] && auth="yes"
fi
echo "GET=$is_get auth=$auth $url argv=[$argv]" >>"$log"
base="${GITHUB_API_URL:-https://api.test}"
key="${url#"$base"}"
fixdir="$(dirname "$MOCK_ROUTES")"
status=404 ; body="$fixdir/bodies/notfound.json" ; headers="-"
while IFS=$'\t' read -r p s b h; do
  [[ "$p" == \#* || -z "$p" ]] && continue
  if [[ "$p" == "$key" ]]; then status="$s"; body="$fixdir/bodies/$b"; headers="$h"; break; fi
done <"$MOCK_ROUTES"
if [[ "$status" == "0" ]]; then
  printf '000'
  echo "curl: (7) Failed to connect" >&2
  exit 7
fi
[[ -n "$hdr" ]] && {
  printf 'HTTP/2 %s\r\n' "$status"
  if [[ "$headers" != "-" ]]; then
    IFS='|' read -ra hs <<<"$headers"
    for x in "${hs[@]}"; do printf '%s\r\n' "$x"; done
  fi
  printf '\r\n'
} >"$hdr"
[[ -n "$out" ]] && cp "$body" "$out"
[[ "$wfmt" == *http_code* ]] && printf '%s' "$status"
exit 0
