#!/bin/sh
# chkconfig: 2345 50 50
### BEGIN INIT INFO
# Provides:          lsh
# Required-Start:    $network
# Required-Stop:     $network
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Start lsh server.
# Description:       Enable lsh (ssh) server at boot time.
# X-Start-Before:    
# X-Stop-After:      
# X-Timesys-Start-Number:  50
# X-Timesys-Stop-Number:  50
### END INIT INFO

umask 022

prefix=/usr
sysconfdir=/etc
piddir=/var/run

LSHD=$prefix/sbin/lshd
PIDFILE=$piddir/lshd.pid
SEEDFILE=/var/spool/lsh/yarrow-seed-file
LSH_KEYGEN=$prefix/bin/lsh-keygen
HOST_KEY_RSA=$sysconfdir/lsh_host_key
LSHD_OPTS="--daemonic "
# Comment out to disable root login
LSHD_OPTS="$LSHD_OPTS --root-login"



checkkeys() {
    if [ ! -f $HOST_KEY_RSA ]; then
	    ${LSH_KEYGEN} --server | $prefix/bin/lsh-writekey --server --passphrase=""
    fi
}

stop_service() {
    if [  -r $PIDFILE  -a  ! -z ${PIDFILE}  ]; then
	    PID=`cat ${PIDFILE}`
    fi
    if [  ${PID:=0} -gt 1 -a  ! "X$PID" = "X "  ]; then
	    kill ${PID}
    else
	    echo "Unable to read PID file"
    fi
    rm -f ${PIDFILE}
}

start_service() {
    if [ ! -f $SEEDFILE ]; then
        echo "Creating YARROW pseudorandom seed for lsh server..."
        mkdir -p $(dirname $SEEDFILE)
        $prefix/bin/lsh-make-seed --server --sloppy < /dev/urandom > /dev/null
    fi

    # Check to see if we have keys that need to be made
    checkkeys

    mkdir -p $piddir

    # Start LSHD
    printf "Starting $LSHD: "         ; $LSHD $LSHD_OPTS

    lshd_rc=$?
    if [ $lshd_rc -ne 0 ]; then
            echo "[FAIL]"
	    echo "$0: Error ${lshd_rc} starting ${LSHD}... bailing."
	    exit $lshd_rc
    fi
    echo "[ OK ]"
}

case $1 in

'start')
    start_service
    ;;

'stop')
    stop_service
    ;;

'restart')
    stop_service
    start_service
    ;;

*)
    echo "Usage: $0 [start|stop|restart]"
    ;;
esac
