#!/bin/sh
#
# by ymc-dabe
# Simply listen on a given port
#

### BEGIN INIT INFO
# Provides:          fliwiOnlyOneRunningSupport
# Required-Start:    $all
# Required-Stop:
# Should-Start:
# Should-Stop:
# Default-Start:
# Default-Stop:
# Short-Description: Allows to use ha_only_one_running for non-network-daemons
# Description:       This allows to use Fliwis ha_only_one_running to be used
#                    with daemons that do not listen on a port.
### END INIT INFO


ymcCommand=$1
USAGE="usage: $0 {start|stop|restart|reload|force-reload|status}";


PATH=/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/usr/bin/socat
USER=daemon
PORT=16249


usage()
{
    echo $USAGE >&2
}

if [ $# != 1 ]; then
    usage
    exit 1
fi


. /lib/lsb/init-functions

case "$ymcCommand" in
  start)
    log_daemon_msg "Starting fliwiOnlyOneRunningSupport" "fliwiOnlyOneRunningSupport"
    start-stop-daemon --start --quiet --pidfile /var/run/fliwiOnlyOneRunningSupport.pid --make-pidfile \
                --background --chuid $USER --name $(basename $DAEMON) --user $USER \
                --exec $DAEMON -- -4 TCP-LISTEN:$PORT,fork,reuseaddr EXEC:"/bin/echo 'RUNNING'"
    log_end_msg $?
    echo
  ;;

  stop)
    log_daemon_msg "Stopping fliwiOnlyOneRunningSupport" "fliwiOnlyOneRunningSupport"
    start-stop-daemon --stop --quiet --pidfile /var/run/fliwiOnlyOneRunningSupport.pid \
                --name $(basename $DAEMON) --user $USER --exec $DAEMON --retry 5
    exit_status=$?
    log_end_msg $exit_status || true
    echo
  ;;

  status)
    status_of_proc -p "/var/run/fliwiOnlyOneRunningSupport.pid" "$DAEMON" fliwiOnlyOneRunningSupport && exit 0 || exit 1
  ;;

  restart|force-reload|reload)
        $0 stop
        sleep 2
        $0 start
  ;;

  *)
        usage
        exit 1
  ;;
esac

