#!/bin/sh

daemon=avcd
PATH=$PATH:/sbin

die() {
	echo $@
	exit 1
}

showUsage() {
	die "$0 {start|stop|restart|status|reload_acd|mdreload} [prefix]"
}

dumpKeys() {
	echo "Enable_byte Volume_byte"
}

mdreload() {
	pids=$(pidof $daemon) || { echo "$daemon is not running." && return 1; }
	echo -n "Motion Reload $daemon... "
	kill -s SIGUSR2 $(echo $pids | cut -d' ' -f1)
	echo "ok."
}

setupMixer() {
	eval $(dumpKeys | tdb get Microphone)
	micEnable=$Enable_byte
	micVolume=$Volume_byte
	eval $(dumpKeys | tdb get Speaker)
	speakerEnable=$Enable_byte
	speakerVolume=$Volume_byte

	mixer=$prefix/bin/mixer
	if [ "$micEnable" != "0" ]; then
		$mixer igain $micVolume
	else
		$mixer igain 0	
	fi

	if [ "$speakerEnable" != 0 ]; then
		$mixer vol $speakerVolume
	else
		$mixer vol 0
	fi
}
start() {

	! pids=$(pidof $daemon) || die "$daemon($pids) is already running."
	echo "Startting $daemon... "
	[ -x $binary ] || die "$binary is not a valid application"
	export LD_LIBRARY_PATH=$prefix/lib
	setupMixer
	$binary > /dev/null 2> /dev/null &
	count=0
	while [ $count -lt 3 ];do
		pids=$(pidof $daemon) && echo -17 > /proc/$pids/oom_adj && break
		count=$((count+1))
		sleep 1
	done
	echo "avcd ok."
}

reload_acd() {
	echo -n "Reloading acd... "
	export LD_LIBRARY_PATH=$prefix/lib
	setupMixer
	echo "ok."
}

status() {
	echo -n "$daemon"
	pids=$(pidof $daemon) && echo "($pids) is running." || echo " is stop."
}

checkExited() {
	pids=$(pidof $daemon) && return 1 || return 0
}

stop() {
	if checkExited; then 
		echo "$daemon is not running." 
		return 0
	fi

	echo -n "Stopping $daemon... "
	killall -USR1 $daemon
	count=0
	while [ $count -lt 10 ];do
		if checkExited; then
			echo "ok."
			return 0
		else
			count=$((count+1))
			if [ $count -gt 5 ]; then
				echo "wait!! $count second"
			fi
			sleep 1
		fi
	done
	checkExited && echo "ok." || die "ng."
}

set_debug() {
	if [ "$1" == "on" ]; then
		touch /tmp/vcd_debug_on
		#killall -s SIGUSR2 avcd
	elif [ "$1" == "off" ]; then
		touch /tmp/vcd_debug_off
		#killall -s SIGUSR2 avcd
	fi
}

action=$1
prefix=$2
end=$3

[ "$end" = "" ] && [ "$action" != "" ] || showUsage
[ "$prefix" = "" ] || [ -d "$prefix" ] || die "$prefix is not a valid directory"

binary=$prefix/sbin/$daemon

case $action in
	start)
		start
	;
	mdreload)
		mdreload	
	;
	stop)
		# stop may call return, instead of exit
		stop || exit 1
	;
	restart)
		stop
		start
	;
	status)
		status
	;
	reload_acd)
		reload_acd
	;
	debug_on)
		set_debug "on"
	;
	debug_off)
		set_debug "off"
	;
	*)
		showUsage
	;
esac

exit 0