#!/bin/sh /etc/rc.common
# Copyright (C) 2006-2011 OpenWrt.org

START=50
STOP=50

USE_PROCD=1

PROG=/usr/sbin/sshd
NAME=sshd
EXTRA_COMMANDS="killclients"
EXTRA_HELP="	killclients Kill ${NAME} processes except servers and yourself"

sshd_instance()
{
        config_get Port "$1" Port
        local pid_file="/etc/ssh/ssh$1_config"
        echo "Port $Port" > $pid_file
        config_get PasswordAuthentication "$1" PasswordAuthentication
        if [ "$PasswordAuthentication" == "yes" ]; then
                echo "PasswordAuthentication yes" >> $pid_file
	elif [ "$PasswordAuthentication" == "no" ]; then
                echo "PasswordAuthentication no" >> $pid_file
	fi

        config_get RootLogin "$1" RootLogin
        if [ "$RootLogin" == "yes" ]; then
                echo "PermitRootLogin yes" >> $pid_file
        elif [ "$RootLogin" == "no" ]; then
                echo "PermitRootLogin no" >> $pid_file
        fi

        echo "PidFile /var/run/sshd.$1.pid" >> $pid_file

        config_get PublicKeyAuthentication "$1" PublicKeyAuthentication
        if [ "$PublicKeyAuthentication" == "yes" ]; then
                echo "PubKeyAuthentication yes" >> $pid_file
                echo "AuthorizedKeysFile      /etc/ssh/authorized_keys" >> $pid_file
                echo "StrictModes      no" >> $pid_file
        fi
        config_get GatewayPorts "$1" GatewayPorts
        if [ "$GatewayPorts" == "yes" ]; then
                echo "GatewayPorts yes" >> $pid_file
        fi
    #    $PROG -D -f "$pid_file" &
	procd_open_instance
	procd_add_mdns "ssh" "tcp" "$Port"
	procd_set_param command $PROG -D -f $pid_file
	procd_set_param file $pid_file
        procd_set_param respawn
        procd_close_instance
}
start_service()
{
        logger "opensshd:start"
        if [[ ! -e "/root/.ssh" ]]; then
                mkdir /root/.ssh
        fi
        for type in rsa ecdsa ed25519
        do
                # check for keys
                key=/etc/ssh/ssh_host_${type}_key
                [ ! -f $key ] && {
                        # generate missing keys
                        [ -x /usr/bin/ssh-keygen ] && {
                                /usr/bin/ssh-keygen -N '' -t $type -f $key 2>&- >&-
                        }
                }
        done
        mkdir -m 0700 -p /var/empty
	. /lib/functions.sh
	config_load sshd
	enablessh=`uci get sshd.@sshd_enable[0].enablessh`
	[ "$enablessh" == 1 ] && config_foreach sshd_instance sshd
}

service_triggers()
{

	procd_add_config_trigger "config.change" "sshd" /etc/init.d/sshd reload

}

shutdown() {
	# close all open connections
	killall sshd
}

killclients()
{
	""
	local ignore=''
	local server
	local pid

	# if this script is run from inside a client session, then ignore that session
	pid="$$"
	while [ "${pid}" -ne 0 ]
	 do
		# get parent process id
		pid=`cut -d ' ' -f 4 "/proc/${pid}/stat"`
		[ "${pid}" -eq 0 ] && break

		# check if client connection
		grep -F -q -e "${PROG}" "/proc/${pid}/cmdline" && {
			append ignore "${pid}"
			break
		}
	done

	# get all server pids that should be ignored
	for server in `cat /var/run/${NAME}.*.pid`
	 do
		append ignore "${server}"
	done

	# get all running pids and kill client connections
	local skip
	for pid in `pidof "${NAME}"`
	 do
		# check if correct program, otherwise process next pid
		grep -F -q -e "${PROG}" "/proc/${pid}/cmdline" || {
			continue
		}

		# check if pid should be ignored (servers, ourself)
		skip=0
		for server in ${ignore}
		 do
			if [ "${pid}" = "${server}" ]
			 then
				skip=1
				break
			fi
		done
		[ "${skip}" -ne 0 ] && continue

		# kill process
		echo "${initscript}: Killing ${pid}..."
		kill -KILL ${pid}
	done
}
