#!/bin/sh
# alpha-stats - YOUR machine, right now: disk, CPU load, memory.
# Every figure is read live from this machine. Anything this shell
# cannot read is said plainly - never guessed, never invented.
_HOME="${ALPHA_HOME:-$HOME/.alpha-shell}"
echo "YOUR MACHINE, RIGHT NOW"
echo
# Disk (the filesystem your home folder lives on)
if command -v df >/dev/null 2>&1; then
  LINE=$(df -P "$HOME" 2>/dev/null | awk 'NR==2')
  if [ -n "$LINE" ]; then
    SIZE=$(echo "$LINE" | awk '{print $2}')
    USED=$(echo "$LINE" | awk '{print $3}')
    AVAIL=$(echo "$LINE" | awk '{print $4}')
    PCT=$(echo "$LINE" | awk '{print $5}')
    echo "Disk:  $PCT full - $(expr $AVAIL / 1024 2>/dev/null || echo '?') MB free"
    echo "       (of $(expr $SIZE / 1024 2>/dev/null || echo '?') MB total on your home filesystem)"
  else
    echo "Disk:  could not be read in this shell."
  fi
else
  echo "Disk:  no df tool in this shell, so no figure is shown."
fi
echo
# CPU load
if [ -r /proc/loadavg ]; then
  LOAD=$(awk '{print $1}' /proc/loadavg)
  echo "CPU:   load average (last minute) is $LOAD"
  echo "       (near 0 = idle; around the number of your CPU cores = fully busy)"
elif command -v uptime >/dev/null 2>&1; then
  echo "CPU:   $(uptime | sed 's/.*load/load/')"
else
  echo "CPU:   load cannot be read in this shell."
fi
NCPU=""
if command -v nproc >/dev/null 2>&1; then NCPU=$(nproc 2>/dev/null); fi
if [ -z "$NCPU" ] && [ -r /proc/cpuinfo ]; then NCPU=$(grep -c '^processor' /proc/cpuinfo 2>/dev/null); fi
[ -n "$NCPU" ] && echo "       CPU cores visible here: $NCPU"
echo
# Memory
if [ -r /proc/meminfo ]; then
  TOT=$(awk '/^MemTotal:/{print int($2/1024)}' /proc/meminfo)
  AVA=$(awk '/^MemAvailable:/{print int($2/1024)}' /proc/meminfo)
  if [ -n "$TOT" ] && [ -n "$AVA" ]; then
    echo "Memory: $AVA MB free of $TOT MB total"
  else
    echo "Memory: figures could not be read in this shell."
  fi
elif command -v free >/dev/null 2>&1; then
  echo "Memory: $(free -m | awk 'NR==2{print $7" MB free of "$2" MB total"}')"
else
  echo "Memory: cannot be read in this shell."
fi
