#!/bin/sh

echo "Testing EDNS Client Subnet (ECS) functionality"
echo "=============================================="
echo ""

# Start the DoH proxy with ECS enabled
echo "Starting DoH proxy with ECS enabled..."
timeout 30 cargo run -- -H example.com -u 8.8.8.8:53 --enable-ecs &
DOH_PID=$!

# Wait for server to start
sleep 3

echo ""
echo "Testing DNS query with client IP headers..."
echo ""

# Test with X-Forwarded-For header
echo "1. Testing with X-Forwarded-For header (simulating client IP 1.2.3.4):"
dig @127.0.0.1 -p 53 +short A example.com | head -5 &
DIG_PID=$!

# Intercept and show the query being sent
echo "   Sending query with X-Forwarded-For: 1.2.3.4"
curl -s -H "X-Forwarded-For: 1.2.3.4" \
     -H "Content-Type: application/dns-message" \
     --data-binary @- \
     "http://127.0.0.1:3000/dns-query" < /dev/null | od -x | head -3

echo ""
echo "2. Testing with X-Real-IP header (simulating client IP 5.6.7.8):"
curl -s -H "X-Real-IP: 5.6.7.8" \
     -H "Content-Type: application/dns-message" \
     --data-binary @- \
     "http://127.0.0.1:3000/dns-query" < /dev/null | od -x | head -3

echo ""
echo "3. Testing without client IP headers (using direct connection):"
curl -s -H "Content-Type: application/dns-message" \
     --data-binary @- \
     "http://127.0.0.1:3000/dns-query" < /dev/null | od -x | head -3

# Clean up
kill $DOH_PID 2>/dev/null
wait $DOH_PID 2>/dev/null

echo ""
echo "Test completed!"
echo ""
echo "Note: To verify ECS is working, you would need to:"
echo "1. Use tcpdump/wireshark to capture outgoing DNS queries to 8.8.8.8"
echo "2. Look for EDNS0 Client Subnet option in the queries"
echo "3. Or use a DNS server that logs ECS information"