#!/bin/bash

# The certificates live in leader-data. Grab them from there, always

source ~/.bash_aliases
mkdir -p etcd_credentials

if [ -z ${ETCDCTL_CERT_FILE} ]; then
    cp $ETCDCTL_CERT etcd_credentials/client.crt
    cp $ETCDCTL_KEY etcd_credentials/client.key
    cp $ETCDCTL_CACERT etcd_credentials/ca.crt
else
    cp $ETCDCTL_CERT_FILE etcd_credentials/client.crt
    cp $ETCDCTL_KEY_FILE etcd_credentials/client.key
    cp $ETCDCTL_CA_FILE etcd_credentials/ca.crt
fi
# Render a README heredoc
cat << EOF > etcd_credentials/README.txt
# ETCD Credentials Package

Greetings! This credentials package was generated for you by Juju. In order
to consume these keys, you will need to do a few things first:

Untarball the archive somewhere you wish to keep your sensitive client
credentials.

Export those locations as environment variables, set the etcdctl endpoint,
and expose the etcd service. Even though Etcd is currently configured to
validate SSL certificates before a connection can be established, it's best
practice to leave it firewalled from the world unless you have need of an
exposed etcd endpoint.

  juju expose etcd
  export ETCDCTL_KEY=$(pwd)/client.key
  export ETCDCTL_CERT=$(pwd)/client.crt
  export ETCDCTL_CACERT=$(pwd)/ca.crt
  export ETCDCTL_ENDPOINTS=https://$(unit-get public-address):2379
  etcdctl member list

If you have any trouble regarding connecting to your Etcd cluster, don't
hesitate to reach out over the juju mailing list: juju@lists.ubuntu.com

EOF

tar cfz etcd_credentials.tar.gz etcd_credentials
cp etcd_credentials.tar.gz /home/ubuntu/
rm -rf etcd_credentials
