#!/bin/bash
# Get Cloudflare nameservers for a domain
# Creates zone if it doesn't exist

set -euo pipefail

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

DOMAIN="$1"

if [ -z "${CLOUDFLARE_API_TOKEN:-}" ]; then
    echo "Error: CLOUDFLARE_API_TOKEN not set"
    exit 1
fi

if [ -z "${CLOUDFLARE_ACCOUNT_ID:-}" ]; then
    echo "Error: CLOUDFLARE_ACCOUNT_ID not set"
    exit 1
fi

# Check if zone exists
EXISTING_ZONE=$(curl -s -X GET "https://api.cloudflare.com/client/v4/zones?name=$DOMAIN" \
    -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
    -H "Content-Type: application/json")

ZONE_COUNT=$(echo "$EXISTING_ZONE" | jq -r '.result | length')

if [ "$ZONE_COUNT" -gt 0 ]; then
    echo "Zone already exists for $DOMAIN"
    NS1=$(echo "$EXISTING_ZONE" | jq -r '.result[0].name_servers[0]')
    NS2=$(echo "$EXISTING_ZONE" | jq -r '.result[0].name_servers[1]')
else
    echo "Creating Cloudflare zone for $DOMAIN..."
    ZONE_RESPONSE=$(curl -s -X POST "https://api.cloudflare.com/client/v4/zones" \
        -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
        -H "Content-Type: application/json" \
        --data "{
            \"account\": {
                \"id\": \"$CLOUDFLARE_ACCOUNT_ID\"
            },
            \"name\": \"$DOMAIN\",
            \"type\": \"full\"
        }")
    
    if echo "$ZONE_RESPONSE" | jq -e '.success == false' > /dev/null 2>&1; then
        ERROR_MSG=$(echo "$ZONE_RESPONSE" | jq -r '.errors[0].message')
        echo "Error: $ERROR_MSG"
        exit 1
    fi
    
    NS1=$(echo "$ZONE_RESPONSE" | jq -r '.result.name_servers[0]')
    NS2=$(echo "$ZONE_RESPONSE" | jq -r '.result.name_servers[1]')
fi

echo ""
echo "Cloudflare Nameservers for $DOMAIN:"
echo "  $NS1"
echo "  $NS2"
echo ""
echo "Use these in your registration command:"
echo "  --name-servers=\"$NS1,$NS2\""
