#!/bin/sh
### BEGIN INIT INFO
# Provides:          ncad
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
### END INIT INFO
#
# Do not configure this file. Edit /etc/default/ncad instead!
#

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/sbin/ncad
NAME=ncad
DESC="NCAD SSH server"

NCAD_PORT=911
NCAD_EXTRA_ARGS="-g -j -k"
NO_START=0

set -e

cancel() { echo "$1" >&2; exit 0; };
test ! -r /etc/default/ncad || . /etc/default/ncad
test -x "$DAEMON" || cancel "$DAEMON does not exist or is not executable."

test -z "$NCAD_BANNER" || \
  NCAD_EXTRA_ARGS="$NCAD_EXTRA_ARGS -b $NCAD_BANNER"
test -n "$NCAD_RSAKEY" || \
  NCAD_RSAKEY="/etc/ncad/ncad_host_rsa_key"
test -n "$NCAD_DSSKEY" || \
  NCAD_DSSKEY="/etc/ncad/ncad_host_dss_key"
test -n "$NCAD_RECEIVE_WINDOW" || \
  NCAD_RECEIVE_WINDOW="65536"

case "$1" in
  start)
        # Make copies of libraries which are not in /lib
        LIBRARIES=`LD_LIBRARY_PATH=/etc/ncad/ ldd /sbin/ncad | awk ' $3 ~ /\// {print $3 ; } ' | grep -v ^/lib | grep -v ^/etc/ncad `
        for LIB in $LIBRARIES ; do 
          echo Copying $LIB to /etc/ncad
          cp $LIB /etc/ncad/
        done
        test "$NO_START" = "0" || cancel 'NO_START is not set to zero.'
        if [ ! -z "$IF" ] &&
           [ ! -z "$IP" ] &&
           [ ! -z "$BC" ] &&
           [ ! -z "$NM" ] &&
           [ ! -z "$GW" ] ; then
         if (ifconfig $IF | grep -q $IP) ; then
           echo Network already running
         else
           echo -n "Setting up network: "
           ifconfig eth0 172.26.183.82 netmask 255.255.255.0 broadcast 172.26.183.255 up
           route add default gateway 172.26.183.82 metric 1
           echo Done
         fi
        else
         echo Consider setting network options in /etc/default/ncad to get things to work earlier
        fi
        echo -n "Starting $DESC: "
        LD_LIBRARY_PATH=/etc/ncad
        start-stop-daemon --start --quiet \
          --exec "$DAEMON" -- -d "$NCAD_DSSKEY" -r "$NCAD_RSAKEY" \
            -p "$NCAD_PORT" -W "$NCAD_RECEIVE_WINDOW" $NCAD_EXTRA_ARGS
        echo "$NAME."
        ;;
  stop)
        echo -n "Stopping $DESC: "
        start-stop-daemon --stop --quiet --oknodo --exec "$DAEMON"
        echo "$NAME."
        ;;
  restart|force-reload)
        test "$NO_START" = "0" || cancel 'NO_START is not set to zero.'
        echo -n "Restarting $DESC: "
        start-stop-daemon --stop --quiet --oknodo --exec "$DAEMON"
        sleep 1
        start-stop-daemon --start --quiet \
          --exec "$DAEMON" -- -d "$NCAD_DSSKEY" -r "$NCAD_RSAKEY" \
            -p "$NCAD_PORT" -W "$NCAD_RECEIVE_WINDOW" $NCAD_EXTRA_ARGS
        echo "$NAME."
        ;;
  *)
        N=/etc/init.d/$NAME
        echo "Usage: $N {start|stop|restart|force-reload}" >&2
        exit 1
        ;;
esac

exit 0
