#!/bin/busybox sh

if [ $# -eq 0 ] ; then
  verbose=1  # output msg to stderr
  wnkCyc=$(mktemp /tmp/whinkerCyc_XXXXXX)
  printf 'CycleFile: ' 1>&2
  echo $wnkCyc
  cat 1>&2 <<- EOEXAMPLE
	Examples:

	1. Start whinker
	PROMPT# cat >$wnkCyc <<EOCYC1
	#msec R G B
	 200 99 0  0
	 200 0 99  0
	 200 0  0 99
	EOCYC1

	2. Add white
	PROMPT# echo 400 99 99 99 >>$wnkCyc

	3. Change whinker
	PROMPT# cat >$wnkCyc <<EOCYC2
	50 99 0 0
	200 0 0 0
	EOCYC2

	4. Stop whinker
	PROMPT# rm $wnkCyc

	* Inside scripts, use:
	wnkCyc=\$($0 .)
	printf '200 99 99 0\n200 0 99 99\n200 99 0 99\n' >\$wnkCyc
	## proc 1
	echo '600 99 99 99' >>\$wnkCyc
	## proc 2
	printf '10 0 99 0\n800 0 0 0\n' >\$wnkCyc
	## proc 3
	rm \$wnkCyc  # stop

	EOEXAMPLE
else
  verbose=0  # no output to stderr
  if [ -f "$1" ] ; then
    wnkCyc="$(readlink -f "$1")"
  else
    wnkCyc=$(mktemp /tmp/whinkerCyc_XXXXXX)
    echo $wnkCyc
  fi
fi
  
# format of $wnkCyc
# period(msec 1-2000) red(0-255) green(0-255) blue(0-255)
# finish if $wnkCyc is deleted

# set LED device
ledR=/sys/class/leds/pmic_ledsr/brightness
ledG=/sys/class/leds/pmic_ledsg/brightness
ledB=/sys/class/leds/pmic_ledsb/brightness
[ -w $ledR ] || ledR=/dev/null
[ -w $ledG ] || ledG=/dev/null
[ -w $ledB ] || ledB=/dev/null
if [ $ledR$ledG$ledB = /dev/null/dev/null/dev/null ] ; then
  echo "ERROR: NO LED" 1>&2
  exit 1
fi

# main
cd /
while : ; do
  if [ ! -f $wnkCyc ] ; then
    echo 0 >$ledR
    echo 0 >$ledG
    echo 0 >$ledB
    [ $verbose -eq 1 ] && echo "whinker $wnkCyc stopped" 1>&2
    exit 0
  fi
  wwait=250  # msec
  while read ms r g b dum ; do
    # args check
    [ 0 -lt "$ms" -a "$ms" -le 2000 ] || continue
    [ 0 -le "$r" -a "$r" -le 255 ] || continue
    [ 0 -le "$g" -a "$g" -le 255 ] || continue
    [ 0 -le "$b" -a "$b" -le 255 ] || continue
    echo $r >$ledR
    echo $g >$ledG
    echo $b >$ledB
    usleep $((ms*1000))
    wwait=""
  done < $wnkCyc 2>/dev/null
  [ -n "$wwait" ] && usleep $((wwait*1000))
done >/dev/null &

exit

