#!/usr/bin/env bash
# Compare how fast two redirects answer. Requires curl and awk.
# Usage: ./compare-redirects.sh [URL_A] [URL_B] [RUNS]
set -euo pipefail

A="${1:-https://redirhub.com}"
B="${2:-https://example.com}"
RUNS="${3:-10}"

measure() {
  # Only the first response is timed (no redirect following), with a
  # fresh connection each run, so DNS, TCP and TLS are included.
  for _ in $(seq "$RUNS"); do
    curl -s -o /dev/null --max-redirs 0 --max-time 10 \
      -w '%{time_namelookup} %{time_connect} %{time_appconnect} %{time_starttransfer} %{http_code} %{redirect_url}\n' \
      "$1" || true
  done
}

report() {
  # Median of each phase, in milliseconds. curl's times are cumulative, so
  # connect and TLS are the differences between them, as on the web page.
  awk -v url="$1" '
    { dns[NR]=$1; tcp[NR]=$2-$1; tls[NR]=($3>0 ? $3-$2 : 0); ttfb[NR]=$4; code=$5; loc=$6 }
    function med(a,  n,i,j,t,b){ n=NR; for(i=1;i<=n;i++) b[i]=a[i]
      for(i=1;i<=n;i++) for(j=i+1;j<=n;j++) if(b[j]<b[i]){t=b[i];b[i]=b[j];b[j]=t}
      return (n%2 ? b[(n+1)/2] : (b[n/2]+b[n/2+1])/2) * 1000 }
    END {
      printf "%s\n  status %s -> %s\n", url, code, (loc==""?"(no Location)":loc)
      printf "  DNS %6.1f ms | connect %6.1f ms | TLS %6.1f ms | first byte %6.1f ms  (median of %d)\n",
        med(dns), med(tcp), med(tls), med(ttfb), NR
    }'
}

measure "$A" | report "$A"
measure "$B" | report "$B"
