#! /bin/sh
### BEGIN INIT INFO
# Provides:          irserver64
# Required-Start:    $local_fs
# Required-Stop:     $local_fs
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts the irserver64.
# Description:       Starts the irserver64 (IRTrans Infrared Control Server, 64 bit version).
### END INIT INFO
#
# Author:            Helmar Gerloni <helmar@gerloni.net>
# Version:           2014-08-09
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="IRTrans Infrared Control Server"
NAME=irserver64
PIDFILE=/tmp/.irserver64.pid
SCRIPTNAME=/etc/init.d/$NAME

#
#	Function that starts irserver64.
#
d_start() {
	start-stop-daemon --start --chdir /usr/local/irtrans/ --exec /usr/local/irtrans/irserver64 -- -no_web -daemon -logfile /var/log/irserver64.log /dev/ttyUSB0
	if [ $? -gt 0 ]; then
		# After stopping irserver64 with the "irclient64 -shutdown" command the server-port 21000/tcp
		# is not closed properly. The port stays in status TIME_WAIT and is released only after the tcp-timeout.
		# After this timeout the server can be started again.
		echo
		echo "Error starting irserver64."
		echo "If you just stopped irserver64 before please wait for a few seconds and try again."
		exit $?
	fi
	rm -rf /var/run/lirc
	mkdir -p /var/run/lirc
	ln -s /dev/lircd /var/run/lirc/lircd
}

#
#	Function that stops irserver64.
#
d_stop() {
	# Stopping the daemon with start-stop-daemon does not turn off the VFD display
	# start-stop-daemon --stop --quiet --pidfile $PIDFILE
	# A single shutdown might not be enough
	/usr/local/irtrans/irclient64 127.0.0.1 -shutdown
	if [ $? -gt 0 ]; then
		echo "Error stopping irserver64 on localhost. Probably irserver64 is not running."
	fi
}

case "$1" in
  start)
	echo -n "Starting $DESC: $NAME"
	d_start
	echo "."
	;;
  stop)
	echo -n "Stopping $DESC: $NAME"
	d_stop
	echo "."
	;;
  restart|force-reload)
	echo -n "Restarting $DESC: $NAME. Waiting for 60 seconds before starting again..."
	d_stop
	sleep 61
	d_start
	echo "."
	;;
  *)
	echo "Usage: $SCRIPTNAME {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
