#!/usr/bin/env bash
# Post-session analysis. Usage: bash lab-analyze.sh <metrics-dir> <client-ip>
D="$1"; U="$2"; PC="$D/session.pcap"
[ -z "$U" ] && { echo "usage: lab-analyze.sh <dir> <client-ip>"; exit 1; }
hist(){ grep -oP 'length \K[0-9]+' | awk '{if($1<200)b="<200(ack/keepalive)";else if($1<1200)b="200-1199";else if($1<1290)b="1200-1289";else if($1<1400)b="1290-1399";else b=">=1400"}{c[b]++}END{for(k in c)printf "    %-22s %d\n",k,c[k]}' | sort; }
echo "############ NODE: $(basename $D) | CLIENT: $U ############"
echo "=== HYSTERIA UDP: client->server (uplink) ==="
tcpdump -nr "$PC" "src host $U and udp" 2>/dev/null | hist
echo "  max uplink: $(tcpdump -nr $PC "src host $U and udp" 2>/dev/null | grep -oP 'length \K[0-9]+' | sort -n | tail -1)"
echo "=== HYSTERIA UDP: server->client (downlink) ==="
tcpdump -nr "$PC" "dst host $U and udp" 2>/dev/null | hist
echo "  max downlink: $(tcpdump -nr $PC "dst host $U and udp" 2>/dev/null | grep -oP 'length \K[0-9]+' | sort -n | tail -1)"
echo "=== throughput per 5s (downlink data pkts >200B) ==="
tcpdump -ttnr "$PC" "dst host $U and udp" 2>/dev/null | awk '{for(i=1;i<=NF;i++)if($i=="length"){s=$(i+1)+0};if(s>200){b=int($1/5)*5;c[b]++}}END{for(k in c)print "    t="k" datapkts="c[k]}' | sort | tail -30
echo "=== stalls (gaps >3s in the flow) ==="
tcpdump -ttnr "$PC" "host $U" 2>/dev/null | awk '{t=$1+0;if(p){d=t-p;if(d>3)printf "    gap %.1fs\n",d};p=t}' | head
echo "=== session lifetime ==="
FIRST=$(tcpdump -ttnr "$PC" "host $U" 2>/dev/null | head -1 | awk '{print int($1)}')
LAST=$(tcpdump -ttnr "$PC" "host $U" 2>/dev/null | tail -1 | awk '{print int($1)}')
echo "    first..last = $((LAST-FIRST))s   total pkts = $(tcpdump -nr $PC "host $U" 2>/dev/null | wc -l)"
echo "=== reality (tcp 8443) pkts for client ==="
tcpdump -nr "$PC" "host $U and tcp port 8443" 2>/dev/null | wc -l
echo "=== DROP / ERROR deltas (before -> after) ==="
paste <(grep -A30 '## nic stats' "$D/before.txt" 2>/dev/null | grep -iE 'drop|error|discard|miss') \
      <(grep -A30 '## nic stats' "$D/after.txt" 2>/dev/null | grep -iE 'drop|error|discard|miss') | head
echo "  udp_rcvbuf_err before/after:"; grep UdpRcvbufErrors "$D/before.txt" "$D/after.txt" 2>/dev/null | awk '{print "   ",$0}'
echo "  conntrack before/after:"; grep -A1 'conntrack count' "$D/before.txt" "$D/after.txt" 2>/dev/null | grep -oE '[0-9]+' | tr '\n' ' '; echo
echo "=== hysteria per-user tx/rx (bytes) ==="
cat "$D/hysteria-traffic.json" 2>/dev/null | python3 -m json.tool 2>/dev/null | head
