#!/bin/bash
# Install Cloudflare Tunnel using Proxmox API
# Alternative method when direct pct access fails

set -e

VMID=5000
TUNNEL_TOKEN="eyJhIjoiNTJhZDU3YTcxNjcxYzVmYzAwOWVkZjA3NDQ2NTgxOTYiLCJ0IjoiYjAyZmUxZmUtY2I3ZC00ODRlLTkwOWItN2NjNDEyOThlYmU4IiwicyI6Ik5HTmtOV0kwWXpNdFpUVmxaUzAwTVRFMkxXRXdNMk10WlRJNU1ETTFaRFF4TURBMiJ9"
PROXMOX_HOST="192.168.11.10"

# Colors
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
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"; }

echo ""
log_info "Installing Cloudflare Tunnel via Proxmox API"
echo ""

# Create installation script to run in container
INSTALL_SCRIPT=$(cat <<'SCRIPT_END'
#!/bin/bash
set -e

# Install cloudflared if needed
if ! command -v cloudflared >/dev/null 2>&1; then
    echo "Installing cloudflared..."
    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
    echo "cloudflared installed"
fi

# Install service
echo "Installing tunnel service..."
cloudflared service install eyJhIjoiNTJhZDU3YTcxNjcxYzVmYzAwOWVkZjA3NDQ2NTgxOTYiLCJ0IjoiYjAyZmUxZmUtY2I3ZC00ODRlLTkwOWItN2NjNDEyOThlYmU4IiwicyI6Ik5HTmtOV0kwWXpNdFpUVmxaUzAwTVRFMkxXRXdNMk10WlRJNU1ETTFaRFF4TURBMiJ9

# Start service
echo "Starting cloudflared service..."
systemctl start cloudflared
systemctl enable cloudflared

sleep 3

# Check status
echo "Service status:"
systemctl status cloudflared --no-pager -l | head -10

# List tunnels
echo "Tunnel list:"
cloudflared tunnel list
SCRIPT_END
)

# Save script to temp file
TEMP_SCRIPT="/tmp/install-cloudflared-$$.sh"
echo "$INSTALL_SCRIPT" > "$TEMP_SCRIPT"
chmod +x "$TEMP_SCRIPT"

# Copy script to container and execute
log_info "Copying installation script to container..."
ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "cat > /tmp/install-cloudflared.sh" < "$TEMP_SCRIPT"

log_info "Executing installation in container..."
# Try to execute via pvesh or direct SSH
ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pvesh create /nodes/pve2/lxc/5000/exec --command 'bash /tmp/install-cloudflared.sh' --output-format json" 2>&1 || \
ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "ssh pve2 'pct exec 5000 -- bash /tmp/install-cloudflared.sh'" 2>&1 || \
log_warn "Could not execute via API or SSH. Please run manually on pve2:"

echo ""
log_warn "If automated installation failed, run these commands on pve2:"
echo ""
echo "pct exec 5000 -- bash << 'EOF'"
echo "$INSTALL_SCRIPT"
echo "EOF"
echo ""

rm -f "$TEMP_SCRIPT"

