#!/bin/bash
# Update Cloudflare Tunnel Token in VMID 102
# The service is already running but with a different token

set -e

VMID=102
NEW_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 "  UPDATING CLOUDFLARE TUNNEL TOKEN IN VMID 102"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Check current service
log_info "Checking current cloudflared service..."
CURRENT_SERVICE=$(pct exec $VMID -- cat /etc/systemd/system/cloudflared.service 2>&1)
echo "$CURRENT_SERVICE" | grep -i "tunnel run" || log_warn "Could not read service file"

# Stop service
log_info "Stopping cloudflared service..."
pct exec $VMID -- systemctl stop cloudflared

# Update service file with new token
log_info "Updating service with new token..."
pct exec $VMID -- bash -c "cat > /etc/systemd/system/cloudflared.service << 'EOF'
[Unit]
Description=cloudflared
After=network.target

[Service]
Type=simple
User=root
ExecStart=/usr/bin/cloudflared --no-autoupdate tunnel run --token $NEW_TOKEN
Restart=on-failure
RestartSec=5s

[Install]
WantedBy=multi-user.target
EOF"

# Reload systemd
log_info "Reloading systemd..."
pct exec $VMID -- systemctl daemon-reload

# Start service
log_info "Starting cloudflared service with new token..."
pct exec $VMID -- systemctl start cloudflared

sleep 5

# Check status
log_info "Checking service status..."
pct exec $VMID -- systemctl status cloudflared --no-pager -l | head -20

# Verify token in service
log_info "Verifying token in service..."
pct exec $VMID -- grep -o "token [^ ]*" /etc/systemd/system/cloudflared.service | head -1

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

