#!/bin/bash
# Redbull Health Check Script
# Usage: ./health-check.sh

set -e

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

TOKEN="2|tjaxz6z6osQUz6whMvNMw23kcBqgToQAvMjSLos347164da9"
COOLIFY_URL="https://redbull.rede5.com.br"
SSH_HOST="redbull"

echo "=============================================="
echo "       REDBULL HEALTH CHECK"
echo "=============================================="
echo ""

# Check SSH connection
echo -n "🔌 SSH Connection: "
if ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no $SSH_HOST "echo ok" &>/dev/null; then
    echo -e "${GREEN}OK${NC}"
else
    echo -e "${RED}FAILED${NC}"
    exit 1
fi

echo ""
echo "📦 Containers Docker:"
echo "-------------------------------------------"
ssh -o ConnectTimeout=5 -o StrictHostKeyChecking=no $SSH_HOST "docker ps --format '{{.Names}}:{{.Status}}'" 2>/dev/null | while read line; do
    if echo "$line" | grep -q "healthy\|Up"; then
        echo -e "  ${GREEN}✓${NC} $line"
    else
        echo -e "  ${RED}✗${NC} $line"
    fi
done

echo ""
echo "🌐 Aplicações Coolify:"
echo "-------------------------------------------"
APPS=$(curl -s -H "Authorization: Bearer $TOKEN" "$COOLIFY_URL/api/v1/applications" 2>/dev/null || echo "[]")
echo "$APPS" | python -c "
import json,sys,os
try:
    d = json.load(sys.stdin)
    for a in d:
        status = a.get('status','unknown')
        if 'running' in status:
            icon = '${GREEN}✓${NC}'
        else:
            icon = '${RED}✗${NC}'
        print(f'  {icon} {a[\"name\"]}: {status}')
except Exception as e:
    print(f'  Erro ao buscar dados: {e}')
" 2>/dev/null || echo -e "  ${RED}Erro ao conectar com API${NC}"

echo ""
echo "=============================================="
echo "       FIM DO HEALTH CHECK"
echo "=============================================="
