#!/bin/bash
#
# VERSION=5
# CHANGES="open/close SSH connection after a hardware factory reset"

BEROCONF=/usr/fallback/beroconf

function log () {
	echo "[init_opensshd] ${1}"
}

function create_keys () {

	# Make sure the ssh-keygen progam exists
	[ -f /usr/bin/ssh-keygen ] || return 1

	# Create /usr/conf/ssh
	[ -d /usr/conf/ssh ] || mkdir -p /usr/conf/ssh

	# Check for the SSH1 RSA key
	if [ ! -f /usr/conf/ssh/ssh_host_key ] ; then
		log "Generating RSA1 Key."
		/usr/bin/ssh-keygen -t rsa1 -f /usr/conf/ssh/ssh_host_key -C '' -N ''
	fi

	# Check for the SSH2 RSA key
	if [ ! -f /usr/conf/ssh/ssh_host_rsa_key ] ; then
		log "Generating RSA2 Key."
		/usr/bin/ssh-keygen -t rsa -f /usr/conf/ssh/ssh_host_rsa_key -C '' -N ''
	fi

	# Check for the SSH2 DSA key
	if [ ! -f /usr/conf/ssh/ssh_host_dsa_key ] ; then
		log "Generating DSA Key."
		/usr/bin/ssh-keygen -t dsa -f /usr/conf/ssh/ssh_host_dsa_key -C '' -N ''
	fi

	umask 077

	return 0
}

function sshd_start () {
	if [ -f /var/lock/sshd ]; then
		return 1
	fi
	/usr/sbin/sshd -h /usr/conf/ssh/ssh_host_key -h /usr/conf/ssh/ssh_host_rsa_key -h /usr/conf/ssh/ssh_host_dsa_key
	touch /var/lock/sshd
}

function sshd_stop () {
	killall	sshd
	rm -f /var/lock/sshd
}

function sshd_restart () {
	sshd_stop
	sleep 1
	sshd_start
}

### MAIN ###

## remove old S50sshd script only if S43sshd is executed
if [ -f /etc/init.d/S50sshd ]; then
	mount -o remount,rw /
	rm -f /etc/init.d/S50sshd
	mount -o remount,ro /
fi

create_keys
if [ "${?}" = "1" ]; then
	log "Could not create SSH-keys, leaving."
	exit 1
fi

iface="eth0"
if [ "$(${BEROCONF} get root lan-ports | /bin/grep -v failed)" = "2" ]; then
	iface="${iface}.10"
fi

case "${1}" in
	start)
		## Hardware factory reset
		if [[ -f /usr/conf/need_red_activate ]] && [[ -z $(/usr/sbin/iptables -L | /bin/grep ssh) ]]; then
			## hardware factory reset occured
			## Open SSH port for update or recovery mode
			/usr/sbin/iptables -A INPUT -i ${iface} -p tcp -s 0.0.0.0/0 --dport 22 -j ACCEPT >/dev/null
		fi
 		log "Starting sshd."
		sshd_start
		if [ "${?}" = "1" ]; then
			log "SSH seems to be running already, leaving."
			exit 1
		fi
		;;
	stop)
		log "Stopping sshd."
		sshd_stop
		/usr/sbin/iptables -D INPUT -i ${iface} -p tcp -s 0.0.0.0/0 --dport 22 -j ACCEPT >/dev/null
		;;
	restart)
		log "Restarting sshd."
		sshd_restart
		;;
	*)
		echo "Usage: ${0} {start|stop|restart}" &>2
		exit 1
		;;
esac

exit 0
