#!/bin/sh

set -e
#set -x

usage () {
	echo "$0 <cluster-name>"
	exit 1
}

if [ $# != 1 ] && [ $# != 2 ] ; then
	usage
fi

if [ "${1}" = "-h" ] || [ "${1}" = "-help" ] || [ "${1}" = "--help" ] ; then
	usage
fi

MY_CWD=$(pwd)

CLUSTER_NAME=${1}
DIRN="/var/lib/oci/clusters/${CLUSTER_NAME}"
if ! [ -d "${DIRN}" ] ; then
	echo "Cannot find cluster named ${DIRN}."
	exit 1
else
	cd ${DIRN}
fi

shift

if [ -n "${1}" ] ; then
	TARGET_HOST=${1}
	shift
fi

unset SSH_AUTH_SOCK
SCP="scp -i /etc/openstack-cluster-installer/id_rsa"

for i in $(find /var/lib/oci/clusters/${CLUSTER_NAME} -maxdepth 1 -type d -iname ${CLUSTER_NAME}'-*') ; do
	HOST=$(basename $i)
	SHORT_HOST=$(basename $i | cut -d. -f1)
	if [ -z "${TARGET_HOST}" ] || [ "${HOST}" = "${TARGET_HOST}" ] ; then
		echo "===> Managing ${HOST}"
		echo "---> Copying in..."
		mkdir -p $i/oci-in-target/etc/ssh
		cd $i/oci-in-target/etc/ssh
		for KEY in dsa ecdsa ed25519 rsa ; do
			${SCP} -o StrictHostKeyChecking=no ${HOST}:/etc/ssh/ssh_host_${KEY}_key . || true
			${SCP} -o StrictHostKeyChecking=no ${HOST}:/etc/ssh/ssh_host_${KEY}_key.pub . || true
		done
		${SCP} -o StrictHostKeyChecking=no ${HOST}:/etc/ssh/sshd_config .
		echo "---> Signing keys..."
		HOST_IP=$(getent hosts ${HOST} | awk '{print $1}')
		ssh-keygen -s /var/lib/oci/clusters/${CLUSTER_NAME}/ssh/ca -I ${HOST}' host key' -n ${HOST},${HOST_IP},localhost,127.0.0.1,${SHORT_HOST} -V -5m:+3650d -h *_key.pub
		echo "---> Creating ssh_known_hosts..."
		echo -n '@cert-authority * ' >ssh_known_hosts
		cat ${DIRN}/ssh/ca.pub >>ssh_known_hosts
		echo "---> Copying back to host..."
		for KEY in dsa ecdsa ed25519 rsa ; do
			if [ -e ssh_host_${KEY}_key-cert.pub ] ; then
				${SCP} -o StrictHostKeyChecking=no ssh_host_${KEY}_key-cert.pub ${HOST}:/etc/ssh/
			fi
		done
		${SCP} -o StrictHostKeyChecking=no ssh_known_hosts ${HOST}:/etc/ssh/
		echo "---> Computing sshd_config..."
		for CERT in $(ls *-cert.pub) ; do
			if ! grep -q "HostCertificate /etc/ssh/${CERT}" sshd_config ; then
				echo "HostCertificate /etc/ssh/${CERT}" >>sshd_config
			fi
		done
		${SCP} -o StrictHostKeyChecking=no sshd_config ${HOST}:/etc/ssh/
		echo "---> Restarting ssh service..."
		ssh -i /etc/openstack-cluster-installer/id_rsa -o StrictHostKeyChecking=no ${HOST} "/etc/init.d/ssh restart"
		echo "---> Fixing rights"
		chown -R www-data:www-data $i/oci-in-target/etc/ssh
	fi
done
cd ${MY_CWD}
