#!/usr/bin/env bash

# PowerDNS Verification Script for WHP
# This script verifies that PowerDNS is properly configured and running

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}Verifying PowerDNS installation...${NC}"

# Check if PowerDNS containers are running
echo -e "${BLUE}Checking PowerDNS containers...${NC}"

if docker ps -q -f name=powerdns | grep -q .; then
    echo -e "✓ PowerDNS container is running"
else
    echo -e "✗ PowerDNS container is not running"
    exit 1
fi

# Check if configuration files exist
echo -e "${BLUE}Checking configuration files...${NC}"

if [ -f "/docker/powerdns/config/pdns.conf" ]; then
    echo -e "✓ PowerDNS configuration file exists"
else
    echo -e "✗ PowerDNS configuration file missing"
    exit 1
fi

if [ -f "/docker/powerdns/config/passwords.conf" ]; then
    echo -e "✓ PowerDNS passwords file exists"
else
    echo -e "✗ PowerDNS passwords file missing"
    exit 1
fi

if [ -f "/docker/powerdns/config/whp-integration.conf" ]; then
    echo -e "✓ WHP integration configuration exists"
else
    echo -e "✗ WHP integration configuration missing"
    exit 1
fi

# Get API key from passwords file
if [ -f "/docker/powerdns/config/passwords.conf" ]; then
    API_KEY=$(grep "^PDNS_API_KEY=" /docker/powerdns/config/passwords.conf | cut -d'=' -f2)
else
    echo -e "✗ Cannot read API key from passwords file"
    exit 1
fi

# Test PowerDNS API
echo -e "${BLUE}Testing PowerDNS API...${NC}"

if curl -s -H "X-API-Key: ${API_KEY}" http://localhost:8081/api/v1/servers/localhost > /dev/null 2>&1; then
    echo -e "✓ PowerDNS API is responding"
else
    echo -e "✗ PowerDNS API is not responding"
    exit 1
fi

# Test DNS resolution (basic test)
echo -e "${BLUE}Testing DNS resolution...${NC}"

# Create a test zone if none exists
ZONES=$(curl -s -H "X-API-Key: ${API_KEY}" http://localhost:8081/api/v1/servers/localhost/zones 2>/dev/null | jq -r '.[].name' 2>/dev/null || echo "")

if [ -z "$ZONES" ]; then
    echo -e "${YELLOW}No zones found - creating test zone...${NC}"
    
    # Create a test zone
    curl -s -X POST -H "X-API-Key: ${API_KEY}" -H "Content-Type: application/json" \
        -d '{"name":"test.local.","kind":"Native","nameservers":["ns1.test.local.","ns2.test.local."]}' \
        http://localhost:8081/api/v1/servers/localhost/zones > /dev/null 2>&1
    
    if [ $? -eq 0 ]; then
        echo -e "✓ Test zone created successfully"
        
        # Test DNS resolution
        if dig @localhost test.local A > /dev/null 2>&1; then
            echo -e "✓ DNS resolution is working"
        else
            echo -e "✗ DNS resolution test failed"
        fi
        
        # Clean up test zone
        curl -s -X DELETE -H "X-API-Key: ${API_KEY}" \
            http://localhost:8081/api/v1/servers/localhost/zones/test.local. > /dev/null 2>&1
        echo -e "✓ Test zone cleaned up"
    else
        echo -e "✗ Failed to create test zone"
    fi
else
    echo -e "✓ Found existing zones: $(echo "$ZONES" | head -3 | tr '\n' ' ')"
    
    # Test DNS resolution with existing zone
    FIRST_ZONE=$(echo "$ZONES" | head -1 | sed 's/\.$//')
    if dig @localhost "$FIRST_ZONE" A > /dev/null 2>&1; then
        echo -e "✓ DNS resolution is working"
    else
        echo -e "✗ DNS resolution test failed"
    fi
fi

# Check database connectivity
echo -e "${BLUE}Checking database connectivity...${NC}"

# Get database password
DB_PASSWORD=$(grep "^PDNS_DB_PASSWORD=" /docker/powerdns/config/passwords.conf | cut -d'=' -f2)

if mysql -h 127.0.0.1 -u pdns -p"${DB_PASSWORD}" -e "USE powerdns; SELECT COUNT(*) FROM domains;" > /dev/null 2>&1; then
    echo -e "✓ PowerDNS database connection successful"
else
    echo -e "✗ PowerDNS database connection failed"
    exit 1
fi

# Check log files
echo -e "${BLUE}Checking log files...${NC}"

if [ -d "/docker/powerdns/logs" ]; then
    echo -e "✓ PowerDNS logs directory exists"
else
    echo -e "✗ PowerDNS logs directory missing"
fi

# Final status
echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}PowerDNS verification completed successfully!${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""
echo -e "${BLUE}PowerDNS Services:${NC}"
echo -e "  • PowerDNS Server: http://localhost:8081 (API)"
echo -e "  • DNS Resolution: Port 53 (TCP/UDP)"
echo ""
echo -e "${BLUE}Management:${NC}"
echo -e "  • Password Management: ./scripts/powerdns-password-manager.sh"
echo -e "  • Health Check: /docker/powerdns/health-check.sh"
echo -e "  • Backup: /docker/powerdns/backup.sh"
echo ""
echo -e "${YELLOW}Remember to change the default password!${NC}" 
