#!/usr/bin/env bash
# Usage: ./repro.sh <jenkins-url> [count]
# Creates <count> freestyle jobs via POST /createItem?name=... with an XML body and
# counts the responses by status and X-Error header.
set -euo pipefail
J=${1:-http://localhost:8080}; N=${2:-200}
CJ=$(mktemp)
CRUMB=$(curl -s -c "$CJ" "$J/crumbIssuer/api/json" | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["crumbRequestField"] + ": " + d["crumb"])' 2>/dev/null || true)
XML='<?xml version="1.1" encoding="UTF-8"?><project><builders/><publishers/><buildWrappers/></project>'
for i in $(seq 1 "$N"); do
  name="repro job $RANDOM$RANDOM"
  enc=$(printf '%s' "$name" | sed 's/ /%20/g')
  curl -s -o /dev/null -D - -b "$CJ" ${CRUMB:+-H "$CRUMB"} \
    -X POST -H 'Content-Type: text/xml; charset=UTF-8' --data-binary "$XML" \
    "$J/createItem?name=$enc" | tr -d '\r' | awk '/^HTTP/{s=$2} /^X-Error/{e=substr($0,10)} END{print s, e}'
done | sort | uniq -c
rm -f "$CJ"
