#!/bin/bash
# Review All LXC Containers on r630-02 and Services Running on Them
# Host: 192.168.11.12 (r630-02)

set -euo pipefail

PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.12}"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
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"; }
log_section() { echo -e "${CYAN}════════════════════════════════════════${NC}"; }

echo "=========================================="
echo "LXC Containers Review - r630-02"
echo "Host: $PROXMOX_HOST"
echo "=========================================="
echo ""

# Function to execute command in container
exec_container() {
    local vmid=$1
    shift
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 root@"$PROXMOX_HOST" "pct exec $vmid -- bash -c '$*'" 2>&1 || echo "COMMAND_FAILED"
}

# Get list of all containers
log_info "Fetching container list..."
CONTAINER_LIST=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct list" 2>&1)

if [ -z "$CONTAINER_LIST" ]; then
    log_error "Cannot access Proxmox host or no containers found"
    exit 1
fi

# Parse container list (skip header)
CONTAINERS=$(echo "$CONTAINER_LIST" | awk 'NR>1 {print $1}')

TOTAL_COUNT=$(echo "$CONTAINERS" | wc -l)
RUNNING_COUNT=$(echo "$CONTAINER_LIST" | awk 'NR>1 && $2=="running" {count++} END {print count+0}')

log_success "Found $TOTAL_COUNT containers ($RUNNING_COUNT running)"
echo ""

# Process each container
for VMID in $CONTAINERS; do
    if [ -z "$VMID" ]; then
        continue
    fi
    
    log_section
    log_info "Container VMID: $VMID"
    
    # Get container info
    CONTAINER_INFO=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct list | grep '^$VMID'" 2>&1)
    if [ -z "$CONTAINER_INFO" ]; then
        log_warn "Could not get info for VMID $VMID"
        continue
    fi
    
    STATUS=$(echo "$CONTAINER_INFO" | awk '{print $2}')
    NAME=$(echo "$CONTAINER_INFO" | awk '{print $3}')
    
    echo "  Name: $NAME"
    echo "  Status: $STATUS"
    
    if [ "$STATUS" != "running" ]; then
        log_warn "Container is not running, skipping service check"
        echo ""
        continue
    fi
    
    # Check IP address if available
    IP=$(exec_container "$VMID" "hostname -I | awk '{print \$1}'" 2>&1 | head -1)
    if [ -n "$IP" ] && [ "$IP" != "COMMAND_FAILED" ]; then
        echo "  IP: $IP"
    fi
    
    # Check system services
    echo ""
    log_info "  System Services:"
    
    # Common services to check
    SERVICES_TO_CHECK="nginx apache2 docker blockscout cloudflared postgresql mysql redis"
    
    for SERVICE in $SERVICES_TO_CHECK; do
        SERVICE_STATUS=$(exec_container "$VMID" "systemctl is-active $SERVICE 2>/dev/null || echo inactive" 2>&1)
        if [ "$SERVICE_STATUS" = "active" ]; then
            echo "    ✓ $SERVICE: active"
        elif [ "$SERVICE_STATUS" != "inactive" ] && [ "$SERVICE_STATUS" != "COMMAND_FAILED" ]; then
            echo "    - $SERVICE: $SERVICE_STATUS"
        fi
    done
    
    # Check Docker if available
    DOCKER_CHECK=$(exec_container "$VMID" "command -v docker >/dev/null 2>&1 && echo 'yes' || echo 'no'" 2>&1)
    if echo "$DOCKER_CHECK" | grep -q "yes"; then
        echo ""
        log_info "  Docker Containers:"
        DOCKER_PS=$(exec_container "$VMID" "docker ps --format 'table {{.Names}}\t{{.Status}}\t{{.Image}}' 2>&1" | head -10)
        if [ -n "$DOCKER_PS" ] && ! echo "$DOCKER_PS" | grep -q "COMMAND_FAILED"; then
            echo "$DOCKER_PS" | sed 's/^/    /'
        fi
    fi
    
    # Check running processes (top processes by CPU)
    echo ""
    log_info "  Top Processes (by CPU):"
    TOP_PROCS=$(exec_container "$VMID" "ps aux --sort=-%cpu | head -6 | tail -5 | awk '{printf \"%-30s %6s%%\\n\", \$11, \$3}'" 2>&1)
    if [ -n "$TOP_PROCS" ] && ! echo "$TOP_PROCS" | grep -q "COMMAND_FAILED"; then
        echo "$TOP_PROCS" | sed 's/^/    /'
    fi
    
    # Check disk usage
    DISK_USAGE=$(exec_container "$VMID" "df -h / | tail -1 | awk '{print \"Used: \" \$3 \"/\" \$2 \" (\" \$5 \" full)\"}'" 2>&1)
    if [ -n "$DISK_USAGE" ] && ! echo "$DISK_USAGE" | grep -q "COMMAND_FAILED"; then
        echo ""
        log_info "  Disk Usage:"
        echo "    $DISK_USAGE"
    fi
    
    echo ""
done

log_section
log_info "Review Complete"
log_success "Processed $TOTAL_COUNT containers"
