#!/bin/sh

#turn of auto expansion
set -f

alterator_api_version=1
. alterator-sh-functions

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

on_message(){
  case "$in_action" in
  read)
    write_string_param kernel "$(uname -r)"
    write_string_param memory_total "$(meminfo "MemTotal")"
    write_string_param memory_free "$(meminfo "MemFree")"
    write_string_param swap_total "$(meminfo "SwapTotal")"
    write_string_param swap_free "$(meminfo "SwapFree")"
    ;;
  list)
    if [ $in__objects = "df" ];then
      df -lhP|
      sed '1d' |
      awk '{printf "(name \"%s\" disk_total \"%s\" disk_used \"%s (%s)\" disk_free \"%s\")\n",$6,$2,$3,$5,$4;}' >&3

    elif [ $in__objects = "cpu" ];then
      awk -F ': ' '
        BEGIN{n=0;}
        function dump(){
          if (name!=""){
            printf "(num \"%d\" name \"%s\" freq \"%d\" cache \"%s\")",n,name,freq,cache
          }
        }
        function clean(){
          name=""; freq=0; cache="";
        }
        /^processor/  {dump(); clean(); n++;}
        /^model name/ {name=$2;}
        /^cpu MHz/    {freq=$2;}
        /^cache size/ {cache=$2;}
        END{dump()}' < /proc/cpuinfo >&3
    fi
    ;;
  esac
}

message_loop
