#!/bin/sh

_M="${0##*/}"

usage() 
{
	cat <<- USAGE

	Usage: $_M [DEVICE] {COMMAND} [ARGS..]
	USAGE

	cat <<- USAGE

	Control to blink led device.

	DEVICE:
	   af    led on front cover
	   card  led on back cover
	   
	COMMANDS:
	   -h|--help             show this page	
	   -s|--start  [ARGS..]	 Start blinking led
	   -t|--stop   [ARGS..]	 Stop blinking led

	ARGS:
	  start:
	   -d|--duty   [1..99]	 Duty ratio to enable led (default: 50)
	   -p|--period [msec]	 Interval to control led (default: 500)
	  stop:
	   -l|--state  [on|off]  Last state of blink

	USAGE
	exit 0
}

# set_if_null: assign value to variable only if it's null, die otherwise
#
# PARAMETERS:
#   $1 - target variable
#   $2 - new value
set_if_null()
{
	local old

	old="`eval echo '$'$1`"
	if [ -n "$old" ]; then
		echo "You can use only one command."
		exit 1
	fi
	
	eval "$1=$2"
}

_duty=50
_period=500
_lstate="off"
	
parse_params()
{
	while [ $# -ge 1 ]
	do
		arg="$1"
		shift

		case "$arg" in
		-d|--duty)
			_duty=$1
			shift
			;;
		-p|--period)
			_period=$1
			shift
			;;
		-l|--state)
			_lstate=$1
			shift
			;;
		*)
			echo "Unknown option. Please see $_M --help";
			exit 0
			;;
		esac
	done	
}

# option handling
if [ $# -lt 2 ]; then
	set_if_null _command help
else
	case "$1" in
	af)
		set_if_null _device af
		;;
	card)
		set_if_null _device card
		;;
	*)
		echo "Unknown device. Please see $_M --help";
		exit 0
		;;	
	esac
	shift
	
	case "$1" in
	-s|--start)
		set_if_null _command start
		shift
		parse_params "$@"
		;;
	-t|--stop)
		set_if_null _command stop
		shift
		parse_params "$@"
		;;
	-h|--help)
		set_if_null _command help
		;;
	*)
		echo "Unknown option. Please see $_M --help";
		exit 0
		;;	
	esac
	shift
fi

# Perform chosen action
case "$_command" in
	start)
		start_blink_led.sh "$_device" $_duty "$_period" &
		;;	    
	
	stop)
		stop_blink_led.sh "$_device" "$_lstate" &
		;;

	help)
		usage
		exit 0
		;;
esac


