#!/bin/sh
#
# PiLeds - Let's play with leds as a kid :-)
# (C) 2014 SliTaz GNU/Linux - BSD License
#
. /lib/libtaz.sh
check_root

usage() {
	cat << EOT

$(boldify "Usage:") $(basename $0) [command] [--option]

$(boldify "Commands:")
  act          $(gettext "Turn on/off the on board ACT green led")
  7-clock      $(gettext "Adafruit 7-segment LED Backpack clock example")
  8x8          $(gettext "Adafruit 8x8 LED Matrix Backpack example")
  ada-clean    $(gettext "Clean: Adafruit 7-segment or 8x8 Matrix")
 
$(boldify "8x8 Options:")
  --test       $(gettext "Test the 8x8 LED Matrix")
  --boat       $(gettext "Draw a tiny boat")
  --smile      $(gettext "Draw a smiley :-)")
  --ovni       $(gettext "Draw an OVNI")

EOT
}

load_modules() {
	modprobe i2c-bcm2708
	modprobe i2c-dev
}

check_packages() {
	db="/var/lib/tazpkg/installed"
	for pkg in i2c-tools $@; do
		[ -f "$db/$pkg/receipt" ] || spk-add ${pkg}
	done
}

adafruit_clean() {
	python /usr/lib/python2.7/Adafruit_LEDBackpack.py
}

case "$1" in

	act)
		brightness="/sys/class/leds/led0/brightness"
		status="$(cat $brightness)"
		[ "$quiet" ] || gettext "Current status:"; echo " '$status'"
		if [ "$status" == 0 ]; then
			echo "0" > ${brightness}; usleep 50000
			echo "1" > ${brightness}
		else
			echo "0" > ${brightness}
		fi ;;

	7-clock) 
		scripts="/usr/share/adafruit/LEDBackpack"
		load_modules 
		check_packages "python-rpi-adafruit"
		if [ -f "${scripts}/ex_7segment_clock.py" ]; then
			python ${scripts}/ex_7segment_clock.py
		else
			gettext "Missing:"; echo " ${scripts}/ex_7segment_clock.py"
		fi ;;
	
	8x8)
		if [ "$2" == "--test" ]|| [ ! "$2" ]; then
			script="/usr/share/adafruit/LEDBackpack/ex_8x8_pixels.py"
			check_packages "python-rpi-adafruit"
		else
			script_name="${2#--}.py"
			script="/usr/share/piclass/code/leds/8x8/$script_name"
			check_packages "python-rpi-adafruit piclass-code-examples"
		fi
		load_modules
		if [ -f "${script}" ]; then
			python ${script}
		else
			gettext "Missing script:"; echo " ${script}"
		fi ;;
		
	ada-clean)
		adafruit_clean ;;
	
	*) usage ;;
	
esac && exit 0
