#!/bin/sh

set -e

# Generate the key if not present
mkdir -p /etc/manila/.ssh
if ! [ -e /etc/manila/.ssh/id_rsa ] ; then
	ssh-keygen -t rsa -f /etc/manila/.ssh/id_rsa -P ""
	chown -R manila:manila /etc/manila/.ssh
fi

# Upload the key to OpenStack
. /root/manila-openrc
KEYPAIR=$(openstack keypair list -f value -c Name 2>/dev/null)
if [ -z "${KEYPAIR}" ] ; then
        openstack keypair create --public-key /etc/manila/.ssh/id_rsa.pub manila-ssh-key
fi

# Copy the key to the other controllers
MY_HOSTNAME=$(hostname --fqdn)
CTRL_LIST=$(cat /etc/hosts | grep controller | grep -v ${MY_HOSTNAME} | awk '{print $1}')
for CTRL in ${CTRL_LIST} ; do
	scp -r /etc/manila/.ssh root@${CTRL}:/etc/manila
	ssh root@${CTRL} "chown -R manila:manila /etc/manila/.ssh"
done
