#!/bin/sh

# description:  Start/stop openssh server. This is a daemon which manages ssh connection 
#
# processname: sshd
# pidfile: /var/run/sshd.pid
#

############
# CHANGELOG
#===========
# 2011/03/21    crms00282384    Claire Dechriste
#               SSH must be disabled by default
#

# Sanity checks.
[ -x /usr/sbin/sshd ] || exit 0

#crms00274217+
. /etc/init.d/rc.config

settingsfile=security.cfg

. $NVDEFAULT_ROOT/$settingsfile
[[ -f $NVLOCAL_ROOT/$settingsfile ]] && . $NVLOCAL_ROOT/$settingsfile
[[ -f $NVDM_ROOT/$settingsfile ]] && . $NVDM_ROOT/$settingsfile
#crms00274217-

#crms00282384
UNLOCK='/usr/sbin/.unlock'

RETVAL=0

start() {
    #does the rsa key from the server already exist? If not, create it.
    if [ ! -d /etc/ssh ] ; then
        mkdir -p /etc/ssh
    fi
    if [ ! -e /etc/ssh/ssh_host_rsa_key ] ; then
	    ssh-keygen -t rsa -b 2048 -f /etc/ssh/ssh_host_rsa_key -N ""
    fi
    # create the /var/log/laslog ddir for ssh logging
    if [ ! -d /var/log/lastlog ] ; then
#       echo "Creating /var/log/lastlog"
        mkdir -p /var/log/lastlog
    fi
    # create the /var/run/utmp for login
    if [ ! -e /var/run/utmp ] ; then
#       echo "Creating /var/run/utmp"
       > /var/run/utmp
    fi

    #crms00282384+
    # if the unlock script exists
    if [ -x "$UNLOCK" ]; then
        # check the lock status
        bool=`$UNLOCK root`
        # if it's false, the phone is locked
        if [ "$bool" == "false" ]; then
            #crms00274217+
            if [ "$SECUCFG_SSH" == "false" ] ; then
                echo "SSH is disabled"
                exit $RETVAL
            fi
            #crms00274217-
        # else, the phone is unlocked,
        # continue without checking the value of SSH setting
        fi
    # unlock script does not exist
    else
        # the phone is locked
        if [ "$SECUCFG_SSH" == "false" ] ; then
            echo "SSH is disabled"
            exit $RETVAL
        fi
    fi
    #crms00282384-

    if [ -x /usr/sbin/sshd ] ; then
        /usr/sbin/sshd -4 -f /etc/ssh/sshd_ictouch.conf
        RETVAL=$?
        usleep 100000
        if [ -f /var/run/sshd.pid ] ; then
           pid=`cat /var/run/sshd.pid`
           echo "   done - pid =" $pid
        fi
    fi
}

stop() {
    echo "Stopping sshd daemon: "

    if [ -f /var/run/sshd.pid ] ; then
       pid=`cat /var/run/sshd.pid`
       kill -9 $pid
       RETVAL=$?
       echo "   done - pid =" $pid
       rm -f /var/run/sshd.pid
    fi

}


# See how we were called.
case "$1" in
    start)
        start
        ;;
    stop)
        stop
        #crms00261807+++
        #terminate opened sessions -- warning this also kill this shell, all code after this is not executedd
        killall -TERM sshd
        #crms00261807---
        ;;
    restart)
        stop
        start
        ;;
    *)
        echo $"Usage: $0 {start|stop|restart}"
        ;;
esac
exit $RETVAL
