#!/bin/bash
# shellcheck disable=SC2086,SC2046
#
#    20-sysinfo - https://phus.lu/code/update-motd-sysinfo.bash
#    Copyright (c) 2023 Phus Lu
#
#    Authors: Phus Lu <phus.lu@gmail.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

# date time
printf -v datetime '%(%Y-%m-%d %H:%M:%S)T'

# system load
read -r load _ </proc/loadavg

# processes
for _ in /proc/[1-9]*; do ((processes++)); done

# disk usage
set -- $(df -h /); rootusage="${12} of $9"

# logined users
set -- $(users); users=$#

# memory usage
readarray meminfo </proc/meminfo
for value in "${meminfo[@]}"; do
	set -- $value
	case $1 in
		"MemTotal:" )
			MemTotal=$2
			;;
		"MemFree:" )
			MemFree=$2
			;;
		"MemAvailable:" )
			MemFree=$2
			;;
		"SwapTotal:" )
			SwapTotal=$2
			;;
		"SwapFree:" )
			SwapFree=$2
			;;
	esac
done
memusage=$(( 100 * (MemTotal-MemFree) / MemTotal ))
if [ "${SwapTotal}" != "0" ]; then
	swapusage=$(( 100 * (SwapTotal-SwapFree) / SwapTotal ))
fi

# ip address
ipaddr_by_fib_trie=true
if [[ $ipaddr_by_fib_trie == true && -f /proc/net/fib_trie ]]; then
	readarray -t fibtrie </proc/net/fib_trie
	for value in "${fibtrie[@]}"; do
		if [[ $value == *"32 host"* && $prev != *"127."* && $prev != *"169.254."* && $prev != *"172.17.0.1" ]]; then
			break
		fi
		prev="$value"
	done
	set -- $prev; ipaddr=$2
else
	read -r -a iproute < <(ip route get 1.1.1.1)
	for (( i=0; i<${#iproute[@]}; i++ )); do
		if [ "${iproute[$i]}" == "src" ]; then
			ipaddr=${iproute[$i+1]}
			break
		fi
	done
fi

# cpu temperature
if [ -f /sys/class/thermal/thermal_zone0/temp ]; then
	read temp < /sys/class/thermal/thermal_zone0/temp
	temperature="Temperature:\t$(( temp / 1000 ))°C"
fi

echo -e "
  System information as of: ${datetime}

  System load:\t${load}\t\tProcesses:\t${processes}
  Usage on /:\t${rootusage}\tLoggin users:\t${users}
  Memory usage:\t${memusage}%\t\tIPv4 address:\t${ipaddr}
  Swap usage:\t${swapusage:-0}\t\t${temperature}
"