#! /bin/sh

PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/sbin/reaim
NAME=reaim
USER=reaim
GROUP=reaim
DESC="Transparent proxy for IM behind NAT"

test -x $DAEMON || exit 0

set -e

case "$1" in
  start)
	if [ -e /var/run/$NAME.pid ]; then
		echo "$DESC: $NAME already started."
		exit 0
	fi
	echo -n "Starting $DESC: $NAME"

	test -e /var/run/$NAME.pid || touch /var/run/$NAME.pid
	chown $USER.$GROUP /var/run/$NAME.pid
	test -e /var/log/$NAME.log || touch /var/log/$NAME.log
	chmod 640 /var/log/$NAME.log
	chown $USER.$GROUP /var/log/$NAME.log

  	start-stop-daemon --start --quiet --background \
		--pidfile /var/run/$NAME.pid --make-pidfile \
		--chuid $USER --exec $DAEMON -- -d

	echo "."
	;;

  stop)
	if [ ! -e /var/run/$NAME.pid ]; then
		echo "$DESC: $NAME is not running."
		exit 0
	fi
	echo -n "Stopping $DESC: $NAME"

	start-stop-daemon --oknodo --stop --quiet \
		--pidfile /var/run/$NAME.pid \
		--chuid $USER --exec $DAEMON
	rm -f /var/run/$NAME.pid

	echo "."
	;;

  restart|force-reload)
	if [ ! -e /var/run/$NAME.pid ]; then
		$0 start
		exit 0
	fi
	echo -n "Restarting $DESC: $NAME"

	start-stop-daemon --oknodo --stop --quiet \
		--pidfile /var/run/$NAME.pid \
		--chuid $USER --exec $DAEMON
	sleep 1
  	start-stop-daemon --start --quiet --background \
		--pidfile /var/run/$NAME.pid --make-pidfile \
		--chuid $USER --exec $DAEMON -- -d

	echo "."
	;;

  *)
	N=/etc/init.d/$NAME
	echo "Usage: $N {start|stop|restart|force-reload}" >&2
	exit 1
	;;

esac

exit 0
