#!/bin/bash

[ "$(uname -m)" == "aarch64" ] || exit

function display() {
	# $1=name $2=value $3=red_limit $4=minimal_show_limit $5=unit $6=after $7=acs/desc{
	if [[ -n "$2" && (( "${2%.*}" -ge "$4" )) ]]; then
		printf "%-14s" "$1:"
		if awk "BEGIN{exit ! ($2 $great $3)}"; then echo -ne "\e[0;91m $2"; else echo -ne "\e[0;92m $2"; fi
		printf "%-1s\x1B[0m" "$5"
		printf "%-11s\t" "$6"
		return 1
	fi
} # display

function storage_info() {
	root_info=$(df -h /)
	root_usage=$(awk '/\// {print $(NF-1)}' <<<${root_info} | sed 's/%//g')
	root_total=$(awk '/\// {print $(NF-4)}' <<<${root_info})
}

# query various systems
storage_info

critical_load=80

# get uptime, logged in users and load in one take
UPTIME=$(LC_ALL=C uptime)
UPT1=${UPTIME#*'up '}
UPT2=${UPT1%'user'*}
users=${UPT2//*','}
users=${users//' '}
time=${UPT2%','*}
time=${time//','}
time=$(echo $time | xargs)
load=${UPTIME#*'load average: '}
load=${load//','}
load=$(echo $load | cut -d" " -f1)
[[ $load == 0.0* ]] && load=0.10
cpucount=$(grep -c processor /proc/cpuinfo)

load=$(awk '{printf("%.0f",($1/$2) * 100)}' <<< "$load $cpucount")

# memory and swap
mem_info=$(LC_ALL=C free -w 2>/dev/null | grep "^Mem" || LC_ALL=C free | grep "^Mem")
memory_usage=$(awk '{printf("%.0f",(($2-($4+$6+$7))/$2) * 100)}' <<<${mem_info})
mem_info=$(echo $mem_info | awk '{print $2}')
memory_total=$(( mem_info / 1024 ))
swap_info=$(LC_ALL=C free -m | grep "^Swap")
swap_usage=$( (awk '/Swap/ { printf("%3.0f", $3/$2*100) }' <<<${swap_info} 2>/dev/null || echo 0) | tr -c -d '[:digit:]')
swap_total=$(awk '{print $(2)}' <<<${swap_info})

echo ""
printf "\e[0;90m Performance:  \x1B[0m\n"

display " Load" "${load%% *}" "${critical_load}" "0" "%" ""

printf "Up time:       \x1B[92m%s\x1B[0m\t" "$time"
display "Local users" "${users##* }" "3" "2" ""
echo ""

if [[ ${memory_total} -gt 1023 ]]; then
	memory_total=$(awk '{printf("%.2f",$1/1024)}' <<<${memory_total})"G"
else
	memory_total+="M"
fi

if [[ ${swap_total} -gt 1023 ]]; then
	swap_total=$(awk '{printf("%.2f",$1/1024)}' <<<${swap_total})"G"
else
	swap_total+="M"
fi

display " Memory usage" "$memory_usage" "70" "0" "%" " of ${memory_total}"
display "Swap usage" "$swap_usage" "75" "-1" "%" " of ${swap_total}"
echo "" # fixed newline
display " Usage of /" "$root_usage" "90" "1" "%" " of $root_total $overlay_root"
echo "" # fixed newline
echo
