#!/bin/bash
# Install Cloudflare Tunnel in VMID 102 (cloudflared container)
# Run this on the node where VMID 102 is located (pve2)

set -e

VMID=102
TUNNEL_TOKEN="eyJhIjoiNTJhZDU3YTcxNjcxYzVmYzAwOWVkZjA3NDQ2NTgxOTYiLCJ0IjoiYjAyZmUxZmUtY2I3ZC00ODRlLTkwOWItN2NjNDEyOThlYmU4IiwicyI6Ik5HTmtOV0kwWXpNdFpUVmxaUzAwTVRFMkxXRXdNMk10WlRJNU1ETTFaRFF4TURBMiJ9"

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

log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warn() { echo -e "${YELLOW}[⚠]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  INSTALLING CLOUDFLARE TUNNEL IN VMID 102"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Check container status
log_info "Checking container status..."
CONTAINER_STATUS=$(pct status $VMID 2>/dev/null | awk '{print $2}' || echo "unknown")
if [ "$CONTAINER_STATUS" != "running" ]; then
    log_info "Starting container..."
    pct start $VMID
    sleep 5
fi

# Install cloudflared if needed
log_info "Checking cloudflared installation..."
if ! pct exec $VMID -- command -v cloudflared >/dev/null 2>&1; then
    log_info "Installing cloudflared..."
    pct exec $VMID -- bash -c "cd /tmp && wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64.deb && dpkg -i cloudflared-linux-amd64.deb || apt install -f -y"
    log_success "cloudflared installed"
else
    log_success "cloudflared already installed"
fi

# Install tunnel service
log_info "Installing tunnel service with token..."
INSTALL_OUTPUT=$(pct exec $VMID -- cloudflared service install "$TUNNEL_TOKEN" 2>&1)
if echo "$INSTALL_OUTPUT" | grep -q -E "successfully|installed|Service installed"; then
    log_success "Tunnel service installed"
else
    log_warn "Installation output: $INSTALL_OUTPUT"
    # Continue anyway - service might already be installed
fi

# Start and enable service
log_info "Starting cloudflared service..."
pct exec $VMID -- systemctl start cloudflared
pct exec $VMID -- systemctl enable cloudflared

sleep 5

# Check status
log_info "Checking service status..."
CLOUDFLARED_STATUS=$(pct exec $VMID -- systemctl is-active cloudflared 2>/dev/null || echo "inactive")
if [ "$CLOUDFLARED_STATUS" = "active" ]; then
    log_success "Cloudflared service is running"
else
    log_warn "Cloudflared service is $CLOUDFLARED_STATUS"
fi

# Show status
log_info "Service status:"
pct exec $VMID -- systemctl status cloudflared --no-pager -l | head -15

# Get tunnel info
log_info "Tunnel information:"
pct exec $VMID -- cloudflared tunnel list 2>&1

echo ""
log_success "Installation complete!"
echo ""
log_info "Next: Wait 1-2 minutes for tunnel to connect, then test:"
echo "  curl https://explorer.d-bis.org/api/v2/stats"
echo ""

