#!/bin/sh

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

# Create a base64-encoded DNS query for example.com
DNS_QUERY="yv4BAAABAAAAAAABB2V4YW1wbGUDY29tAAABAAEAACkQAAAAgAAAAA=="

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

# Wait for server to start
sleep 3

echo ""
echo "Testing DNS queries with different client IPs:"
echo ""

# Test 1: With X-Forwarded-For header
echo "1. Query with X-Forwarded-For: 192.168.1.100"
curl -s -H "X-Forwarded-For: 192.168.1.100" \
     "http://127.0.0.1:3000/dns-query?dns=$DNS_QUERY" \
     -o response1.bin
echo "   Response size: $(wc -c < response1.bin) bytes"
echo "   First few bytes: $(od -x response1.bin | head -1)"

echo ""
echo "2. Query with X-Real-IP: 10.0.0.50"
curl -s -H "X-Real-IP: 10.0.0.50" \
     "http://127.0.0.1:3000/dns-query?dns=$DNS_QUERY" \
     -o response2.bin
echo "   Response size: $(wc -c < response2.bin) bytes"
echo "   First few bytes: $(od -x response2.bin | head -1)"

echo ""
echo "3. Query with IPv6 client (X-Forwarded-For: 2001:db8::1)"
curl -s -H "X-Forwarded-For: 2001:db8::1" \
     "http://127.0.0.1:3000/dns-query?dns=$DNS_QUERY" \
     -o response3.bin
echo "   Response size: $(wc -c < response3.bin) bytes"
echo "   First few bytes: $(od -x response3.bin | head -1)"

echo ""
echo "4. Query without client IP headers"
curl -s "http://127.0.0.1:3000/dns-query?dns=$DNS_QUERY" \
     -o response4.bin
echo "   Response size: $(wc -c < response4.bin) bytes"
echo "   First few bytes: $(od -x response4.bin | head -1)"

# Test with JSON API
echo ""
echo "5. JSON API with X-Forwarded-For: 203.0.113.1"
curl -s -H "X-Forwarded-For: 203.0.113.1" \
     -H "Accept: application/dns-json" \
     "http://127.0.0.1:3000/dns-query?name=example.com&type=1" | jq -r '.Answer[0].data' 2>/dev/null || echo "   Failed to get JSON response"

# Clean up
kill $DOH_PID 2>/dev/null
rm -f response*.bin

echo ""
echo "Test completed!"
echo ""
echo "Note: EDNS Client Subnet adds the client's IP (truncated to /24 for IPv4, /56 for IPv6)"
echo "to the DNS query sent to the upstream resolver (8.8.8.8 in this case)."
echo "This allows the resolver to return geographically optimized results."