#!/bin/sh

#turn of auto expansion
set -f

. /usr/share/alterator/build/backend3.sh

_()
{
LANG=${in_language%%;*}.utf8 gettext "alterator-sysinfo" "$1"
}

meminfo()
{
    sed -nr "/^$1:/ { s,^$1:[[:space:]]*,,;p;q}" /proc/meminfo 
}

on_message()
{
	case "$in_action" in
		constraints)
			echo '('
			printf 'kernel (label "%s")' "`_ "Kernel version"`"

			printf 'memory-total (label "%s")' "`_ "Memory (total)"`"
			printf 'memory-free (label "%s")' "`_ "Memory (free)"`"

			printf 'swap-total (label "%s")' "`_ "Swap space (total)"`"
			printf 'swap-free (label "%s")' "`_ "Swap space (free)"`"

			printf 'disk-mount (label "%s")' "`_ "mount point"`"
			printf 'disk-total (label "%s")' "`_ "total"`"
			printf 'disk-free (label "%s")' "`_ "free"`"
			printf 'disk-used (label "%s")' "`_ "used"`"
			printf 'disk-percent (label "%s")' "`_ "usage in percents"`"

			printf 'cpu-name (label "%s")' "`_ "Name"`"
			printf 'cpu-freq (label "%s")' "`_ "Frequency, MHz"`"
			printf 'cpu-cache (label "%s")' "`_ "Cache size"`"
			echo ')'
			;;
		read)
			echo '('
			printf ' kernel "%s"' "$(uname -r)"
			printf ' memory-total "%s"' "$(meminfo "MemTotal")"
			printf ' memory-free "%s"' "$(meminfo "MemFree")"
			printf ' swap-total "%s"' "$(meminfo "SwapTotal")"
			printf ' swap-free "%s"' "$(meminfo "SwapFree")"
			echo ')'
			;;
		list)
			echo '('
			if [ $in__objects = "df" ];then
			    df -lhP|
			    sed '1d'|
			    awk '{printf "(\"%s\" disk-total \"%s\" disk-used \"%s\" disk-free \"%s\" disk-percent \"%s\")\n",$6,$2,$3,$4,$5;}'
			fi
			if [ $in__objects = "cpu" ];then
				cat /proc/cpuinfo |
				awk -F': ' '
BEGIN { num = -1 }

{
	if ($1 ~ /^processor\y/)
		if (num >= 0)
			printf("(\"%d\" cpu-name \"%s\" cpu-freq \"%.2f\" cpu-cache \"%s\")", num, name, freq, cache)
		else {
			num = $2
			name = ""
			freq = 0
			cache = 0
		}

	if ($1 ~ /^model name\y/)
		name = $2
	if ($1 ~ /^cpu MHz\y/)
		freq = $2
	if ($1 ~ /^cache size\y/)
		cache = $2
}

END {
	if (num >= 0)
		printf("(\"%d\" cpu-name \"%s\" cpu-freq \"%.2f\" cpu-cache \"%s\")", num, name, freq, cache)
}'
			fi
			echo ')'
			;;
		*)
			echo '#f'
			;;
	esac
}

message_loop
