#!/bin/bash
# Module 1-2: Quick Summary + System Health

HOSTNAME=$(hostname)
UPTIME=$(uptime -p)
KERNEL=$(uname -r)
OS=$(lsb_release -d | cut -f2- 2>/dev/null || echo "Ubuntu")
MEMORY_USED=$(free -h | awk '/^Mem:/ {print $3}')
MEMORY_TOTAL=$(free -h | awk '/^Mem:/ {print $2}')
DISK_USED=$(df -h / | awk 'NR==2 {print $3}')
DISK_TOTAL=$(df -h / | awk 'NR==2 {print $2}')
DISK_PERCENT=$(df -h / | awk 'NR==2 {print $5}')
CONTAINERS_RUNNING=$(docker ps -q | wc -l)
CONTAINERS_TOTAL=$(docker ps -aq | wc -l)
CONTAINERS_UNHEALTHY=$(docker ps --filter "health=unhealthy" -q 2>/dev/null | wc -l)
DB_SIZE=$(du -sh /mnt/psql-data 2>/dev/null | cut -f1 || echo "0")
BACKUP_SIZE=$(du -sh /mnt/backups 2>/dev/null | cut -f1 || echo "0")
NETWORKS_COUNT=$(docker network ls | grep -v NETWORK | wc -l)

cat << EOF
## 1️⃣ QUICK SUMMARY

### System Overview

| **Metric** | **Value** |
|------------|-----------|
| **Hostname** | $HOSTNAME |
| **Uptime** | $UPTIME |
| **OS** | $OS |
| **Kernel** | $KERNEL |
| **Memory** | $MEMORY_USED / $MEMORY_TOTAL |
| **Disk (/)** | $DISK_USED / $DISK_TOTAL ($DISK_PERCENT) |
| **Docker Containers** | $CONTAINERS_RUNNING running / $CONTAINERS_TOTAL total |
| **Unhealthy Containers** | $CONTAINERS_UNHEALTHY |
| **Databases Size** | $DB_SIZE |
| **Backups Size** | $BACKUP_SIZE |
| **Docker Networks** | $NETWORKS_COUNT |

---

## 2️⃣ SYSTEM HEALTH

### Critical Services Status

| Service | Status | Health | Notes |
|---------|--------|--------|-------|
EOF

for service in traefik postgres-main redis-main vault; do
    if docker ps --format '{{.Names}}' | grep -q "^${service}$"; then
        HEALTH=$(docker inspect --format='{{.State.Health.Status}}' "$service" 2>/dev/null || echo "none")
        
        if [[ "$HEALTH" == "unhealthy" ]]; then
            STATUS="🔴 Running"; NOTES="Check logs: docker logs $service"
        elif [[ "$HEALTH" == "healthy" ]]; then
            STATUS="🟢 Healthy"; NOTES="OK"
        else
            STATUS="🟡 Running"; HEALTH="no healthcheck"; NOTES="Running normally"
        fi
        
        echo "| **$service** | $STATUS | $HEALTH | $NOTES |"
    else
        echo "| **$service** | ⚫ Stopped | - | **CRITICAL** |"
    fi
done

echo ""
echo "---"
echo ""
