#!/usr/bin/env bash
# Cloudflare DNS Configuration Script
# Automates DNS record creation for d-bis.org domain

set -euo pipefail

# Colors for output

# Configuration
ZONE_ID=""
API_TOKEN=""
IP_ADDRESS=""
DOMAIN="d-bis.org"

# Parse arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        --zone-id)
            ZONE_ID="$2"
            shift 2
            ;;
        --api-token)
            API_TOKEN="$2"
            shift 2
            ;;
        --ip)
            IP_ADDRESS="$2"
            shift 2
            ;;
        --domain)
            DOMAIN="$2"
            shift 2
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Validate arguments
if [ -z "$ZONE_ID" ] || [ -z "$API_TOKEN" ] || [ -z "$IP_ADDRESS" ]; then
    echo "Usage: $0 --zone-id <zone_id> --api-token <api_token> --ip <ip_address> [--domain <domain>]"
    exit 1
fi

# Logging function
log() {
    log_success "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

error() {
    log_error "[ERROR] $1"
    exit 1
}

warn() {
    log_warn "[WARNING] $1"
}

# Cloudflare API function
cloudflare_api() {
    local method=$1
    local endpoint=$2
    local data=${3:-}
    
    if [ -n "$data" ]; then
        curl -s -X "$method" \
            "https://api.cloudflare.com/client/v4/$endpoint" \
            -H "Authorization: Bearer $API_TOKEN" \
            -H "Content-Type: application/json" \
            -d "$data"
    else
        curl -s -X "$method" \
            "https://api.cloudflare.com/client/v4/$endpoint" \
            -H "Authorization: Bearer $API_TOKEN" \
            -H "Content-Type: application/json"
    fi
}

# Check if DNS record exists
check_record() {
    local record_type=$1
    local record_name=$2
    
    cloudflare_api "GET" "zones/$ZONE_ID/dns_records?type=$record_type&name=$record_name" | \
        jq -e '.result | length > 0' > /dev/null 2>&1
}

# Get DNS record ID
get_record_id() {
    local record_type=$1
    local record_name=$2
    
    cloudflare_api "GET" "zones/$ZONE_ID/dns_records?type=$record_type&name=$record_name" | \
        jq -r '.result[0].id'
}

# Create or update DNS record
create_or_update_record() {
    local record_type=$1
    local record_name=$2
    local record_content=$3
    local ttl=${4:-300}
    local proxied=${5:-true}
    
    if check_record "$record_type" "$record_name"; then
        log "Updating DNS record: $record_name ($record_type) -> $record_content"
        local record_id=$(get_record_id "$record_type" "$record_name")
        
        local data=$(jq -n \
            --arg type "$record_type" \
            --arg name "$record_name" \
            --arg content "$record_content" \
            --argjson ttl "$ttl" \
            --argjson proxied "$proxied" \
            '{
                type: $type,
                name: $name,
                content: $content,
                ttl: $ttl,
                proxied: $proxied
            }')
        
        local response=$(cloudflare_api "PUT" "zones/$ZONE_ID/dns_records/$record_id" "$data")
        
        if echo "$response" | jq -e '.success' > /dev/null; then
            log "DNS record updated successfully"
        else
            error "Failed to update DNS record: $(echo "$response" | jq -r '.errors[0].message')"
        fi
    else
        log "Creating DNS record: $record_name ($record_type) -> $record_content"
        
        local data=$(jq -n \
            --arg type "$record_type" \
            --arg name "$record_name" \
            --arg content "$record_content" \
            --argjson ttl "$ttl" \
            --argjson proxied "$proxied" \
            '{
                type: $type,
                name: $name,
                content: $content,
                ttl: $ttl,
                proxied: $proxied
            }')
        
        local response=$(cloudflare_api "POST" "zones/$ZONE_ID/dns_records" "$data")
        
        if echo "$response" | jq -e '.success' > /dev/null; then
            log "DNS record created successfully"
        else
            error "Failed to create DNS record: $(echo "$response" | jq -r '.errors[0].message')"
        fi
    fi
}

# Main function
main() {
    log "Configuring Cloudflare DNS for $DOMAIN"
    log "Zone ID: $ZONE_ID"
    log "IP Address: $IP_ADDRESS"
    
    # Create A record for root domain
    create_or_update_record "A" "$DOMAIN" "$IP_ADDRESS" 300 true
    create_or_update_record "A" "www.$DOMAIN" "$IP_ADDRESS" 300 true
    
    # Create A record for RPC endpoint
    create_or_update_record "A" "rpc.$DOMAIN" "$IP_ADDRESS" 300 true
    create_or_update_record "A" "rpc2.$DOMAIN" "$IP_ADDRESS" 300 true
    
    # Create A record for explorer
    create_or_update_record "A" "explorer.$DOMAIN" "$IP_ADDRESS" 300 true
    
    # Create CNAME records (if needed)
    # create_or_update_record "CNAME" "api.$DOMAIN" "rpc.$DOMAIN" 300 true
    
    log "Cloudflare DNS configuration completed"
    log "DNS records may take a few minutes to propagate"
}

# Run main function
main "$@"

