#! /bin/sh
### BEGIN INIT INFO
# Provides:          workaround-3415
# Should-Start:      console-screen
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Workaround for bug #3415
# Description:       Workaround for Maemo Bugzilla bug #3415
### END INIT INFO
#
# Author:	Tommi Saviranta <wnd@iki.fi>
#

set -e

PATH=/sbin:/bin:/usr/sbin:/usr/bin

DESC="Workaround for bug #3415"
NAME=workaround-3415
DAEMON=/usr/bin/$NAME
SCRIPTNAME=/etc/init.d/$NAME
DEFAULT=/etc/default/$NAME
PIDFILE=/tmp/.workaround-3415.pid
USER=user

test -x $DAEMON || exit 0

test -f "$DEFAULT" && source "$DEFAULT"
test $sleeptime || sleeptime=3
DAEMON_ARGS="$sleeptime"


#
# Function that starts the daemon/service
#
do_start()
{
	# Return
	#   0 if daemon has been started
	#   1 if daemon was already running
	#   2 if daemon could not be started
	start-stop-daemon --start --test --chuid $USER --quiet \
			--pidfile $PIDFILE --exec $DAEMON --test >/dev/null \
			|| return 1
	start-stop-daemon --start --chuid $USER --quiet --background \
			--pidfile $PIDFILE --make-pidfile --exec $DAEMON -- \
			$DAEMON_ARGS 2>/dev/null \
			|| return 2
}

#
# Function that stops the daemon/service
#
do_stop()
{
	# Return
	#   0 if daemon has been stopped
	#   1 if daemon was already stopped
	#   2 if daemon could not be stopped
	#   other if a failure occurred
	start-stop-daemon --stop --user $USER --quiet --retry=TERM/30/KILL/5 \
			--pidfile $PIDFILE --name $NAME 2>/dev/null
	RETVAL="$?"
	test "$RETVAL" = 2 && return 2
	test "$RETVAL" = 0 && rm -f "$PIDFILE"
	return "$RETVAL"
}


case "$1" in
  start)
	test "$VERBOSE" = no || echo -n "Starting $DESC: $NAME"
	do_start
	RETVAL="$?"
	case "$RETVAL" in
		0) test "$VERBOSE" = no || echo "." ;;
		1) test "$VERBOSE" = no || echo " - already running." ;;
		2) test "$VERBOSE" = no || echo ". Failed!" ;;
	esac
	test $RETVAL -ne 2 || exit 1
	;;
  stop)
	test "$VERBOSE" = no || echo -n "Stopping $DESC: $NAME"
	do_stop
	RETVAL="$?"
	case "$RETVAL" in
		0) test "$VERBOSE" = no || echo "." ;;
		1) test "$VERBOSE" = no || echo " - already stopped." ;;
		2) test "$VERBOSE" = no || echo ". Failed." ;;
	esac
	test $RETVAL -ne 2 || exit 1
	;;
  restart|force-reload)
	test "$VERBOSE" = no || echo -n "Restarting $DESC: $NAME"
	do_stop
	if test $? -eq 2; then
		echo ". Failed!"
		exit 2
	fi
	do_start
	if test $? -ne 0; then
		echo ". Failed!"
		exit 2
	fi
	echo "."
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
	exit 3
	;;
esac
