#!/bin/sh
# ssh_config_reload.sh
#

SSH_CONF_FILE="/etc/ssh/sshd_config"
TMP_SSH_ALGO_FILE="/tmp/sp_ssh_algo.conf"
SSH_RELOAD_STATUS_FILE="/tmp/sp_ssh_reload_status"

# ReturnOnError():
# Exit with an error code on error.
#
ReturnOnError() {
    if ! [ $1 -eq 0 ] ; then
        exit 1
    else
	exit 0
    fi
}

while IFS=" " read SSH_CONF_ALGO_TYPE SSH_CONF_ALGO_NAMES; do
	grep -q $SSH_CONF_ALGO_TYPE $SSH_CONF_FILE
	if [ $? -eq 0 ]
	then
		echo -n "Append SSH Algo Type in sshd_config" 
		sed -i -e 's/^'$SSH_CONF_ALGO_TYPE' .*/'$SSH_CONF_ALGO_TYPE' '$SSH_CONF_ALGO_NAMES'/g' $SSH_CONF_FILE
		if [ $? -ne 0 ]
		then
			echo -n "sed error, Could not set $SSH_CONF_ALGO_TYPE in sshd_config"
			echo 1 >  $SSH_RELOAD_STATUS_FILE
			exit 1
		fi
	else
		sed -i '$a '$SSH_CONF_ALGO_TYPE' '$SSH_CONF_ALGO_NAMES'' $SSH_CONF_FILE
		if [ $? -ne 0 ]
		then
			echo -n "First time sed error, Could not set $SSH_CONF_ALGO_TYPE in sshd_config"
			echo 1 >  $SSH_RELOAD_STATUS_FILE
			exit 1
		fi
	fi

done < $TMP_SSH_ALGO_FILE

sel_logger SP.notice "testing ssh_config_prereload.sh: restart sshd"
/usr/sbin/sshd -T -C user=$LOGNAME -C host=localhost -C addr=localhost > /dev/null 2>&1
if [ $? -eq 0 ]
then
	sel_logger SP.notice "ssh_config_prereload.sh: restart sshd"
	/etc/init.d/ssh reload
	if ! [ $? -eq 0 ]
	then
		echo -n "Error : Could not reload ssh." >> /var/log/messages
		echo 1 > $SSH_RELOAD_STATUS_FILE
		exit 1
	fi
else
	cp /etc/ssh/sshd_config_bkup /etc/ssh/sshd_config
	/usr/sbin/sshd -T -C user=$LOGNAME -C host=localhost -C addr=localhost > /dev/null 2>&1
	if [ $? -eq 0 ]
	then
		echo -n "Successfully reverted to old configuration.No need to reload"
		echo 1 > $SSH_RELOAD_STATUS_FILE
		exit 0
	else
		echo -n "Error in reverting to old configuration"
		echo 1 > $SSH_RELOAD_STATUS_FILE
		exit 1
	fi
fi

echo 0 > $SSH_RELOAD_STATUS_FILE

#exit 0
