#!/bin/bash
#
# Report CPU usage (user/system)
#
# $Id: cpu.sh,v 1.13 2008-06-10 17:51:00 andozer Exp $
#
do_vmstat () {
	vmstat 5 2 | awk '
	BEGIN { pos = 0 }
	{
		getline;

		if (pos == 0) {
			for (c = 1; c < NF; c++) {
				if ($c == "us") pos = c;
			}
		}
	} END { f = pos + 1; print $pos "\n" $f "\n0\nCPU user/system" }'

	exit 0
}

case `uname` in
FreeBSD)
	if [ `uname -r | cut -c 1` -lt 4 ]	# old thing
	then
		do_vmstat
	fi

	HZ=128
	sysctl -n kern.cp_time | awk -v ncpu=`sysctl -n hw.ncpu` -v hz=$HZ '
{
	tick = 100 / (hz * ncpu);
	printf "%d\n%d\n0\nCPU user/system\ncpui:%d\ncpui:0\ncpui:0\ncpui:CPU idle\n",
		($1 + $2) * tick, $3 * tick, $5 * tick;
}'
;;

Linux)
	HZ=100
	awk -vhz=$HZ '
($1 == "cpu") {
	us = $2 + $3;
	sy = $4;
	id = $5;
	next;
}

($1 ~ /^cpu[0-9]/) {
	ncpu = substr($1, 4);
	next;
}

($1 !~ /cpu/) {
	ncpu++;
	tick = 100/(hz * ncpu);
	printf "%d\n%d\n0\nCPU user/system\n", us * tick, sy * tick;
	printf "cpui:%d\ncpui:0\ncpui:0\ncpui:CPU idle\n", id * tick;
	exit;
}' < /proc/stat
;;

*)
	do_vmstat
;;
esac
