#!/bin/bash

# Test DNS resolution using dig
# Usage: ./02_dig_test.sh

set -e

echo "Testing DNS resolution with dig..."

# Function to test DNS query
test_dns_query() {
    local hostname="$1"
    local expected_ip="$2"
    local description="$3"

    echo ""
    echo "Testing: $description"
    echo "Query: $hostname.argus.com"
    echo "Expected IP: $expected_ip"

    # Perform dig query
    result=$(dig @localhost $hostname.argus.com A +short 2>/dev/null || echo "QUERY_FAILED")

    if [ "$result" = "QUERY_FAILED" ]; then
        echo "✗ DNS query failed"
        return 1
    elif [ "$result" = "$expected_ip" ]; then
        echo "✓ DNS query successful: $result"
        return 0
    else
        echo "✗ DNS query returned unexpected result: $result"
        return 1
    fi
}

# Check if dig is available
if ! command -v dig &> /dev/null; then
    echo "Installing dig (dnsutils)..."
    apt-get update && apt-get install -y dnsutils
fi

# Check if container is running
if ! docker compose ps | grep -q "Up"; then
    echo "Error: BIND9 container is not running"
    echo "Please start the container first with: ./01_start_container.sh"
    exit 1
fi

echo "=== DNS Resolution Tests ==="

# Test cases based on current configuration
failed_tests=0

# Test ns1.argus.com -> 127.0.0.1
if ! test_dns_query "ns1" "127.0.0.1" "Name server resolution"; then
    ((failed_tests++))
fi

# Test web.argus.com -> 12.4.5.6
if ! test_dns_query "web" "12.4.5.6" "Web server resolution"; then
    ((failed_tests++))
fi

echo ""
echo "=== Test Summary ==="
if [ $failed_tests -eq 0 ]; then
    echo "✓ All DNS tests passed!"
    exit 0
else
    echo "✗ $failed_tests test(s) failed"
    exit 1
fi