#!/bin/bash
# Read-only server health check. Safe: no writes outside /tmp.
export LC_ALL=C
line() { printf '\n----- %s -----\n' "$1"; }

line "SYSTEM"
printf 'host: %s\n' "$(hostname -f 2>/dev/null || hostname)"
printf 'os: %s\n' "$(. /etc/os-release; echo "$PRETTY_NAME")"
printf 'kernel: %s\n' "$(uname -r)"
printf 'uptime: %s\n' "$(uptime -p 2>/dev/null)"
printf 'load: %s (cpus: %s)\n' "$(cut -d' ' -f1-3 /proc/loadavg)" "$(nproc)"
printf 'time: %s\n' "$(date '+%Y-%m-%d %H:%M:%S %Z')"

line "MEMORY"
free -h | sed -n '1,3p'

line "DISK"
df -hT -x tmpfs -x devtmpfs | sed -n '1,10p'

line "SERVICES"
for s in apache2 mysql mariadb php8.1-fpm ssh ufw fail2ban cron docker redis-server; do
  st=$(systemctl is-active "$s" 2>/dev/null)
  en=$(systemctl is-enabled "$s" 2>/dev/null)
  [ -n "$st" ] && printf '%-14s %-10s %s\n' "$s" "$st" "$en"
done

line "LISTENING PORTS"
ss -tlnp 2>/dev/null | awk 'NR==1 || /LISTEN/' | sed 's/  */ /g' | cut -c1-120 | head -25

line "WEB STACK"
apache2 -v 2>/dev/null | head -2
php -v 2>/dev/null | head -1
printf 'vhosts: %s files\n' "$(ls /etc/apache2/sites-enabled/ 2>/dev/null | wc -l)"
ls /etc/apache2/sites-enabled/ 2>/dev/null | sed 's/^/  /'

line "DOCUMENT ROOTS"
ls -la /var/www/ 2>/dev/null
du -sh /var/www/* 2>/dev/null | sort -rh | head -8

line "APACHE ERRORS (last 12)"
tail -n 12 /var/log/apache2/error.log 2>/dev/null || echo "(no error.log)"

line "TLS CERTS"
for c in $(grep -rlE 'SSLCertificateFile' /etc/apache2/sites-enabled/ 2>/dev/null | head -3); do
  f=$(grep -oE 'SSLCertificateFile\s+\S+' "$c" | awk '{print $2}' | head -1)
  [ -f "$f" ] && printf '%s -> %s\n' "$f" "$(openssl x509 -enddate -noout -in "$f" 2>/dev/null)"
done

line "FIREWALL"
if command -v ufw >/dev/null 2>&1; then ufw status 2>/dev/null | head -6; fi
iptables -S 2>/dev/null | head -10

line "LOGINS / AUTH FAILURES"
who 2>/dev/null | head -5
printf 'failed logins (24h): %s\n' "$(grep -c 'Failed password' /var/log/auth.log 2>/dev/null || echo 0)"
last -n 5 2>/dev/null | head -5

line "SECURITY UPDATES"
if command -v apt-get >/dev/null 2>&1; then
  printf 'reboot-required: %s\n' "$([ -f /var/run/reboot-required ] && echo YES || echo no)"
  printf 'upgradable pkgs: %s\n' "$(apt list --upgradable 2>/dev/null | grep -c upgradable)"
fi

line "TOP PROCESSES (memory)"
ps -eo pid,pcpu,pmem,rss,comm --sort=-pmem 2>/dev/null | head -8

line "END"
