#!/usr/bin/env bash

: <<'END'
sysinfo
system information for DigiHub

Version 0.2

Steve de Bode - W0FFS - July 2026

Input:  none
Output: none - informational
END

UI_LIB="/usr/local/lib/digihub/dh.lib"
[ -r "$UI_LIB" ] && source "$UI_LIB" || {
  printf "\nERROR: Missing UI library: %s\n\n" "$UI_LIB" >&2
  exit 1
}

# Model Information
if grep -q "Raspberry Pi" /proc/cpuinfo; then
  model=$(cat /sys/firmware/devicetree/base/model | tr -d '\0')
fi

# CPU Information
cpuname=$(lscpu | grep 'Model name' | awk '{ print $3 }')
cpucore=$(lscpu | grep 'Core(s) per cluster:' | awk '{ print $4 }')
if [ -z "$cpucore" ]; then
cpucore=$(lscpu | grep 'Core(s) per socket:' | awk '{ print $4 }')
fi
cpuspeed=$(lscpu | grep "max MHz" | awk '{ print $4 }' | cut -d. -f1)
cpuscale=$(lscpu | grep "scaling MHz" | awk '{ print $4 }')
cpuload=$({ head -n1 /proc/stat; sleep 0.2; head -n1 /proc/stat; } | awk '/^cpu /{u=$2-u;s=$4-s;i=$5-i;w=$6-w}END{print int(0.5+100*(u+s+w)/(u+s+i+w))"%"}')

# Memory Information
memtot=$(free -k | grep Mem | awk '{ print $2 }')
memtotgb=$(echo "scale=2; $memtot / 1024 / 1024" | bc)
memtotgb=$(printf "%.2f\n" "$memtotgb")
memuse=$(free -k | grep Mem | awk '{ print $3 }')
memusegb=$(echo "scale=2; $memuse / 1024 / 1024" | bc)
memusegb=$(printf "%.2f\n" "$memusegb")
memfre=$(free -k | grep Mem | awk '{ print $4 }')
memfregb=$(echo "scale=2; $memfre / 1024 / 1024" | bc)
memfregb=$(printf "%.2f\n" "$memfregb")
memfrepct=$(echo "scale=2; ($memfre * 100) / $memtot" | bc)

# Disk Information
disksize=$(df / | sed -n '2{p;q}' | awk '{ print $2 }')
diskused=$(df / | sed -n '2{p;q}' | awk '{ print $3 }')
diskavai=$(df / | sed -n '2{p;q}' | awk '{ print $4 }')
disksizegb=$(echo "scale=2; $disksize / 1024 / 1024" | bc)
diskusedgb=$(echo "scale=2; $diskused / 1024 / 1024" | bc)
diskavaigb=$(echo "scale=2; $diskavai / 1024 / 1024" | bc)
diskupct=$(df / | sed -n '2{p;q}' | awk '{ print $5 }')

# Uptime
up=$(cut -d . -f 1 /proc/uptime)

# Last Login
if [[ "$(cat /etc/os-release | grep PRETTY)" == *"bookworm"* ]]; then
  getlast=$(lastlog -u $USER | awk 'NR==2')
else
  getlast=$(lastlog2 -u $USER | awk 'NR==2')
fi
read -a lastinfo <<< "$getlast"
lastinfo[3]=$(date -d "${lastinfo[3]}" '+%A')
lastinfo[4]=$(date -d "${lastinfo[4]} 1" '+%B')

dd=$((up / 86400))
remsecs=$((up % 86400))

hh=$((remsecs / 3600))
remsecs=$((remsecs % 3600))

mm=$((remsecs / 60))
remsecs=$((remsecs % 60))

# DigiHub Installation Info
dhinfo="$HOME/.dhinfo"

if [ -r "$dhinfo" ]; then
  IFS=',' read -r callsign class expiry grid lat lon licstat \
                 forename initial surname suffix \
                 street town state zip country \
                 aprspass axnodepass mapboxtoken \
                 winlinkpass defaultmode radiointerface \
                 rigdevice rigbaud rignumber \
                 vncpass < "$dhinfo"
fi

# Output
clear

# Raspberry Pi specifics (if applicable)
if grep -q "Raspberry Pi" /proc/cpuinfo; then
  section "Hardware"
  kv "Model" "$model"
  kv "Serial Number" "$(grep Serial /proc/cpuinfo | awk '{print $3}')"
fi

section "System"
kv "Operating System" "$(grep PRETTY /etc/os-release | sed 's/^[^"]*"//' | tr -d '"')"
kv "Kernel" "$(uname -r)"
kv "Shell Version" "$BASH_VERSION"

section "Resources"
kv "CPU" "$cpuname $cpucore Cores @ $cpuspeed MHz ($cpuscale scaling) $cpuload Load"
kv "Memory" "$memtotgb GB Total, $memusegb GB Used, $memfregb GB ($memfrepct%) Free"
kv "Disk" "$disksizegb GB Total, $diskavaigb GB Available, $diskusedgb GB ($diskupct) Used"

section "Network"
kv "Hostname" "$(hostname -f)"
internal_ips="$(ip a | grep -w inet | grep -v 127 | awk '{ printf "%s ",$2 }')"
external_ip="$(wget -q -O - http://icanhazip.com/ | tail | tr -d '\n')"
kv "IP Addresses" "Internal: ${internal_ips}External: ${external_ip}"

section "Time"
kv "Timezone" "$(date +'UTC %z (%Z)')"
kv "System Time" "$(date +'%A, %e %B %Y, %r')"
kv "Uptime" "$dd day(s) $hh hour(s) $mm minute(s) $remsecs second(s)"
kv "Last Login" "${lastinfo[0]} (${lastinfo[1]}) ${lastinfo[6]} ${lastinfo[3]}, ${lastinfo[4]} ${lastinfo[5]} ${lastinfo[8]}"

section "DigiHub"
kv "Copyright" "DigiHub © W0FFS $(date +%Y)"
kv "Installed for" "Callsign: ${callsign:-Unknown} - ${forename:-Unknown}"
kv "Coordinates" "Latitude: ${lat:-Unknown} Longitude: ${lon:-Unknown} Grid: ${grid:-Unknown}"

if [ -r "$HOME/.digihub-update-available" ]; then
  kv "Update Available" "Run 'dhupdate' to review and apply the latest DigiHub changes."
fi

if [ -r "$HOME/.digihub-dhinfo-missing" ]; then
  kv "Configuration Missing" ".dhinfo not found and could not be auto-restored; run install.sh or dhedit."
fi

printf "\n"
