#!/bin/sh

# Start the proftpd FTP daemon.

PATH=/bin:/usr/bin:/sbin:/usr/sbin
DAEMON=/usr/sbin/proftpd
NAME=proftpd

# Defaults
RUN="no"
OPTIONS=""

# Read config (will override defaults)
[ -r /etc/default/proftpd ] && . /etc/default/proftpd

trap "" 1
trap "" 15

test -f $DAEMON || exit 0

if ! egrep -q "^[[:space:]]*ServerType.*standalone" /etc/proftpd.conf
then
    RUN="no"
    INETD="yes"
fi

start()
{
    if start-stop-daemon --start --quiet --pidfile /var/run/$NAME.pid \
        --exec $DAEMON -- $OPTIONS ; then
        echo "$NAME."
    else
        echo "."
    fi
}

signal()
{
    if [ "$1" = "stop" ]; then
	SIGNAL="-9"
    else
	if [ "$1" = "reload" ]; then
	    SIGNAL="-1"
	else
	    echo "ERR: wrong parameter given to signal()"
	fi
    fi
    for i in $(find /var/run/proftpd \
        -regex "^/var/run/proftpd/proftpd-[0-9]+\$") ; do
        kill $SIGNAL $(echo $i | sed 's/^[^0-9]\+-//') || true
	killed=1
	if [ "$SIGNAL" = "-9" ]; then
	    rm -f $i
	fi
    done
    if [ -n "$killed" ] ; then
        echo "$NAME."
    else
        echo "."
    fi
}

case "$1" in
    start)
	if [ "x$RUN" = "xyes" ] ; then
	    echo -n "Starting professional ftp daemon: "
	    start
	else
	    if [ "x$INETD" = "xyes" ] ; then
		echo "ProFTPd is started from inetd."
	    fi
	fi
	;;

    force-start)
	echo -n "Starting professional ftp daemon: "
	start
	;;	
    
    stop)
	if [ "x$RUN" = "xyes" ] ; then
	    echo -n "Stopping professional ftp daemon: "
	    signal stop
	else
	    if [ "x$INETD" = "xyes" ] ; then
		echo "ProFTPd is started from inetd."
	    fi
	fi
	;;

    reload)
	echo -n "Reloading $NAME configuration..."
	signal reload
	echo " done."
	;;

    force-reload|restart)
	if [ "x$RUN" = "xyes" ] ; then
	    echo -n "Restarting professional ftp daemon."
	    signal stop
	    echo -n "."
	    sleep 2
	    echo -n "."
	    start
	    echo " done."
	else
	    if [ "x$INETD" = "xyes" ] ; then
		echo "ProFTPd is started from inetd."
	    fi
	fi
	;;

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

exit 0
