#!/bin/bash
# Automated Cloudflare Tunnel Setup
# Automatically loads domain from .env file

set -euo pipefail

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

# Load domain from .env
if [ -f "$ENV_FILE" ]; then
    export $(grep -v '^#' "$ENV_FILE" | grep -E "CLOUDFLARE_DOMAIN" | xargs)
    # Get domain from CLOUDFLARE_DOMAIN or extract from RPC_URL
    if [ -n "${CLOUDFLARE_DOMAIN:-}" ]; then
        DOMAIN_NAME="rpc.${CLOUDFLARE_DOMAIN}"
        echo "Domain loaded from .env (CLOUDFLARE_DOMAIN): $DOMAIN_NAME"
    else
        RPC_URL=$(grep "^RPC_URL=" "$ENV_FILE" 2>/dev/null | cut -d'=' -f2 | tr -d '"' || echo "")
        if [ -n "$RPC_URL" ]; then
            DOMAIN_NAME=$(echo "$RPC_URL" | sed 's|https\?://||' | sed 's|/.*||')
            if [ -n "$DOMAIN_NAME" ]; then
                echo "Domain loaded from .env (RPC_URL): $DOMAIN_NAME"
            fi
        fi
    fi
fi

# Allow override via argument
DOMAIN_NAME="${1:-${DOMAIN_NAME:-}}"

if [ -z "$DOMAIN_NAME" ]; then
    echo "Error: No domain name found in .env (RPC_URL) and none provided as argument"
    echo "Usage: $0 [domain-name]"
    echo "Example: $0 rpc.d-bis.org"
    exit 1
fi

echo "=========================================="
echo "Automated Cloudflare Tunnel Setup"
echo "=========================================="
echo "Domain: $DOMAIN_NAME"
echo ""
echo "This script will setup Cloudflare Tunnel on the Nginx proxy."
echo "It requires browser authentication for the initial login."
echo ""
read -p "Press Enter to continue or Ctrl+C to cancel..."

# Get Nginx proxy IP from Terraform
cd "$SCRIPT_DIR/.."
NGINX_IP=$(terraform output -json 2>/dev/null | jq -r '.nginx_proxy.value.public_ip // empty' || echo "")

if [ -z "$NGINX_IP" ]; then
    echo "Error: Nginx proxy IP not found"
    exit 1
fi

echo "Nginx Proxy: $NGINX_IP"
echo ""

# Copy setup script
echo "Copying setup script to Nginx proxy..."
scp "$SCRIPT_DIR/setup-cloudflare-tunnel.sh" besuadmin@$NGINX_IP:/tmp/ 2>&1 || {
    echo "Error: Could not copy script to Nginx proxy"
    exit 1
}

# Run setup script
echo "Running Cloudflare Tunnel setup..."
echo "Note: You will need to complete browser authentication."
echo ""
ssh -t besuadmin@$NGINX_IP "cd /tmp && ./setup-cloudflare-tunnel.sh '$DOMAIN_NAME'" || {
    echo "Error: Cloudflare Tunnel setup failed"
    exit 1
}

echo ""
echo "=========================================="
echo "Cloudflare Tunnel Setup Complete!"
echo "=========================================="
echo "Domain: $DOMAIN_NAME"
echo "Tunnel should now be running."
echo ""
echo "Verify:"
echo "  curl https://$DOMAIN_NAME/health"
echo ""

