#!/bin/bash
# get-cloudflare-info.sh
# Gets Cloudflare Zone ID and Account ID using credentials from .env

set -euo pipefail

# Load environment variables from .env if it exists
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -f "${SCRIPT_DIR}/../.env" ]; then
    set -a
    source <(grep -v '^#' "${SCRIPT_DIR}/../.env" | grep -v '^$' | sed 's/^/export /')
    set +a
fi

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

DOMAIN="${DOMAIN:-sankofa.nexus}"
API_TOKEN="${CLOUDFLARE_API_TOKEN:-}"
API_KEY="${CLOUDFLARE_API_KEY:-}"
API_EMAIL="${CLOUDFLARE_EMAIL:-}"

log() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1" >&2
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

check_auth() {
    if [ -z "$API_TOKEN" ] && [ -z "$API_KEY" ]; then
        error "Either CLOUDFLARE_API_TOKEN or CLOUDFLARE_API_KEY must be set"
    fi
    
    if [ -z "$API_TOKEN" ] && [ -z "$API_EMAIL" ]; then
        error "If using CLOUDFLARE_API_KEY, CLOUDFLARE_EMAIL must also be set"
    fi
}

get_zone_id() {
    log "Getting Zone ID for ${DOMAIN}..."
    
    local zone_id
    if [ -n "$API_TOKEN" ]; then
        zone_id=$(curl -s -X GET \
            -H "Authorization: Bearer ${API_TOKEN}" \
            -H "Content-Type: application/json" \
            "https://api.cloudflare.com/client/v4/zones?name=${DOMAIN}" | \
            jq -r '.result[0].id')
    else
        zone_id=$(curl -s -X GET \
            -H "X-Auth-Email: ${API_EMAIL}" \
            -H "X-Auth-Key: ${API_KEY}" \
            -H "Content-Type: application/json" \
            "https://api.cloudflare.com/client/v4/zones?name=${DOMAIN}" | \
            jq -r '.result[0].id')
    fi
    
    if [ "$zone_id" != "null" ] && [ -n "$zone_id" ]; then
        echo "CLOUDFLARE_ZONE_ID=${zone_id}"
        log "✓ Zone ID: ${zone_id}"
        return 0
    else
        warn "Could not get Zone ID for ${DOMAIN}"
        return 1
    fi
}

get_account_id() {
    log "Getting Account ID..."
    
    local account_id
    if [ -n "$API_TOKEN" ]; then
        account_id=$(curl -s -X GET \
            -H "Authorization: Bearer ${API_TOKEN}" \
            -H "Content-Type: application/json" \
            "https://api.cloudflare.com/client/v4/accounts" | \
            jq -r '.result[0].id')
    else
        account_id=$(curl -s -X GET \
            -H "X-Auth-Email: ${API_EMAIL}" \
            -H "X-Auth-Key: ${API_KEY}" \
            -H "Content-Type: application/json" \
            "https://api.cloudflare.com/client/v4/accounts" | \
            jq -r '.result[0].id')
    fi
    
    if [ "$account_id" != "null" ] && [ -n "$account_id" ]; then
        echo "CLOUDFLARE_ACCOUNT_ID=${account_id}"
        log "✓ Account ID: ${account_id}"
        return 0
    else
        warn "Could not get Account ID"
        return 1
    fi
}

update_env_file() {
    local zone_id=$1
    local account_id=$2
    
    local env_file="${SCRIPT_DIR}/../.env"
    
    if [ ! -f "$env_file" ]; then
        warn ".env file not found, creating it..."
        touch "$env_file"
    fi
    
    # Update or add Zone ID
    if grep -q "^CLOUDFLARE_ZONE_ID=" "$env_file"; then
        sed -i "s/^CLOUDFLARE_ZONE_ID=.*/CLOUDFLARE_ZONE_ID=${zone_id}/" "$env_file"
    else
        echo "CLOUDFLARE_ZONE_ID=${zone_id}" >> "$env_file"
    fi
    
    # Update or add Account ID
    if grep -q "^CLOUDFLARE_ACCOUNT_ID=" "$env_file"; then
        sed -i "s/^CLOUDFLARE_ACCOUNT_ID=.*/CLOUDFLARE_ACCOUNT_ID=${account_id}/" "$env_file"
    else
        echo "CLOUDFLARE_ACCOUNT_ID=${account_id}" >> "$env_file"
    fi
    
    log "✓ Updated .env file"
}

main() {
    echo ""
    echo "╔══════════════════════════════════════════════════════════════╗"
    echo "║          Cloudflare Information Retrieval                    ║"
    echo "╚══════════════════════════════════════════════════════════════╝"
    echo ""
    
    check_auth
    
    local zone_id_output=$(get_zone_id)
    local account_id_output=$(get_account_id)
    
    echo ""
    info "Retrieved Information:"
    echo "$zone_id_output"
    echo "$account_id_output"
    
    # Extract values
    local zone_id=$(echo "$zone_id_output" | cut -d'=' -f2)
    local account_id=$(echo "$account_id_output" | cut -d'=' -f2)
    
    if [ -n "$zone_id" ] && [ "$zone_id" != "null" ] && [ -n "$account_id" ] && [ "$account_id" != "null" ]; then
        echo ""
        read -p "Update .env file with these values? (y/N): " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            update_env_file "$zone_id" "$account_id"
        else
            info "Values not saved. Add them manually to .env:"
            echo "$zone_id_output"
            echo "$account_id_output"
        fi
    else
        warn "Some values could not be retrieved. Check your credentials and domain."
    fi
}

main "$@"

