Charm: ~clint-fewbar:precise/elb   Revision: 5   Hook: elb-target-relation-joined
#!/bin/sh
#
set -ue

target_service=${JUJU_REMOTE_UNIT%%/*}

. `pwd`/elb_env.sh

my_instance_id=`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id`
my_az=`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone`

# if elb for service X does not exist
#   create elb for service X
if ! elb-describe-lbs $target_service ; then	
	DNS_NAME=`elb-create-lb $target_service --availability-zones $my_az \
                      --listener "protocol=tcp, lb-port=80, instance-port=80"`
	juju-log "Created ELB - $DNS_NAME in Availability Zone $my_az"
	echo $DNS_NAME > touched_elb_${target_service}
else
    echo UNKNOWN > touched_elb_${target_service}
fi
# register local instance with elb for service X
elb-register-instances-with-lb $target_service --instances $my_instance_id

found=0
for zone in "`config-get availability-zones`" ; do
    if [ "$zone" = "$my_az" ] ; then
        found=1
    fi
done
if [ $found -eq 0 ] ; then
    exit 0
fi
# Now wait for us to come online and then make sure our AZ is registered
limit=120
while ! elb-describe-instance-health $target_service --instances $my_instance_id |grep InService ; do
    sleep 1
    limit=$((limit-1))
    if [ $limit -lt 1 ] ; then
        juju-log -l ERROR "Timed out waiting for instance health check."
        exit 1
    fi
done
elb-enable-zones-for-lb $target_service --availability-zones $my_az