#!/bin/bash
# Bulk domain registration via Google Cloud Domains + Cloudflare nameservers
#
# Usage:
#   ./bulk-register.sh domains.txt
#
# Requirements:
#   - gcloud CLI authenticated
#   - CLOUDFLARE_API_TOKEN env var set
#   - CLOUDFLARE_ACCOUNT_ID env var set
#   - contact.yaml file in current directory

set -euo pipefail

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

# Check prerequisites
if ! command -v gcloud &> /dev/null; then
    echo -e "${RED}Error: gcloud CLI not found${NC}"
    exit 1
fi

if ! command -v curl &> /dev/null; then
    echo -e "${RED}Error: curl not found${NC}"
    exit 1
fi

if ! command -v jq &> /dev/null; then
    echo -e "${RED}Error: jq not found${NC}"
    exit 1
fi

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

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

if [ ! -f "contact.yaml" ]; then
    echo -e "${RED}Error: contact.yaml not found${NC}"
    exit 1
fi

# Get domains from file or args
if [ $# -eq 1 ] && [ -f "$1" ]; then
    mapfile -t DOMAINS < "$1"
else
    DOMAINS=("$@")
fi

if [ ${#DOMAINS[@]} -eq 0 ]; then
    echo "Usage: $0 <domains.txt> OR $0 domain1.com domain2.com ..."
    exit 1
fi

echo -e "${YELLOW}Bulk Domain Registration${NC}"
echo "Domains to process: ${#DOMAINS[@]}"
echo ""

RESULTS_FILE="registration-results-$(date +%Y%m%d-%H%M%S).txt"
SUCCESS_COUNT=0
FAIL_COUNT=0

for DOMAIN in "${DOMAINS[@]}"; do
    # Skip empty lines
    [ -z "$DOMAIN" ] && continue
    
    echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
    echo -e "Processing: ${GREEN}$DOMAIN${NC}"
    echo ""
    
    # Step 1: Check availability
    echo "→ Checking availability..."
    if ! gcloud domains registrations search-domains "$DOMAIN" 2>/dev/null | grep -q "AVAILABLE"; then
        echo -e "  ${RED}✗ $DOMAIN not available${NC}"
        echo "FAIL: $DOMAIN - Not available" >> "$RESULTS_FILE"
        ((FAIL_COUNT++))
        continue
    fi
    echo -e "  ${GREEN}✓ Available${NC}"
    
    # Step 2: Get price
    echo "→ Getting price..."
    PRICE=$(gcloud domains registrations get-register-parameters "$DOMAIN" \
        --format="value(yearlyPrice.units)" 2>/dev/null)
    
    if [ -z "$PRICE" ]; then
        echo -e "  ${RED}✗ Could not get price${NC}"
        echo "FAIL: $DOMAIN - Price lookup failed" >> "$RESULTS_FILE"
        ((FAIL_COUNT++))
        continue
    fi
    echo -e "  ${GREEN}✓ Price: \$${PRICE}.00 USD/year${NC}"
    
    # Step 3: Create Cloudflare zone
    echo "→ Creating Cloudflare zone..."
    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\"
        }")
    
    # Check for errors
    if echo "$ZONE_RESPONSE" | jq -e '.success == false' > /dev/null 2>&1; then
        ERROR_MSG=$(echo "$ZONE_RESPONSE" | jq -r '.errors[0].message')
        echo -e "  ${RED}✗ Cloudflare error: $ERROR_MSG${NC}"
        echo "FAIL: $DOMAIN - Cloudflare zone creation failed: $ERROR_MSG" >> "$RESULTS_FILE"
        ((FAIL_COUNT++))
        continue
    fi
    
    NS1=$(echo "$ZONE_RESPONSE" | jq -r '.result.name_servers[0]')
    NS2=$(echo "$ZONE_RESPONSE" | jq -r '.result.name_servers[1]')
    
    if [ "$NS1" == "null" ] || [ "$NS2" == "null" ]; then
        echo -e "  ${RED}✗ Could not get nameservers${NC}"
        echo "FAIL: $DOMAIN - Nameserver extraction failed" >> "$RESULTS_FILE"
        ((FAIL_COUNT++))
        continue
    fi
    
    echo -e "  ${GREEN}✓ Zone created${NC}"
    echo "    NS: $NS1"
    echo "    NS: $NS2"
    
    # Step 4: Register domain
    echo "→ Registering domain..."
    if gcloud domains registrations register "$DOMAIN" \
        --contact-data-from-file=contact.yaml \
        --contact-privacy=private-contact-data \
        --yearly-price="${PRICE}.00 USD" \
        --name-servers="$NS1,$NS2" \
        --quiet \
        --async 2>&1 | tee -a "$RESULTS_FILE"; then
        
        echo -e "  ${GREEN}✓ Registration initiated${NC}"
        echo "SUCCESS: $DOMAIN - Registered with NS $NS1, $NS2" >> "$RESULTS_FILE"
        ((SUCCESS_COUNT++))
    else
        echo -e "  ${RED}✗ Registration failed${NC}"
        echo "FAIL: $DOMAIN - gcloud registration command failed" >> "$RESULTS_FILE"
        ((FAIL_COUNT++))
    fi
    
    echo ""
    sleep 2  # Rate limit courtesy
done

# Summary
echo -e "${YELLOW}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${GREEN}Registration Summary${NC}"
echo -e "  Success: ${GREEN}$SUCCESS_COUNT${NC}"
echo -e "  Failed:  ${RED}$FAIL_COUNT${NC}"
echo -e "  Results: $RESULTS_FILE"
echo ""
echo "Check status with:"
echo "  gcloud domains operations list"
echo "  gcloud domains registrations list"
