#!/usr/bin/env bash
# Start all stopped containers on r630-02
# This script fixes storage issues and starts all containers
# Usage: ./scripts/start-all-r630-02.sh

set -euo pipefail

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

# Configuration
NODE_IP="192.168.11.12"
NODE_NAME="r630-02"

# 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"; }

echo ""
log_info "═══════════════════════════════════════════════════════════"
log_info "  STARTING ALL CONTAINERS ON $NODE_NAME"
log_info "═══════════════════════════════════════════════════════════"
echo ""

# Get all stopped containers
log_info "Finding stopped containers..."
STOPPED_VMIDS=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
    "pct list 2>/dev/null | tail -n +2 | awk '\$2 == \"stopped\" {print \$1}'" || echo "")

if [[ -z "$STOPPED_VMIDS" ]]; then
    log_success "✅ All containers are already running"
    exit 0
fi

STOPPED_COUNT=$(echo "$STOPPED_VMIDS" | wc -l)
log_info "Found $STOPPED_COUNT stopped container(s)"
echo ""

# Convert to array
mapfile -t STOPPED_ARRAY <<< "$STOPPED_VMIDS"

# Process each stopped container
for vmid in "${STOPPED_ARRAY[@]}"; do
    if [[ -z "$vmid" ]]; then
        continue
    fi
    
    log_info "Processing VMID $vmid..."
    
    # Get container info
    hostname=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
        "pct config $vmid 2>/dev/null | grep -oP 'hostname=\\K[^,]+' | head -1" || echo "unknown")
    
    log_info "  Hostname: $hostname"
    
    # Check storage configuration
    rootfs=$(ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
        "pct config $vmid 2>/dev/null | grep '^rootfs:'" || echo "")
    
    if [[ -n "$rootfs" ]]; then
        # Check if using wrong storage pool
        if echo "$rootfs" | grep -q "thin1:" && ! echo "$rootfs" | grep -q "thin1-r630-02"; then
            log_warn "  Storage issue detected: using 'thin1' instead of 'thin1-r630-02'"
            
            # Extract storage details
            storage_line=$(echo "$rootfs" | sed 's/^rootfs: //')
            storage_pool=$(echo "$storage_line" | cut -d':' -f1)
            storage_volume=$(echo "$storage_line" | cut -d':' -f2 | cut -d',' -f1)
            storage_size=$(echo "$storage_line" | grep -oP 'size=\\K[^,]+' || echo "")
            
            if [[ "$storage_pool" == "thin1" ]] && [[ -n "$storage_volume" ]]; then
                log_info "  Fixing storage: thin1 → thin1-r630-02"
                
                if [[ -n "$storage_size" ]]; then
                    new_rootfs="thin1-r630-02:$storage_volume,size=$storage_size"
                else
                    new_rootfs="thin1-r630-02:$storage_volume"
                fi
                
                if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
                    "pct set $vmid -rootfs $new_rootfs" 2>&1; then
                    log_success "  ✅ Storage fixed"
                else
                    log_error "  ❌ Failed to fix storage"
                    continue
                fi
            fi
        fi
    fi
    
    # Start container
    log_info "  Starting container..."
    if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
        "pct start $vmid" 2>&1; then
        log_success "  ✅ Container $vmid ($hostname) started"
        sleep 2
    else
        log_error "  ❌ Failed to start container $vmid"
        # Show error details
        ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
            "pct start $vmid 2>&1" || true
    fi
    
    echo ""
done

# Wait for services to initialize
log_info "Waiting 5 seconds for services to initialize..."
sleep 5

# Show final status
log_info "Final container status:"
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no root@${NODE_IP} \
    "pct list 2>/dev/null | tail -n +2 | awk '{printf \"  VMID %s (%s): %s\\n\", \$1, \$3, \$2}'" || true

echo ""
log_success "═══════════════════════════════════════════════════════════"
log_success "  START COMPLETE"
log_success "═══════════════════════════════════════════════════════════"
echo ""
