#!/usr/bin/env bash
# Create DNS record for rpc-core.d-bis.org using Cloudflare API
# Usage: ./create-dns-record-rpc-core.sh [API_TOKEN] [ZONE_ID]
# Supports both API_TOKEN and API_KEY+EMAIL from .env file

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }

DOMAIN="rpc-core.d-bis.org"
NAME="rpc-core"
IP="192.168.11.250"

# Load .env if exists
if [ -f "$SCRIPT_DIR/../.env" ]; then
    source "$SCRIPT_DIR/../.env" 2>/dev/null
elif [ -f "$SCRIPT_DIR/.env" ]; then
    source "$SCRIPT_DIR/.env" 2>/dev/null
fi

# Get API credentials (token or key+email)
if [ -n "$1" ]; then
    # Token provided as argument
    API_TOKEN="$1"
    API_EMAIL=""
    API_KEY=""
    AUTH_METHOD="token"
    log_info "Using API token from argument"
elif [ -n "$CLOUDFLARE_API_TOKEN" ]; then
    API_TOKEN="$CLOUDFLARE_API_TOKEN"
    API_EMAIL=""
    API_KEY=""
    AUTH_METHOD="token"
    log_info "Using API token from .env"
elif [ -n "$CLOUDFLARE_API_KEY" ] && [ -n "$CLOUDFLARE_EMAIL" ]; then
    API_TOKEN=""
    API_KEY="$CLOUDFLARE_API_KEY"
    API_EMAIL="$CLOUDFLARE_EMAIL"
    AUTH_METHOD="key"
    log_info "Using API key + email from .env"
else
    log_error "No Cloudflare credentials found"
    log_info "Usage: $0 [API_TOKEN] [ZONE_ID]"
    log_info ""
    log_info "Or set in .env file:"
    log_info "  CLOUDFLARE_API_TOKEN=\"your-token\""
    log_info "  OR"
    log_info "  CLOUDFLARE_API_KEY=\"your-key\""
    log_info "  CLOUDFLARE_EMAIL=\"your-email\""
    exit 1
fi

ZONE_ID="${2:-${CLOUDFLARE_ZONE_ID:-}}"

# Set up auth headers
if [ "$AUTH_METHOD" = "token" ]; then
    AUTH_HEADER="Authorization: Bearer $API_TOKEN"
    AUTH_EXTRA=""
else
    AUTH_HEADER="X-Auth-Email: $API_EMAIL"
    AUTH_EXTRA="X-Auth-Key: $API_KEY"
fi

# Get Zone ID if not provided
if [ -z "$ZONE_ID" ]; then
    log_info "Getting Zone ID for d-bis.org..."
    if [ "$AUTH_METHOD" = "token" ]; then
        ZONE_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=d-bis.org" \
            -H "$AUTH_HEADER" \
            -H "Content-Type: application/json")
    else
        ZONE_RESPONSE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=d-bis.org" \
            -H "$AUTH_HEADER" \
            -H "$AUTH_EXTRA" \
            -H "Content-Type: application/json")
    fi
    
    ZONE_ID=$(echo "$ZONE_RESPONSE" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)
    
    if [ -z "$ZONE_ID" ]; then
        log_error "Failed to get Zone ID. Check API credentials and domain."
        log_info "Response: $(echo "$ZONE_RESPONSE" | head -3)"
        exit 1
    fi
    log_success "Zone ID: $ZONE_ID"
else
    log_info "Using Zone ID: $ZONE_ID"
fi

# Check if record already exists
log_info "Checking if DNS record already exists..."
if [ "$AUTH_METHOD" = "token" ]; then
    EXISTING=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?name=$DOMAIN" \
        -H "$AUTH_HEADER" \
        -H "Content-Type: application/json")
else
    EXISTING=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?name=$DOMAIN" \
        -H "$AUTH_HEADER" \
        -H "$AUTH_EXTRA" \
        -H "Content-Type: application/json")
fi

if echo "$EXISTING" | grep -q '"id"'; then
    RECORD_ID=$(echo "$EXISTING" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)
    log_warn "DNS record already exists (ID: $RECORD_ID)"
    log_info "Updating existing record..."
    
    # Update existing record
    if [ "$AUTH_METHOD" = "token" ]; then
        RESPONSE=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" \
            -H "$AUTH_HEADER" \
            -H "Content-Type: application/json" \
            --data "{
                \"type\": \"A\",
                \"name\": \"$NAME\",
                \"content\": \"$IP\",
                \"ttl\": 1,
                \"proxied\": false
            }")
    else
        RESPONSE=$(curl -s -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" \
            -H "$AUTH_HEADER" \
            -H "$AUTH_EXTRA" \
            -H "Content-Type: application/json" \
            --data "{
                \"type\": \"A\",
                \"name\": \"$NAME\",
                \"content\": \"$IP\",
                \"ttl\": 1,
                \"proxied\": false
            }")
    fi
else
    log_info "Creating new DNS record..."
    
    # Create new record
    if [ "$AUTH_METHOD" = "token" ]; then
        RESPONSE=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
            -H "$AUTH_HEADER" \
            -H "Content-Type: application/json" \
            --data "{
                \"type\": \"A\",
                \"name\": \"$NAME\",
                \"content\": \"$IP\",
                \"ttl\": 1,
                \"proxied\": false
            }")
    else
        RESPONSE=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
            -H "$AUTH_HEADER" \
            -H "$AUTH_EXTRA" \
            -H "Content-Type: application/json" \
            --data "{
                \"type\": \"A\",
                \"name\": \"$NAME\",
                \"content\": \"$IP\",
                \"ttl\": 1,
                \"proxied\": false
            }")
    fi
fi

# Check response
if echo "$RESPONSE" | grep -q '"success":true'; then
    log_success "DNS record created/updated successfully!"
    
    # Get record details
    RECORD_ID=$(echo "$RESPONSE" | grep -o '"id":"[^"]*' | head -1 | cut -d'"' -f4)
    log_info "Record ID: $RECORD_ID"
    log_info "Domain: $DOMAIN"
    log_info "IP: $IP"
    log_info "Proxied: Yes (🟠 Orange Cloud)"
    
    echo ""
    log_info "DNS record created. Wait 2-5 minutes for propagation, then run:"
    log_info "  pct exec 2500 -- certbot --nginx --non-interactive --agree-tos --email admin@d-bis.org -d rpc-core.d-bis.org --redirect"
else
    log_error "Failed to create DNS record"
    log_info "Response: $RESPONSE"
    exit 1
fi
