#!/bin/bash

# === CONFIG ===
REMOTE_USER="doc"
BOT_TOKEN="8178867489:AAH0VjN7VnZSCIWasSz_y97iBLLjPJA751k"
CHAT_ID="1559582356"
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
LOGFILE="$HOME/krang-logs/health-$(date '+%Y%m%d-%H%M').log"

# Thresholds
SWAP_LIMIT_MB=512
LOAD_LIMIT=4.0

mkdir -p "$HOME/krang-logs"

SERVERS=(
  thevault.sshjunkie.com
  zcluster.technodrome1.sshjunkie.com
  zcluster.technodrome2.sshjunkie.com
  shredder.sshjunkie.com
  chatwithus.live
)

SUMMARY="📡 Krang System Health Report - $TIMESTAMP\n\n"

for HOST in "${SERVERS[@]}"; do
  echo "🔍 Collecting from $HOST..."

  DATA=$(ssh "$REMOTE_USER@$HOST" bash -s << 'EOF'
HOST=$(hostname)
MEM=$(free -h | awk '/Mem:/ {print $4 " free"}')
SWAP_RAW=$(free -m | awk '/Swap:/ {print $3}')
SWAP="$SWAP_RAW Mi used"
DISK=$(df -h / | awk 'NR==2 {print $4 " free"}')
LOAD=$(uptime | awk -F'load average:' '{print $2}' | cut -d, -f1 | xargs)
APACHE=$(systemctl is-active apache2 2>/dev/null || systemctl is-active httpd 2>/dev/null)
[ "$APACHE" = "active" ] && APACHE_STATUS="✅ Apache running" || APACHE_STATUS="❌ Apache not running"

echo "$HOST|$MEM|$SWAP_RAW|$SWAP|$DISK|$LOAD|$APACHE_STATUS"
EOF
)

  IFS='|' read -r H MEM SWAP_MB SWAP_HUMAN DISK LOAD1 APACHE_STATUS <<< "$DATA"

  ALERTS=""
  if (( SWAP_MB > SWAP_LIMIT_MB )); then
    ALERTS+="⚠️ HIGH SWAP ($SWAP_HUMAN)\n"
  fi

  LOAD_INT=$(awk "BEGIN {print ($LOAD1 > $LOAD_LIMIT) ? 1 : 0}")
  if [ "$LOAD_INT" -eq 1 ]; then
    ALERTS+="⚠️ HIGH LOAD ($LOAD1)\n"
  fi

  ALERTS_MSG=""
  [ -n "$ALERTS" ] && ALERTS_MSG="🚨 ALERTS:\n$ALERTS"

  SUMMARY+="🖥️ $H
• Mem: $MEM
• Swap: $SWAP_HUMAN
• Disk: $DISK
• Load: $LOAD1
• $APACHE_STATUS
$ALERTS_MSG
\n"
done

# Log to file
echo -e "$SUMMARY" > "$LOGFILE"

# Send to Telegram
curl -s -X POST https://api.telegram.org/bot$BOT_TOKEN/sendMessage \
  -d chat_id="$CHAT_ID" \
  -d text="$SUMMARY"
