#!/bin/bash

# $0 // command
# $1 // sensor name
# $2 // property name
# $3 // extension or sparse_name
# $4 // mode [read|write]
# $5 // size
# $6 // offset
# $7 // sensor-specific data
# $8 // property-specific data

# log every call (debug)
echo -n "$(/bin/date) ~ $* ~ " >>/var/log/owexternal.sh.log

# case insensitive string comparison
shopt -s nocasematch

if [[ "$4" == "read" ]] ; then
  case "$7" in # sensor specific data
    "memory" )
      case "$8" in # property specific data
        "total" )
          /usr/bin/free | grep -e "^Mem:" | tr -s ' ' | cut -d ' ' -f 2 | tee -a /var/log/owexternal.sh.log
          ;;
        "used" )
          /usr/bin/free | grep -e "^Mem:" | tr -s ' ' | cut -d ' ' -f 3 | tee -a /var/log/owexternal.sh.log
          ;;
        "free" )
          /usr/bin/free | grep -e "^Mem:" | tr -s ' ' | cut -d ' ' -f 4 | tee -a /var/log/owexternal.sh.log
          ;;
        "shared" )
          /usr/bin/free | grep -e "^Mem:" | tr -s ' ' | cut -d ' ' -f 5 | tee -a /var/log/owexternal.sh.log
          ;;
        "buffers" )
          /usr/bin/free | grep -e "^Mem:" | tr -s ' ' | cut -d ' ' -f 6 | tee -a /var/log/owexternal.sh.log
          ;;
        "cached" )
          /usr/bin/free | grep -e "^Mem:" | tr -s ' ' | cut -d ' ' -f 7 | tee -a /var/log/owexternal.sh.log
          ;;
        * )
          echo "NOTIMPL" >>/var/log/owexternal.sh.log
          ;;
      esac
      ;;
    * )
      case "$8" in # property specific data
        # read disk properties in kB for mountpoint in sensor data
        "disksize" )
          /bin/df -k $7 | tail -1 | tr -s ' ' | cut -d ' ' -f 2 | tee -a /var/log/owexternal.sh.log
          ;;
        "diskused" )
          /bin/df -k $7 | tail -1 | tr -s ' ' | cut -d ' ' -f 3 | tee -a /var/log/owexternal.sh.log
          ;;
        "diskfree" )
          /bin/df -k $7 | tail -1 | tr -s ' ' | cut -d ' ' -f 4 | tee -a /var/log/owexternal.sh.log
          ;;
        "diskpercentage" )
          /bin/df -k $7 | tail -1 | tr -s ' ' | cut -d ' ' -f 5 | tee -a /var/log/owexternal.sh.log
          ;;
        "mountpoint" )
          /bin/df -k $7 | tail -1 | tr -s ' ' | cut -d ' ' -f 6 | tee -a /var/log/owexternal.sh.log
          ;;
        "diskdevice" )
          /bin/df -k $7 | tail -1 | tr -s ' ' | cut -d ' ' -f 1 | tee -a /var/log/owexternal.sh.log
          ;;
        * )
          echo "NOTIMPL" >>/var/log/owexternal.sh.log
          ;;
      esac
      ;;
  esac
elif [[ "$4" == "write" ]] ; then
  # TODO
  echo "NOTIMPL" >>/var/log/owexternal.sh.log
fi
 
