Charm: oneiric/couchbase   Revision: 6   Hook: cluster-relation-changed
#!/bin/bash
# This must be renamed to the name of the relation. The goal here is to
# affect any change needed by relationships being formed
# This script should be idempotent.

set -ux

MASTER_INSTALL_TIME=`facter couchbase-install-time`
MASTER_MEMBER=$JUJU_UNIT_NAME
COUCHBASE_USERNAME=`config-get cluster_username`
COUCHBASE_PASSWORD=`config-get cluster_password`

# Find out the oldest/first node
for MEMBER in `relation-list`
do
   INSTALL_TIME=`relation-get install-time ${MEMBER}`
   [ ${INSTALL_TIME} -lt ${MASTER_INSTALL_TIME} ] && MASTER_MEMBER=${MEMBER}
done

if [ ${JUJU_UNIT_NAME} != ${MASTER_MEMBER} ]; then
   # I am not the master node so, I need to join up with the master node
    /opt/couchbase/bin/couchbase-cli rebalance \
                 -u `relation-get username ${MASTER_MEMBER}` -p `relation-get password ${MASTER_MEMBER}` \
                 -c `relation-get ip ${MASTER_MEMBER}` \
                 --server-add=`facter couchbase-ip` \
                 --server-add-username=${COUCHBASE_USERNAME} \
                 --server-add-password=${COUCHBASE_PASSWORD}
fi

exit 0