#!/usr/bin/env bash
# Restart a Cloudflare tunnel service

set -euo pipefail

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

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

# Usage
if [ $# -lt 1 ]; then
    echo "Usage: $0 <tunnel-name>"
    echo ""
    echo "Tunnel names: ml110, r630-01, r630-02"
    exit 1
fi

TUNNEL_NAME="$1"

# Validate tunnel name
if [[ ! "$TUNNEL_NAME" =~ ^(ml110|r630-01|r630-02)$ ]]; then
    log_error "Invalid tunnel name: $TUNNEL_NAME"
    log_error "Valid names: ml110, r630-01, r630-02"
    exit 1
fi

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.10}"
VMID="${VMID:-102}"
SERVICE="cloudflared-${TUNNEL_NAME}"

# Check if running on Proxmox host
if command -v pct &> /dev/null; then
    RUN_LOCAL=true
else
    RUN_LOCAL=false
fi

exec_in_container() {
    local cmd="$1"
    if [ "$RUN_LOCAL" = true ]; then
        pct exec "$VMID" -- bash -c "$cmd"
    else
        ssh "root@${PROXMOX_HOST}" "pct exec $VMID -- bash -c '$cmd'"
    fi
}

log_info "Restarting tunnel: $TUNNEL_NAME"

# Check if service exists
if ! exec_in_container "systemctl list-unit-files | grep -q $SERVICE"; then
    log_error "Service $SERVICE not found"
    exit 1
fi

# Restart service
log_info "Stopping service..."
exec_in_container "systemctl stop $SERVICE" || log_warn "Service was not running"

sleep 2

log_info "Starting service..."
if exec_in_container "systemctl start $SERVICE"; then
    log_success "Service started"
    
    # Wait a moment and check status
    sleep 3
    if exec_in_container "systemctl is-active --quiet $SERVICE"; then
        log_success "Tunnel $TUNNEL_NAME is running"
    else
        log_error "Tunnel $TUNNEL_NAME failed to start"
        log_info "Check logs: journalctl -u $SERVICE -n 50"
        exit 1
    fi
else
    log_error "Failed to start service"
    log_info "Check logs: journalctl -u $SERVICE -n 50"
    exit 1
fi

