#!/bin/bash
# Isolated live confirmation of the roster-cert fix, using the REAL roster_server.py.
# Runs under `sudo unshare -n` so port 8081 is free and production is never touched.
#
# Proves: with a cert from the FIXED generator (IP SAN), a client that verifies the cert
# BY THE DIALED IP completes the handshake against the real server and gets the roster
# XML; with the OLD DNS-only cert, the same client fails verification (certificate_unknown
# class). That is the exact before/after the production fix targets.
set -u
D=/tmp/roster-iso
rm -rf "$D"; mkdir -p "$D"
cp /home/alex/OpenFUT/fifa17-recon/tools/roster_server.py "$D/" && sed -i "s@/tmp/roster_server.log@$D/roster_server.log@" "$D/roster_server.py"
DIAL=127.0.0.1
DNS="DNS:winter15.gosredirector.ea.com,DNS:*.gosredirector.ea.com,DNS:*.ea.com"

ip link set lo up 2>/dev/null || { echo "  FATAL: cannot bring up lo in namespace"; exit 1; }

gen() {  # $1 = san
  openssl req -x509 -newkey rsa:2048 -nodes -keyout "$D/redir_key.pem" -out "$D/redir_cert.pem" \
    -days 3650 -subj "/CN=winter15.gosredirector.ea.com" -addext "subjectAltName=$1" >/dev/null 2>&1
}

run_server() {
  OPENFUT_BIND=127.0.0.1 python3 "$D/roster_server.py" >"$D/srv.log" 2>&1 &
  echo $! > "$D/srv.pid"
  for i in $(seq 1 25); do ss -tln 2>/dev/null | grep -q ":8081" && return 0; sleep 0.2; done
  echo "  FATAL: roster_server never bound 8081"; echo "  --- srv.log ---"; sed "s/^/    /" "$D/srv.log"; return 1
}
stop_server() { kill "$(cat "$D/srv.pid" 2>/dev/null)" 2>/dev/null; for i in $(seq 1 25); do ss -tln 2>/dev/null | grep -q ":8081" || return 0; sleep 0.2; done; echo "  WARN: 8081 still bound after stop"; }

rc_new=9; rc_old=9

echo "=== NEW cert (fixed generator: DNS + IP:$DIAL,IP:10.10.0.120) ==="
gen "$DNS,IP:$DIAL,IP:10.10.0.120"
echo "  SAN: $(openssl x509 -in "$D/redir_cert.pem" -noout -ext subjectAltName | tail -1 | tr -s ' ')"
if run_server; then
  python3 "$(dirname "$0")/roster-cert-verify.py" "$D/redir_cert.pem" "$DIAL" 8081; rc_new=$?
  stop_server
fi

echo "=== OLD cert (DNS-only, the failing production shape) ==="
gen "$DNS"
if run_server; then
  python3 "$(dirname "$0")/roster-cert-verify.py" "$D/redir_cert.pem" "$DIAL" 8081; rc_old=$?
  stop_server
fi

echo "=== verdict ==="
echo "  new cert exit=$rc_new (want 0 = verified+200)"
echo "  old cert exit=$rc_old (want 1 = verify failed)"
if [ "$rc_new" = 0 ] && [ "$rc_old" = 1 ]; then
  echo "  PASS: the real roster server serves a by-IP-verifiable cert after the fix, not before"
else
  echo "  FAIL: unexpected outcome"
fi
rm -rf "$D"