#!/bin/sh
# This script signs the SSH host keys of the OCI live image, and
# delete the SSH ca keys. This way, no more fingerprint warning
# will be print, and one can always trust the live image host keys.

set -e

# Collect all interface names which are contactable, and find their IPs
# (they are contactable, therefore appear in /proc/net/route)
for iface in $(cat /proc/net/route | grep -v Iface | awk '{print $1}' | sort -u) ; do
        IP_ADDRs=${IP_ADDRs}" "$(LC_ALL=C ip addr show "${iface}" | grep inet | head -n 1 | awk '{print $2}' | cut -d/ -f1 | grep -E '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$')
done

SIGNED_A_KEY=no
if [ -e /root/ssh-ca/ca ] ; then
	for keytype in dsa ecdsa ed25519 rsa ; do
		if [ -e /etc/ssh/ssh_host_${keytype}_key ] && [ -e /etc/ssh/ssh_host_${keytype}_key.pub ] ; then
			if ! [ -e /etc/ssh/ssh_host_${keytype}_key-cert.pub ] ; then
				ssh-keygen -s /root/ssh-ca/ca -I 'OCI live image host key' -n $(echo ${IP_ADDRs} | tr ' ' ',') -V -5m:+3650d -h /etc/ssh/ssh_host_${keytype}_key.pub
				SIGNED_A_KEY=yes
			fi
			if ! grep -q "HostCertificate /etc/ssh/ssh_host_${keytype}_key-cert.pub" /etc/ssh/sshd_config ; then
				echo "HostCertificate /etc/ssh/ssh_host_${keytype}_key-cert.pub" >>/etc/ssh/sshd_config
			fi
		fi
	done
	# Delete the SSH ca after booting.
	rm -rf /root/ssh-ca
fi

# Restart sshd, since we've added some key certificates
if [ "${SIGNED_A_KEY}" = "yes" ] ; then
	invoke-rc.d --quiet ssh restart
fi
