#!/bin/bash
# Update DNS Record to Point to Cloudflare Tunnel
# Updates existing DNS record to point to tunnel

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"
    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"
    exit 1
fi

DOMAIN_NAME="${1:-rpc.d-bis.org}"
TUNNEL_ID="${2:-}"

if [ -z "$TUNNEL_ID" ]; then
    # Try to get tunnel ID from existing tunnel
    TUNNEL_ID=$(sudo cloudflared tunnel list 2>/dev/null | grep "phase1-nginx-proxy" | awk '{print $1}' || echo "")
    if [ -z "$TUNNEL_ID" ]; then
        echo "Error: Tunnel ID required or tunnel not found"
        exit 1
    fi
fi

echo "=========================================="
echo "Updating DNS Record to Tunnel"
echo "=========================================="
echo "Domain: $DOMAIN_NAME"
echo "Tunnel ID: $TUNNEL_ID"
echo ""

# Get existing record
RECORD_ID=$(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 [ -z "$RECORD_ID" ]; then
    echo "Error: DNS record not found for $DOMAIN_NAME"
    exit 1
fi

echo "Found DNS record: $RECORD_ID"
echo "Updating to point to tunnel..."

# Update record
RESPONSE=$(curl -s -X PATCH "https://api.cloudflare.com/client/v4/zones/${CLOUDFLARE_ZONE_ID}/dns_records/${RECORD_ID}" \
    -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"
    echo "  $DOMAIN_NAME → ${TUNNEL_ID}.cfargotunnel.com"
    echo "  Proxy: Enabled"
else
    echo "✗ Failed to update DNS record"
    echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
    exit 1
fi

echo ""
echo "DNS update complete!"
echo "Note: DNS propagation may take a few minutes."

