#!/bin/bash
# Automated Cloudflare DNS Configuration
# Creates DNS records via Cloudflare API using credentials from .env

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../../.." && pwd)"
ENV_FILE="$PROJECT_ROOT/.env"

# Load Cloudflare credentials
if [ ! -f "$ENV_FILE" ]; then
    echo "Error: .env file not found at $ENV_FILE"
    exit 1
fi

export $(grep -v '^#' "$ENV_FILE" | grep -E "CLOUDFLARE_" | xargs)

if [ -z "${CLOUDFLARE_ZONE_ID:-}" ] || [ -z "${CLOUDFLARE_API_TOKEN:-}" ]; then
    echo "Error: Missing Cloudflare credentials in .env"
    exit 1
fi

DOMAIN_NAME="${1:-}"
TUNNEL_ID="${2:-}"

if [ -z "$DOMAIN_NAME" ]; then
    echo "Usage: $0 <domain-name> [tunnel-id]"
    echo "Example: $0 rpc.yourdomain.com <tunnel-id>"
    exit 1
fi

if [ -z "$TUNNEL_ID" ]; then
    echo "Warning: No tunnel ID provided. DNS record will point to placeholder."
    TUNNEL_ID="placeholder-tunnel-id"
fi

echo "=========================================="
echo "Cloudflare DNS Configuration"
echo "=========================================="
echo "Domain: $DOMAIN_NAME"
echo "Tunnel ID: $TUNNEL_ID"
echo ""

# Check if record already exists
EXISTING=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/dns_records?name=${DOMAIN_NAME}" \
    -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
    -H "Content-Type: application/json" | jq -r '.result[0].id // empty' 2>/dev/null || echo "")

if [ -n "$EXISTING" ]; then
    echo "DNS record already exists. Updating..."
    
    # Update existing record
    RESPONSE=$(curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/dns_records/${EXISTING}" \
        -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
        -H "Content-Type: application/json" \
        --data "{\"type\":\"CNAME\",\"name\":\"${DOMAIN_NAME}\",\"content\":\"${TUNNEL_ID}.cfargotunnel.com\",\"ttl\":3600,\"proxied\":true}")
    
    SUCCESS=$(echo "$RESPONSE" | jq -r '.success // false' 2>/dev/null || echo "false")
    
    if [ "$SUCCESS" = "true" ]; then
        echo "✓ DNS record updated successfully"
    else
        echo "✗ Failed to update DNS record"
        echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
        exit 1
    fi
else
    echo "Creating new DNS record..."
    
    # Create new record
    RESPONSE=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/dns_records" \
        -H "Authorization: Bearer ${CLOUDFLARE_API_TOKEN}" \
        -H "Content-Type: application/json" \
        --data "{\"type\":\"CNAME\",\"name\":\"${DOMAIN_NAME}\",\"content\":\"${TUNNEL_ID}.cfargotunnel.com\",\"ttl\":3600,\"proxied\":true}")
    
    SUCCESS=$(echo "$RESPONSE" | jq -r '.success // false' 2>/dev/null || echo "false")
    
    if [ "$SUCCESS" = "true" ]; then
        echo "✓ DNS record created successfully"
    else
        echo "✗ Failed to create DNS record"
        echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
        exit 1
    fi
fi

echo ""
echo "DNS Configuration Complete!"
echo "  Domain: $DOMAIN_NAME"
echo "  Points to: ${TUNNEL_ID}.cfargotunnel.com"
echo "  Proxy: Enabled (orange cloud)"
echo ""

