#!/bin/bash
# Check services for a single container
# Usage: ./check-container-services.sh <VMID>

VMID=$1
PROXMOX_HOST="${PROXMOX_HOST:-192.168.11.12}"

if [ -z "$VMID" ]; then
    echo "Usage: $0 <VMID>"
    exit 1
fi

exec_container() {
    ssh -o StrictHostKeyChecking=no -o ConnectTimeout=3 root@"$PROXMOX_HOST" "pct exec $VMID -- bash -c '$*'" 2>&1
}

echo "=== VMID $VMID ==="
CONTAINER_INFO=$(ssh -o StrictHostKeyChecking=no root@"$PROXMOX_HOST" "pct list | grep '^$VMID'" 2>&1)
NAME=$(echo "$CONTAINER_INFO" | awk '{print $3}')
STATUS=$(echo "$CONTAINER_INFO" | awk '{print $2}')

echo "Name: $NAME"
echo "Status: $STATUS"

if [ "$STATUS" != "running" ]; then
    echo "Container not running"
    exit 0
fi

# Get IP
IP=$(exec_container "hostname -I | awk '{print \$1}'" 2>&1 | head -1)
echo "IP: ${IP:-unknown}"

# Check services
echo "Services:"
SERVICES="nginx apache2 docker blockscout cloudflared postgresql mysql mariadb redis gitea firefly"
for svc in $SERVICES; do
    STATUS_CHECK=$(exec_container "systemctl is-active $svc 2>/dev/null || echo 'inactive'" 2>&1)
    if [ "$STATUS_CHECK" = "active" ]; then
        echo "  ✓ $svc: active"
    fi
done

# Check Docker
DOCKER=$(exec_container "command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' | head -5 | tr '\n' ' ' || echo 'no'" 2>&1)
if [ "$DOCKER" != "no" ] && [ -n "$DOCKER" ]; then
    echo "  Docker containers: $DOCKER"
fi

# Disk usage
DISK=$(exec_container "df -h / | tail -1 | awk '{print \$5 \" (\" \$3 \"/\" \$2 \")\"}'" 2>&1)
echo "Disk usage: ${DISK:-unknown}"
