#!/bin/bash
# health_check.sh — system overview for Arch Linux
# Sections: System · CPU · RAM · Battery · Disk health · Disk space · Docker · Network · Summary

# ══ HELPERS ═══════════════════════════════════════════════
CYAN='\033[0;36m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
BOLD='\033[1m'
RESET='\033[0m'

warnings=0
problems=0

section() { echo -e "\n${BOLD}${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n $1${RESET}"; }
ok()    { echo -e "  ${GREEN}✔ $1${RESET}"; }
warn()  { echo -e "  ${YELLOW}⚠ $1${RESET}"; warnings=$(( warnings + 1 )); }
bad()   { echo -e "  ${RED}✘ $1${RESET}"; problems=$(( problems + 1 )); }
info()  { echo -e "  $1"; }
title() { echo -e "\n  ${BOLD}$1${RESET}"; }
has()   { command -v "$1" &>/dev/null; }

# grade_high <value> <warn_at> <bad_at> <message>   — higher is worse
grade_high() {
    if   (( $1 >= $3 )); then bad "$4"
    elif (( $1 >= $2 )); then warn "$4"
    else ok "$4"; fi
}
# grade_low <value> <warn_at> <bad_at> <message>    — lower is worse
grade_low() {
    if   (( $1 <= $3 )); then bad "$4"
    elif (( $1 <= $2 )); then warn "$4"
    else ok "$4"; fi
}

mem()   { awk -v k="$1:" '$1==k {print $2}' /proc/meminfo; }                     # value in kB
human() { numfmt --to=iec-i --suffix=B --format="%.1f" $(( ${1:-0} * 1024 )); }  # kB → human

sudo -v 2>/dev/null   # ask for the password once, up front

# ══ SYSTEM ════════════════════════════════════════════════
section "🖥  SYSTEM"
info "Hostname:  $(cat /proc/sys/kernel/hostname)"
info "OS:        $(. /etc/os-release 2>/dev/null && echo "$PRETTY_NAME")"
info "Kernel:    $(uname -r)"
[ -n "$XDG_CURRENT_DESKTOP" ] && info "Desktop:   $XDG_CURRENT_DESKTOP (${XDG_SESSION_TYPE:-unknown})"
info "Uptime:    $(uptime -p | sed 's/^up //')"
info "Last boot: $(who -b | awk '{print $3, $4}')"

# Running kernel no longer on disk = kernel was upgraded since boot
if [ ! -d "/usr/lib/modules/$(uname -r)" ]; then
    warn "Kernel was updated — reboot needed"
fi

if has pacman; then
    title "Packages"
    info "Installed: $(pacman -Qq | wc -l) ($(pacman -Qqe | wc -l) explicit, $(pacman -Qqm | wc -l) AUR/foreign)"

    last_upgrade=$(grep -a 'starting full system upgrade' /var/log/pacman.log 2>/dev/null | tail -1 | grep -oP '^\[\K[0-9-]+')
    if [ -n "$last_upgrade" ]; then
        days=$(( ( $(date +%s) - $(date -d "$last_upgrade" +%s) ) / 86400 ))
        info "Last full upgrade: $last_upgrade ($days day(s) ago)"
    fi

    if has checkupdates; then
        updates=$(checkupdates 2>/dev/null | wc -l)
        (( updates == 0 )) && ok "Repos: up to date" || warn "Repos: $updates package(s) to update"
    else
        info "Repos: install 'pacman-contrib' to check for updates"
    fi

    if has yay; then
        aur_updates=$(yay -Qua 2>/dev/null | wc -l)
        (( aur_updates == 0 )) && ok "AUR: up to date" || warn "AUR: $aur_updates package(s) to update"
    fi

    orphans=$(pacman -Qdtq 2>/dev/null | wc -l)
    (( orphans == 0 )) && ok "Orphans: none" || warn "Orphans: $orphans package(s) (cleanup.sh removes them)"
fi

if has systemctl; then
    title "Services"
    failed=$(systemctl --failed --no-legend --plain 2>/dev/null | awk '{print $1}')
    if [ -z "$failed" ]; then
        ok "No failed services"
    else
        while read -r unit; do bad "Failed: $unit"; done <<< "$failed"
    fi
    journal_errors=$(journalctl -b -p 3 -q --no-pager 2>/dev/null | wc -l)
    info "Journal errors this boot: $journal_errors (see: journalctl -b -p 3)"
fi

# ══ CPU ═══════════════════════════════════════════════════
section "🧠 CPU"
cores=$(nproc)
info "Model:     $(awk -F': ' '/model name/ {print $2; exit}' /proc/cpuinfo)"
info "Cores:     $cores"
gov=/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor
[ -r "$gov" ] && info "Governor:  $(cat "$gov")"

cpu_temp=$(sensors 2>/dev/null | grep -E "Package id 0|Core 0|Tctl|CPU" | head -1 | grep -oP '[0-9]+\.[0-9]+(?=°C)' | head -1)
if [ -n "$cpu_temp" ]; then
    grade_high "${cpu_temp%.*}" 70 90 "Temperature: ${cpu_temp}°C"
else
    info "Temperature: install 'lm_sensors' + run 'sudo sensors-detect'"
fi

read -r load1 load5 load15 _ < /proc/loadavg
# Load above the core count means processes are queueing for CPU
grade_high "${load1%.*}" "$cores" $(( cores * 2 )) "Load:      $load1 / $load5 / $load15 (1 / 5 / 15 min)"

title "Top 5 apps by CPU"
while read -r cpu count name; do
    info "$(printf '%-22.22s %6s %%  (%d proc)' "$name" "$cpu" "$count")"
done < <(ps -eo pcpu=,comm= | awk '{c[$2]+=$1; n[$2]++} END {for (k in c) printf "%.1f %d %s\n", c[k], n[k], k}' | sort -rn | head -5)

# ══ RAM ═══════════════════════════════════════════════════
section "🧩 RAM"
mem_total=$(mem MemTotal)
mem_avail=$(mem MemAvailable)
mem_used=$(( mem_total - mem_avail ))
mem_cache=$(( $(mem Buffers) + $(mem Cached) + $(mem SReclaimable) ))
pct_ram=$(( mem_used * 100 / mem_total ))

info "Total:     $(human "$mem_total")"
grade_high "$pct_ram" 70 90 "Used:      $(human "$mem_used") (${pct_ram}%)"
info "Available: $(human "$mem_avail")"
info "Free:      $(human "$(mem MemFree)") (completely unused)"
info "Cache:     $(human "$mem_cache") (reclaimable)"
info "Shared:    $(human "$(mem Shmem)") (tmpfs / shared memory)"

swap_total=$(mem SwapTotal)
if (( swap_total > 0 )); then
    swap_used=$(( swap_total - $(mem SwapFree) ))
    pct_swap=$(( swap_used * 100 / swap_total ))
    grade_high "$pct_swap" 50 80 "Swap:      $(human "$swap_used") / $(human "$swap_total") (${pct_swap}%)"
    while read -r name type prio; do
        info "  → $name ($type, priority $prio)"
    done < <(swapon --show=NAME,TYPE,PRIO --noheadings 2>/dev/null)
    info "Swappiness: $(cat /proc/sys/vm/swappiness)"
else
    warn "Swap:      none configured"
fi

# Pressure = % of time processes were stalled waiting for memory
if [ -r /proc/pressure/memory ]; then
    psi10=$(awk '/^some/ {sub("avg10=","",$2); print $2}' /proc/pressure/memory)
    psi300=$(awk '/^some/ {sub("avg300=","",$4); print $4}' /proc/pressure/memory)
    grade_high "${psi10%.*}" 10 25 "Pressure:  ${psi10}% (10s) / ${psi300}% (5min)"
fi

oom=$(awk '$1=="oom_kill" {print $2}' /proc/vmstat)
if [ -n "$oom" ]; then
    (( oom > 0 )) && bad "OOM kills since boot: $oom" || ok "OOM kills since boot: 0"
fi

title "Top 5 apps by RAM"
while read -r rss count name; do
    info "$(printf '%-22.22s %6d MB  (%d proc)' "$name" $(( rss / 1024 )) "$count")"
done < <(ps -eo rss=,comm= | awk '{r[$2]+=$1; n[$2]++} END {for (k in r) printf "%d %d %s\n", r[k], n[k], k}' | sort -rn | head -5)

title "Modules"
if has dmidecode; then
    while read -r line; do info "$line"; done < <(sudo dmidecode -t memory 2>/dev/null | awk -F': ' '
        function flush() {
            if (dev) {
                if (size ~ /No Module/) printf "%s: empty\n", loc
                else printf "%s: %s %s @ %s\n", loc, size, type, speed
            }
            dev=0; size=""; type=""; speed=""; loc=""
        }
        /^Memory Device/ {dev=1}
        /^\tSize:/       {size=$2}
        /^\tType:/       {type=$2}
        /^\tSpeed:/      {speed=$2}
        /^\tLocator:/    {loc=$2}
        /^$/             {flush()}
        END              {flush()}')
else
    info "install 'dmidecode' to list RAM modules"
fi

# ══ BATTERY ═══════════════════════════════════════════════
section "🔋 BATTERY"
bat=$(find /sys/class/power_supply -maxdepth 1 -name "BAT*" 2>/dev/null | head -1)
batval() { cat "$bat/$1" 2>/dev/null; }

if [ -n "$bat" ]; then
    status=$(batval status)
    capacity=$(batval capacity)

    model="$(batval manufacturer) $(batval model_name)"
    [ -n "${model// /}" ] && info "Model:     $model ($(batval technology))"

    if [ -n "$capacity" ]; then
        if [ "$status" = "Discharging" ]; then
            grade_low "$capacity" 20 10 "Charge:    ${capacity}% ($status)"
        else
            ok "Charge:    ${capacity}% ($status)"
        fi
    fi

    # Batteries report either energy_* (µWh) or charge_* (µAh)
    if [ -r "$bat/energy_full" ]; then kind=energy; unit="Wh"; else kind=charge; unit="Ah"; fi
    full=$(batval "${kind}_full")
    design=$(batval "${kind}_full_design")
    now=$(batval "${kind}_now")

    if [ -n "$full" ] && [ -n "$design" ] && (( design > 0 )); then
        health_pct=$(( full * 100 / design ))
        grade_low "$health_pct" 80 60 "Health:    ${health_pct}% of design capacity"
        info "Capacity:  $(awk -v f="$full" -v d="$design" 'BEGIN {printf "%.1f / %.1f", f/1e6, d/1e6}') $unit (now / new)"
    else
        info "Health:    not reported by this battery"
    fi

    cycles=$(batval cycle_count)
    [ -n "$cycles" ] && (( cycles > 0 )) && info "Cycles:    $cycles"

    # Power draw and time estimate
    if [ "$kind" = energy ]; then rate=$(batval power_now); else rate=$(batval current_now); fi
    if [ -n "$rate" ] && (( rate > 0 )); then
        if [ "$kind" = energy ]; then
            info "Power:     $(awk -v r="$rate" 'BEGIN {printf "%.1f", r/1e6}') W"
        fi
        if [ "$status" = "Discharging" ] && [ -n "$now" ]; then
            info "Remaining: $(awk -v n="$now" -v r="$rate" 'BEGIN {h=n/r; printf "%dh %02dm", h, (h-int(h))*60}')"
        elif [ "$status" = "Charging" ] && [ -n "$now" ] && [ -n "$full" ]; then
            info "Until full: $(awk -v n="$now" -v f="$full" -v r="$rate" 'BEGIN {h=(f-n)/r; printf "%dh %02dm", h, (h-int(h))*60}')"
        fi
    fi

    limit=$(batval charge_control_end_threshold)
    [ -n "$limit" ] && info "Charge limit: ${limit}%"
else
    info "No battery detected"
fi

# ══ DISK HEALTH ═══════════════════════════════════════════
section "💽 DISK HEALTH (SMART)"
root_part=$(findmnt -no SOURCE / 2>/dev/null | sed 's/\[.*//')
parent=$(lsblk -no PKNAME "$root_part" 2>/dev/null | head -1)
disk=${parent:+/dev/$parent}
disk=${disk:-$root_part}

if ! has smartctl; then
    info "install 'smartmontools' to read SMART data"
else
    smart=$(sudo smartctl -a "$disk" 2>/dev/null)
    smartval() { echo "$smart" | grep -m1 "$1" | awk -F': *' '{print $2}'; }

    info "Device:    $disk — $(smartval 'Model Number:')"

    health=$(smartval "SMART overall")
    [ "$health" = "PASSED" ] && ok "Overall:   $health" || bad "Overall:   ${health:-unknown}"

    temp=$(smartval "^Temperature:" | awk '{print $1}')
    [ -n "$temp" ] && grade_high "$temp" 60 75 "Temperature: ${temp}°C"

    spare=$(smartval "Available Spare:" | tr -d '%')
    [ -n "$spare" ] && grade_low "$spare" 50 10 "Available spare: ${spare}%"

    wear=$(smartval "Percentage Used:" | tr -d '%')
    [ -n "$wear" ] && grade_high "$wear" 50 80 "Wear:      ${wear}%"

    errors=$(smartval "Media and Data Integrity Errors:")
    [ "$errors" = "0" ] && ok "Media errors: 0" || bad "Media errors: ${errors:-unknown}"

    info "Power-on hours:   $(smartval 'Power On Hours:')"
    info "Data written:     $(smartval 'Data Units Written:' | grep -oP '\[\K[^\]]+')"
    info "Unsafe shutdowns: $(smartval 'Unsafe Shutdowns:') (lifetime)"
fi

# ══ DISK SPACE ════════════════════════════════════════════
section "📦 DISK SPACE"
while read -r fs size used avail pct mount; do
    grade_high "${pct%\%}" 70 90 "$mount — $used / $size (${pct}, $avail free)"
done < <(df -h | grep -E '^/dev/')

# ══ DOCKER ════════════════════════════════════════════════
section "🐳 DOCKER"
if ! has docker; then
    info "Docker not installed"
elif systemctl is-active --quiet docker 2>/dev/null; then
    running=$(docker ps --format "{{.Names}} ({{.Status}})" 2>/dev/null)
    if [ -n "$running" ]; then
        ok "Running — $(echo "$running" | wc -l) container(s) up"
        while read -r line; do info "  → $line"; done <<< "$running"
    else
        ok "Running — no containers up"
    fi
    while read -r line; do info "$line"; done < <(docker system df 2>/dev/null)
else
    info "Docker service is stopped"
fi

# ══ NETWORK ═══════════════════════════════════════════════
section "🌐 NETWORK"
route=$(ip route get 1.1.1.1 2>/dev/null)
iface=$(echo "$route" | grep -oP 'dev \K\S+')
local_ip=$(echo "$route" | grep -oP 'src \K\S+')
gateway=$(echo "$route" | grep -oP 'via \K\S+')

info "Interface: ${iface:-not found}"
info "Local IP:  ${local_ip:-not found}"
info "Gateway:   ${gateway:-not found}"
info "DNS:       $(awk '/^nameserver/ {printf "%s ", $2}' /etc/resolv.conf 2>/dev/null)"

if has nmcli; then
    wifi=$(nmcli -t -f ACTIVE,SSID,SIGNAL dev wifi 2>/dev/null | awk -F: '$1=="yes" {print $2 " (signal " $3 "%)"}')
    [ -n "$wifi" ] && info "Wi-Fi:     $wifi"
fi

latency=$(ping -c 3 -W 2 -q 8.8.8.8 2>/dev/null | awk -F'/' '/^rtt|^round-trip/ {print $5}')
if [ -n "$latency" ]; then
    ok "Internet:  connected (${latency} ms)"
else
    bad "Internet:  no connection"
fi

if getent hosts archlinux.org &>/dev/null; then
    ok "DNS lookup: working"
else
    bad "DNS lookup: failing"
fi

# ══ SUMMARY ═══════════════════════════════════════════════
section "📋 SUMMARY"
if (( problems == 0 && warnings == 0 )); then
    ok "All good"
else
    (( problems > 0 )) && echo -e "  ${RED}✘ $problems problem(s)${RESET}"
    (( warnings > 0 )) && echo -e "  ${YELLOW}⚠ $warnings warning(s)${RESET}"
fi

echo -e "\n${BOLD}${CYAN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${RESET}\n"
