#!/bin/sh

# colour for output
txtbld=$(tput bold)
txtund=${txtbld}$(tput sgr 0 1)
txtred=$(tput setaf 1)
txtyellow=$(tput setaf 3)
txtblue=$(tput setaf 4)
txtreset=$(tput sgr0)

#check if root is running this
if [ "`id -u`" != "0" ]; then
        echo "Permission denied, must be root!" 1>&2
        exit 1
fi

#establish default for the program
if [ -z "$GNX_PATH" ]; then
	GNX_PATH="/mnt/gnx-root"
fi

# check if openssh keys exist
if [ -f "$GNX_PATH/etc/ssh/ssh_host_rsa_key" ] && [ -f "$GNX_PATH/etc/ssh/ssh_host_dsa_key" ]; then
	echo "${txtbld}${txtblue}Saving openssh keys for rescue dropbear...${txtreset}"
	mount -o remount,rw /mnt/rescRO
	if [ "$?" != "0" ]; then
		echo "Error: Failed to open the rescue file system for editing" 1>&2
		exit 1
	fi
	dropbearconvert openssh dropbear "$GNX_PATH/etc/ssh/ssh_host_dsa_key" /mnt/rescRO/etc/dropbear/dropbear_dss_host_key
	if [ "$?" != "0" ]; then
                echo "Error: Failed to convert openssh dsa key for dropbear" 1>&2
                exit 1
        fi
	dropbearconvert openssh dropbear "$GNX_PATH/etc/ssh/ssh_host_rsa_key" /mnt/rescRO/etc/dropbear/dropbear_rsa_host_key
        if [ "$?" != "0" ]; then
                echo "Error: Failed to convert openssh rsa key for dropbear" 1>&2
                exit 1
        fi
	mount -o remount,ro /mnt/rescRO
        if [ "$?" != "0" ]; then
                echo "Error: Failed to remount rescue file system read-only" 1>&2
                exit 1
        fi

	echo -e "${txtbld}${txtblue}[Success]${txtreset}"
else
	exit 1
fi

exit 0
