#!/usr/bin/env bash
set -euo pipefail
out=work/scratch/liferay-critical/host-routing-confusion.jsonl
: > "$out"
run_case() {
  local name=$1; shift
  local hdr body err rc status loc bytes preview xid
  hdr=$(mktemp); body=$(mktemp); err=$(mktemp)
  set +e
  curl -sk --http1.1 --max-time 12 -X POST 'https://infoportal.baloise.de/api/spring/portal' \
    -H 'X-Bug-Bounty: dwbzn' -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")
  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 name "$name" --argjson rc "$rc" --argjson status "$status" --arg location "$loc" --argjson bytes "$bytes" --arg preview "$preview" --arg exchange "$xid" '{name:$name,rc:$rc,status:$status,location:$location,bytes:$bytes,preview:$preview,exchange:$exchange}' >> "$out"
  rm -f "$hdr" "$body" "$err"
}
run_case baseline
run_case host_registration -H 'Host: mein-portal-registrierung.baloise.de'
run_case host_registration_xfh_info -H 'Host: mein-portal-registrierung.baloise.de' -H 'X-Forwarded-Host: infoportal.baloise.de'
run_case host_info_xfh_registration -H 'Host: infoportal.baloise.de' -H 'X-Forwarded-Host: mein-portal-registrierung.baloise.de'
run_case host_registration_forwarded_info -H 'Host: mein-portal-registrierung.baloise.de' -H 'Forwarded: host=infoportal.baloise.de;proto=https'
run_case host_info_forwarded_registration -H 'Host: infoportal.baloise.de' -H 'Forwarded: host=mein-portal-registrierung.baloise.de;proto=https'
run_case duplicate_registration_then_info -H 'Host: mein-portal-registrierung.baloise.de' -H 'Host: infoportal.baloise.de'
run_case duplicate_info_then_registration -H 'Host: infoportal.baloise.de' -H 'Host: mein-portal-registrierung.baloise.de'
run_case comma_registration_info -H 'Host: mein-portal-registrierung.baloise.de, infoportal.baloise.de'
run_case comma_info_registration -H 'Host: infoportal.baloise.de, mein-portal-registrierung.baloise.de'
jq -r '[.status,.bytes,.name,.location,.preview,.exchange] | @tsv' "$out"
