#!/bin/bash
#
# applesmc keyboard backlight sample test daemon
# by Silvan Calarco <silvan.calarco@mambasoft.it>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License v2 as published by the
# Free Software Foundation.
#
SENSIBILITY=25
TIMEWAIT=2
BLINDOFF=50
BLINDON=100
SENSOR_FILE=/sys/devices/platform/applesmc.768/light

[ -e $SENSOR_FILE ] || exit 1

while [ "1" ]; do
   eval `cat $SENSOR_FILE|sed "s|(\(.*\),\(.*\))|LIGHTL=\1 LIGHTR=\2|"` >/dev/null
   if [ "$LIGHTR" ]; then
      if [ $LIGHTL -gt $LIGHTR ]; then
         LIGHTM=$LIGHTL
      else
         LIGHTM=$LIGHTR
      fi
#      LIGHTM=`expr \( $LIGHTL + $LIGHTR \) / 2`
      BACKLIGHT=`expr 255 - $LIGHTM \* $SENSIBILITY`
      if [ $BACKLIGHT -lt $BLINDOFF ]; then
         BACKLIGHT=0
      elif [ $BACKLIGHT -lt $BLINDON ]; then
         BACKLIGHT=`expr $BACKLIGHT + 50`
      else      
         [ $BACKLIGHT -gt 255 ] && BACKLIGHT=255
      fi
#      echo "LightM=$LIGHTM Backlight=$BACKLIGHT "
      applesmc $BACKLIGHT
#      echo $BACKLIGHT > /sys/devices/platform/applesmc.768/keyboard_backlight
#      CURRBACKLIGHT=$BACKLIGHT
      sleep $TIMEWAIT
   fi
done
