#! /bin/sh
set -e

# /etc/init.d/rsync: start and stop the rsync daemon

DAEMON=/usr/bin/rsync
RSYNC_ENABLE=false
RSYNC_OPTS=''
RSYNC_DEFAULTS_FILE=/etc/default/rsync
RSYNC_CONFIG_FILE=/etc/rsyncd.conf

test -x $DAEMON || exit 0

if [ -s $RSYNC_DEFAULTS_FILE ]; then
    . $RSYNC_DEFAULTS_FILE
    case "x$RSYNC_ENABLE" in
        xtrue|xfalse)   ;;
        xinetd)         exit 0
                        ;;
        *)              echo "Value of RSYNC_ENABLE in $RSYNC_DEFAULTS_FILE must be either 'true' or 'false';"
                        echo "not starting rsync daemon."
                        exit 1
                        ;;
    esac
fi

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

case "$1" in
  start)
	if "$RSYNC_ENABLE"; then
            echo -n "Starting rsync daemon: rsync"
	    if [ -s /var/run/rsync.pid ] && kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
	    	echo " apparently already running."
		exit 0
	    fi
            if [ ! -s "$RSYNC_CONFIG_FILE" ]; then
                echo " missing or empty config file $RSYNC_CONFIG_FILE"
                exit 1
            fi
            start-stop-daemon --start --quiet --background \
                --pidfile /var/run/rsync.pid --make-pidfile \
                --exec /usr/bin/rsync \
                -- --no-detach --daemon --config "$RSYNC_CONFIG_FILE" $RSYNC_OPTS
            echo "."
        else
            if [ -s "$RSYNC_CONFIG_FILE" ]; then
                echo "rsync daemon not enabled in /etc/default/rsync"
            fi
        fi
	;;
  stop)
        echo -n "Stopping rsync daemon: rsync"
	start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/rsync.pid
	rm -f /var/run/rsync.pid
        echo "."
	;;

  reload|force-reload)
        echo "Reloading rsync daemon: not needed, as the daemon"
        echo "re-reads the config file whenever a client connects."
	;;

  restart)
	set +e
        if $RSYNC_ENABLE; then
            echo -n "Restarting rsync daemon: rsync"
	    if [ -s /var/run/rsync.pid ] && kill -0 $(cat /var/run/rsync.pid) >/dev/null 2>&1; then
		start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/rsync.pid || true
		sleep 1
	    else
	    	rm -f /var/run/rsync.pid
	    fi
            if ! start-stop-daemon --start --quiet --background \
                --pidfile /var/run/rsync.pid --make-pidfile \
                --exec /usr/bin/rsync \
                -- --no-detach --daemon --config "$RSYNC_CONFIG_FILE" $RSYNC_OPTS
	    then
	    	echo "start failed?"
		rm -f /var/run/rsync.pid
	    fi
            echo "."
        else
            echo "rsync daemon not enabled in /etc/default/rsync"
        fi
	;;

  *)
	echo "Usage: /etc/init.d/rsync {start|stop|reload|force-reload|restart}"
	exit 1
esac

exit 0
