#!/bin/bash
# Check domain registration and DNS status

set -euo pipefail

if [ $# -ne 1 ]; then
    echo "Usage: $0 <domain>"
    exit 1
fi

DOMAIN="$1"

# Colors
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}Domain Status Check: $DOMAIN${NC}"
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# Check Google Cloud Domains registration
echo "→ Google Cloud Domains Registration:"
if gcloud domains registrations describe "$DOMAIN" --format=yaml 2>/dev/null; then
    echo -e "  ${GREEN}✓ Domain registered${NC}"
else
    echo -e "  ${RED}✗ Domain not found in Google Cloud${NC}"
fi
echo ""

# Check DNS nameservers
echo "→ Current Nameservers (public DNS):"
if dig NS "$DOMAIN" +short 2>/dev/null | head -4; then
    echo -e "  ${GREEN}✓ Nameservers visible${NC}"
else
    echo -e "  ${YELLOW}⚠ Nameservers not yet propagated${NC}"
fi
echo ""

# Check Cloudflare zone status
if [ -n "${CLOUDFLARE_API_TOKEN:-}" ]; then
    echo "→ Cloudflare Zone Status:"
    ZONE_INFO=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$DOMAIN" \
        -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" 2>/dev/null)
    
    if echo "$ZONE_INFO" | jq -e '.result | length > 0' > /dev/null 2>&1; then
        STATUS=$(echo "$ZONE_INFO" | jq -r '.result[0].status')
        NS1=$(echo "$ZONE_INFO" | jq -r '.result[0].name_servers[0]')
        NS2=$(echo "$ZONE_INFO" | jq -r '.result[0].name_servers[1]')
        
        echo "  Status: $STATUS"
        echo "  Nameservers:"
        echo "    - $NS1"
        echo "    - $NS2"
        
        if [ "$STATUS" == "active" ]; then
            echo -e "  ${GREEN}✓ Zone active${NC}"
        else
            echo -e "  ${YELLOW}⚠ Zone pending (waiting for nameserver propagation)${NC}"
        fi
    else
        echo -e "  ${RED}✗ No Cloudflare zone found${NC}"
    fi
else
    echo "→ Cloudflare Zone Status: ${YELLOW}(CLOUDFLARE_API_TOKEN not set)${NC}"
fi
echo ""

# Check WHOIS
echo "→ WHOIS Privacy:"
if whois "$DOMAIN" 2>/dev/null | grep -iq "privacy\|redacted\|data protected"; then
    echo -e "  ${GREEN}✓ Privacy protection enabled${NC}"
else
    echo -e "  ${YELLOW}⚠ Privacy may not be enabled${NC}"
fi
echo ""

echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo "Check complete!"
