#!/bin/bash

# Screenlets-daemon startup-script (thanks to raptros-v76).

SL_PATH="/usr/share/screenlets"

# get PID of running daemon (or 0 if not running)
get_pid() {
	#SL_PID=`ps aux|grep "./screenletsd.py start"|grep -v grep|cut -d' ' -f8`
	SL_PID=`ps axo "%p,%a" |grep "./screenletsd.py start"|grep -v grep|cut -d',' -f1`
}

# start the screenlets-daemon
start_screenlets() {
	# check if daemon is already running
	get_pid
	if  [ -n "$SL_PID" ]; then
		echo "Screenletsd is already running - stop the running daemon first."
	else
		$SL_PATH/screenletsd.py start & 	# run the daemon
	fi
}

# add a screenlet through the daemon
add_screenlet() {
	get_pid
	if  [ -n "$SL_PID" ]; then
		$SL_PATH/add-screenlet.py $1
	else
		echo "Screenletsd is not running - cannot add screenlet."
	fi
}

# reset (delete) the daemon's session-data in $HOME/.config/Screenlets
# TODO: ask for confirmation before reset
reset_session_data() {
	get_pid
	if  [ -n "$SL_PID" ]; then
		echo "Error: Screenlets-Daemon is still running. Stop the daemon first!"
	else
		rm -f $HOME/.config/Screenlets/*.state
		rm -f $HOME/.config/Screenlets/screenletsd.ses
		echo "Session-data has been cleared."
	fi
}

# stop the running daemon
stop_screenlets() {
	get_pid
	kill $SL_PID
}

# output note
echo "Screenletsd v0.0.1 | (c) RYX (Rico Pfaus) 2007 | released under the GPL"

# check args
case "$1" in
	add)
		add_screenlet $2
		;;
	start)
		start_screenlets
		;;
	stop)
		stop_screenlets
		echo "Screenlets-daemon stopped."
		;;
	restart)
		stop_screenlets
		sleep 1
		start_screenlets
		;;
	reset)
		# cleanup the session
		reset_session_data
		;;
	help)
		echo " "
		echo "The Screenlets-Daemon (screenletsd) is the backend for starting, "
		echo "saving and restoring Screenlets."
		echo " "
		echo "ACTIONS:"
		echo " 'add <name>' : add a Screenlet (e.g. 'add Clock')"
		echo " 'help'       : show this help-text"
		echo " 'start'      : start the daemon"
		echo " 'stop'       : stop the daemon"
		echo " 'reset'      : reset the session (delete all Screenlets)"
		echo " 'restart'    : restart the daemon"
		echo " "
		echo "OPTIONS:"
		echo " No options yet."
		echo " "
		;;
	*)
		# TODO: output usage
		#echo "usage: $0 {start|stop|add <name>|reset}" >&2
		echo "Usage: screenletsd <action> [option(s)]" >&2
		#$SL_PATH/screenletsd.py $1	# let the daemon output its usage
		exit 3
		;;
esac

exit 0
