#!/bin/sh

#turn of auto expansion
set -f

alterator_api_version=1
. alterator-sh-functions

meminfo(){
  local name t u f o
  free -mo |
  while read name t u f o; do
    case "$name" in
      Mem:)
        write_string_param memory_total "${t}M"
        write_string_param memory_free  "${f}M"
        write_string_param memory_used  "${u}M"
        write_string_param memory_perc  "$((100*$u/$t))"
      ;;
      Swap:)
        write_string_param swap_total "${t}M"
        write_string_param swap_free  "${f}M"
        write_string_param swap_used  "${u}M"
        write_string_param swap_perc  "$((100*$u/$t))"
      ;;
    esac
  done
}

on_message(){
  case "$in_action" in
  read)
    write_string_param kernel "$(uname -r)"
    write_string_param release "$(cat /etc/altlinux-release | sed -e 's/^alt linux[[:space:]]*//i')"
    meminfo
    ;;
  list)
    if [ $in__objects = "df" ];then
      df -lhP|
      awk '(NR!=1)&&!/^udevfs/&&!/^shmfs/ {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 MHz\" 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
