#!/bin/sh
#Display CPU usage percentage

_openbsd() {
	CPUS=$(sysctl | grep 'hw.ncpuonline' | sed 's/^.*=//')
	TOTALUSAGE=$(ps aux | awk '{print $3}' | sed '1d' | sort | paste -s -d+ - | bc)
	USAGE=$(printf "$TOTALUSAGE / $CPUS\n" | bc -l)
	printf "$USAGE" | grep "^\.[0-9]" > /dev/null && printf "0$(printf $USAGE | cut -c1-3)%%" || printf "$(printf "$USAGE" | cut -c1-4)%%\n"
}

_freebsd() {
	CPUS="$(sysctl hw.ncpu | sed 's/^.*: //')"
	FREE=$(ps -o %cpu -p $(pgrep -S idle) | tail -n 1)
	TPP=$(expr $CPUS \* 100)
	TOTALUSAGE=$(printf "$TPP - $FREE" | bc -l)
	USAGE=$(printf "$TOTALUSAGE / $CPUS" | bc -l | cut -c -4)
	printf "$USAGE" | egrep "\.[0-9]{3}" > /dev/null && printf "0$(printf $USAGE | cut -c -3)%%\n" || printf -- "$USAGE%%\n"
}

_linux() {
	TOTALUSAGE="$(ps axch -o cmd,%cpu --sort=-%cpu | sed 's/ //' | grep -E -o " [0-9].*" | sed 's/ //' | paste -s -d+ - | bc)"
	USAGE="$(printf "$(printf "$TOTALUSAGE / $(nproc)\n" | bc -l | cut -c1-4)%%\n")"
	printf -- "$USAGE%" | grep "^\.[0-9]" > /dev/null && printf -- "0$(printf -- $USAGE% | cut -c1-3)%%" || printf -- "$(printf -- "$USAGE%" | cut -c1-4)%%\n"
}

case $(uname) in
	Linux) _linux ;;
	OpenBSD) _openbsd  ;;
	FreeBSD) _freebsd ;;
esac
