#!/bin/bash
#
# Add a new key to kxc's configuration (initializing it if necessary).
#
# If /etc/kxc is missing, this script creates it, as well as the required
# client certificates.
#
# Then, it adds configuration for fetching a given key.

set -e

SERVER="$1"
KEYNAME="$2"

if [ "$SERVER" = "" ] || [ "$KEYNAME" = "" ]; then
	echo "
Usage: kxc-add-key <server hostname> <key name>

This command adds a new key to kxc's configuration, initializing it if
necessary.
"
	exit 1
fi


# Create the base configuration directory.
echo "Creating directories (/etc/kxc/)"
mkdir -p /etc/kxc/

# Create a private key for the client.
if ! [ -e /etc/kxc/key.pem ]; then
	kxgencert \
		-organization "kxc@$HOSTNAME" \
		-key /etc/kxc/key.pem \
		-cert /etc/kxc/cert.pem
	chmod 400 /etc/kxc/key.pem
else
	echo "Private key already exists (/etc/kxc/key.pem)"
fi

echo "Setting URL to kxd://$SERVER/$HOSTNAME/$KEYNAME"
echo "kxd://$SERVER/$HOSTNAME/$KEYNAME" > "/etc/kxc/${KEYNAME}.url"

echo
echo
echo "YOU need to copy the server certificate to"
echo "/etc/kxc/${KEYNAME}.server_cert.pem. For example, using:"
echo
echo "  $ scp $SERVER:/etc/kxd/cert.pem /etc/kxc/${KEYNAME}.server_cert.pem"
echo
