#!/usr/bin/env bash
# Interactive setup for Cloudflare API credentials
# Usage: ./setup-cloudflare-env.sh

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

echo "Cloudflare API Credentials Setup"
echo "================================="
echo ""

# Check if .env exists
if [[ -f "$ENV_FILE" ]]; then
    echo "Found existing .env file: $ENV_FILE"
    read -p "Overwrite? (y/N): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        echo "Keeping existing .env file"
        exit 0
    fi
fi

echo ""
echo "Choose authentication method:"
echo "1. API Token (Recommended - more secure)"
echo "2. Email + API Key (Legacy)"
read -p "Choice [1-2]: " -n 1 -r
echo ""

if [[ $REPLY == "1" ]]; then
    echo ""
    echo "Get your API Token from:"
    echo "  https://dash.cloudflare.com/profile/api-tokens"
    echo "  Create token with: Zone:Edit, Account:Cloudflare Tunnel:Edit permissions"
    echo ""
    read -p "Enter Cloudflare API Token: " -s CLOUDFLARE_API_TOKEN
    echo ""
    
    if [[ -z "$CLOUDFLARE_API_TOKEN" ]]; then
        echo "Error: API Token cannot be empty"
        exit 1
    fi
    
    cat > "$ENV_FILE" <<EOF
# Cloudflare API Configuration
CLOUDFLARE_API_TOKEN="${CLOUDFLARE_API_TOKEN}"

# Domain
DOMAIN="d-bis.org"

# Optional: Zone ID (will be auto-detected if not set)
# CLOUDFLARE_ZONE_ID=""

# Optional: Account ID (will be auto-detected if not set)
# CLOUDFLARE_ACCOUNT_ID=""

# Tunnel Token (already installed)
TUNNEL_TOKEN="eyJhIjoiNTJhZDU3YTcxNjcxYzVmYzAwOWVkZjA3NDQ2NTgxOTYiLCJ0IjoiMTBhYjIyZGEtOGVhMy00ZTJlLWE4OTYtMjdlY2UyMjExYTA1IiwicyI6IlptRXlOMkkyTVRrdE1EZzFNeTAwTkRBNExXSXhaalF0Wm1KaE5XVmpaVEEzTVdGbCJ9"
EOF

elif [[ $REPLY == "2" ]]; then
    echo ""
    read -p "Enter Cloudflare Email: " CLOUDFLARE_EMAIL
    read -p "Enter Cloudflare API Key: " -s CLOUDFLARE_API_KEY
    echo ""
    
    if [[ -z "$CLOUDFLARE_EMAIL" ]] || [[ -z "$CLOUDFLARE_API_KEY" ]]; then
        echo "Error: Email and API Key cannot be empty"
        exit 1
    fi
    
    cat > "$ENV_FILE" <<EOF
# Cloudflare API Configuration
CLOUDFLARE_EMAIL="${CLOUDFLARE_EMAIL}"
CLOUDFLARE_API_KEY="${CLOUDFLARE_API_KEY}"

# Domain
DOMAIN="d-bis.org"

# Optional: Zone ID (will be auto-detected if not set)
# CLOUDFLARE_ZONE_ID=""

# Optional: Account ID (will be auto-detected if not set)
# CLOUDFLARE_ACCOUNT_ID=""

# Tunnel Token (already installed)
TUNNEL_TOKEN="eyJhIjoiNTJhZDU3YTcxNjcxYzVmYzAwOWVkZjA3NDQ2NTgxOTYiLCJ0IjoiMTBhYjIyZGEtOGVhMy00ZTJlLWE4OTYtMjdlY2UyMjExYTA1IiwicyI6IlptRXlOMkkyTVRrdE1EZzFNeTAwTkRBNExXSXhaalF0Wm1KaE5XVmpaVEEzTVdGbCJ9"
EOF

else
    echo "Invalid choice"
    exit 1
fi

chmod 600 "$ENV_FILE"
echo ""
echo "✓ Credentials saved to: $ENV_FILE"
echo ""
echo "Next step: Run ./scripts/configure-cloudflare-api.sh"

