#!/bin/bash
# VPN MTU and Performance Optimization Testing Script
# Tests MTU values and provides optimization recommendations

set -e

VPN_SERVER_IP="${1:-}"
TUNNEL_IP="${2:-10.0.0.2}"

if [ -z "$VPN_SERVER_IP" ]; then
  echo "Usage: $0 <vpn_server_ip> [tunnel_ip]"
  echo "Example: $0 203.0.113.50 10.0.0.2"
  exit 1
fi

echo "=== VPN MTU and Performance Diagnostic ==="
echo "Server IP: $VPN_SERVER_IP"
echo "Tunnel IP: $TUNNEL_IP"
echo ""

# Test 1: Check interface status
echo "=== 1. Interface Status ==="
if command -v wg &> /dev/null; then
  wg show
  ip -4 addr show wg0 2>/dev/null || echo "wg0 not found"
else
  echo "WireGuard not installed"
fi
echo ""

# Test 2: System resources
echo "=== 2. System Resources ==="
echo "Load average:"
uptime
echo ""

# Test 3: Path MTU discovery (external endpoint)
echo "=== 3. Path MTU Discovery (external endpoint) ==="
echo "Testing different packet sizes to find working MTU..."
echo "Note: If ICMP is blocked, some tests may show 100% loss"

PACKET_SIZES=(1472 1400 1350 1300 1200 1000 500)
for size in "${PACKET_SIZES[@]}"; do
  result=$(ping -c 2 -M do -s "$size" "$VPN_SERVER_IP" 2>&1 | grep "packets transmitted")
  if echo "$result" | grep -q "0% packet loss"; then
    echo "✓ Packet size $size works (MTU: $((size + 28)))"
    break
  elif echo "$result" | grep -q "100% packet loss"; then
    echo "✗ Packet size $size failed"
  fi
done
echo ""

# Test 4: Test through tunnel
echo "=== 4. Tunnel Performance Test ==="
if ping -c 1 -W 1 "$TUNNEL_IP" &> /dev/null; then
  echo "Testing tunnel latency and jitter..."
  for round in {1..3}; do
    echo "Round $round:"
    ping -c 5 "$TUNNEL_IP" | grep "rtt" || echo "Test failed"
    sleep 1
  done
else
  echo "✗ Tunnel IP $TUNNEL_IP unreachable"
fi
echo ""

# Test 5: Current BBR status
echo "=== 5. Congestion Control Status ==="
if [ -f /proc/sys/net/ipv4/tcp_congestion_control ]; then
  echo "Current congestion control: $(cat /proc/sys/net/ipv4/tcp_congestion_control)"
  echo "Default qdisc: $(cat /proc/sys/net/core/default_qdisc)"
  if lsmod | grep -q bbr; then
    echo "✓ BBR module loaded"
  else
    echo "✗ BBR module not loaded"
  fi
else
  echo "Cannot read congestion control settings"
fi
echo ""

# Test 6: Recommendations
echo "=== 6. Optimization Recommendations ==="
echo ""
echo "Recommended MTU values (try in order):"
echo "  1. 1280 - Most conservative, maximum compatibility"
echo "  2. 1300 - Recommended balance of performance and compatibility"
echo "  3. 1350 - If network quality is good"
echo ""
echo "WireGuard configuration with MTU:"
echo "  [Interface]"
echo "  PostUp = ip link set dev wg0 mtu 1300"
echo ""
echo "BBR optimization:"
echo "  modprobe tcp_bbr"
echo "  sysctl -w net.core.default_qdisc=fq"
echo "  sysctl -w net.ipv4.tcp_congestion_control=bbr"
echo ""
