#!/usr/bin/env bash
# Read-only server health snapshot for systemd-based Linux hosts.
set -u

timestamp="$(date +%Y%m%d-%H%M%S)"
report="${1:-server-health-${timestamp}.log}"
warnings=0

section() {
  printf '\n## %s\n' "$1"
}

{
  printf 'Server health snapshot\nGenerated: %s\nHost: %s\n' \
    "$(date --iso-8601=seconds)" "$(hostname --fqdn 2>/dev/null || hostname)"

  section "Uptime and load"
  uptime

  section "Memory"
  free -h

  section "Filesystems"
  df -hT -x tmpfs -x devtmpfs

  section "Failed systemd units"
  if command -v systemctl >/dev/null 2>&1; then
    systemctl --failed --no-pager || true
  else
    printf 'systemctl is not installed\n'
  fi

  section "Listening sockets"
  if command -v ss >/dev/null 2>&1; then
    ss -lntup
  else
    printf 'ss is not installed\n'
  fi

  section "Recent critical events"
  if command -v journalctl >/dev/null 2>&1; then
    journalctl -p 0..3 --since "24 hours ago" --no-pager -n 100 || true
  else
    printf 'journalctl is not installed\n'
  fi
} > "$report" 2>&1

while read -r usage mountpoint; do
  percent="${usage%\%}"
  if [[ "$percent" =~ ^[0-9]+$ ]] && (( percent >= 85 )); then
    printf 'WARNING: %s is %s full\n' "$mountpoint" "$usage"
    ((warnings += 1))
  fi
done < <(df -P -x tmpfs -x devtmpfs | awk 'NR > 1 {print $5, $6}')

if command -v systemctl >/dev/null 2>&1; then
  failed_count="$(systemctl --failed --no-legend 2>/dev/null | wc -l)"
  if (( failed_count > 0 )); then
    printf 'WARNING: %s systemd unit(s) failed\n' "$failed_count"
    ((warnings += 1))
  fi
fi

printf 'Report: %s\nStatus: %s warning(s) found\n' "$report" "$warnings"
exit "$(( warnings > 0 ? 1 : 0 ))"
