#!/bin/bash
### BEGIN INIT INFO
# Provides:          gutenbach-remctl
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Starts remctld.
# Description:       Starts remctld.
### END INIT INFO

case "$1" in
    start)
	if [ -e /var/run/gutenbach/remctld.pid ]; then
	    pid=$(cat /var/run/gutenbach/remctld.pid)
	    if [ -n "$pid" ]; then
		kill -0 "$pid"
		if [ "$?" == 0 ]; then
		    echo "Ending remctld..." >&2
		    kill "$pid" || true
		fi
	    fi
	fi

	pid=$(sudo lsof -i :4373 | grep remctld | sed s/remctld\ // | sed s/\ .*//)
	if [ -n "$pid" ]; then
	    kill -0 "$pid"
	    if [ "$?" == 0 ]; then
		echo "Ending remctld socket binding..." >&2
		kill "$pid" || true
	    fi
	fi

	echo "Starting remctld..." >&2
	remctld -m -P /var/run/gutenbach/remctld.pid &
	;;

    stop)
	if [ -e /var/run/gutenbach/remctld.pid ]; then
	    pid=$(cat /var/run/gutenbach/remctld.pid)
	    if [ -n "$pid" ]; then
		kill -0 "$pid"
		if [ "$?" == 0 ]; then
		    echo "Ending remctld..." >&2
		    kill "$pid" || true
		fi
	    fi
	fi

	pid=$(sudo lsof -i :4373 | grep remctld | sed s/remctld\ // | sed s/\ .*//)
	if [ -n "$pid" ]; then
	    kill -0 "$pid"
	    if [ "$?" == 0 ]; then
		echo "Ending remctld socket binding..." >&2
		kill "$pid" || true
	    fi
	fi
	;;

    restart)
	if [ -e /var/run/gutenbach/remctld.pid ]; then
	    pid=$(cat /var/run/gutenbach/remctld.pid)
	    if [ -n "$pid" ]; then
		kill -0 "$pid"
		if [ "$?" == 0 ]; then
		    echo "Ending remctld..." >&2
		    kill "$pid" || true
		fi
	    fi
	fi

	pid=$(sudo lsof -i :4373 | grep remctld | sed s/remctld\ // | sed s/\ .*//)
	if [ -n "$pid" ]; then
	    kill -0 "$pid"
	    if [ "$?" == 0 ]; then
		echo "Ending remctld socket binding..." >&2
		kill "$pid" || true
	    fi
	fi

	echo "Starting remctld..." >&2
	remctld -m -P /var/run/gutenbach/remctld.pid &
	;;

    force-reload)
	if [ -e /var/run/gutenbach/remctld.pid ]; then
	    pid=$(cat /var/run/gutenbach/remctld.pid)
	    if [ -n "$pid" ]; then
		kill -0 "$pid"
		if [ "$?" == 0 ]; then
		    echo "Ending remctld..." >&2
		    kill "$pid" || true
		fi
	    fi
	fi

	pid=$(sudo lsof -i :4373 | grep remctld | sed s/remctld\ // | sed s/\ .*//)
	if [ -n "$pid" ]; then
	    kill -0 "$pid"
	    if [ "$?" == 0 ]; then
		echo "Ending remctld socket binding..." >&2
		kill "$pid" || true
	    fi
	fi

	echo "Starting remctld..." >&2
	remctld -m -P /var/run/gutenbach/remctld.pid &
	;;

    *)
	echo "Usage: $0 {start|stop|restart}"
	exit 1
	;;
esac