#!/bin/bash

set -eu # -x for verbose logging to juju debug-log

hostname=`unit-get private-address`

# Get the mysql password that was generated by the install hook
password=`cat /var/lib/juju/mysql.passwd`

# Get the database name; this takes a service unit (ex: wordpress/0)
# and extracts just 'wordpress'
service=`echo $JUJU_REMOTE_UNIT | cut -d/ -f1` # split on /

# Determine if a database needs to be created for this service
existing_databases=`mysql --password="$password" --silent --execute 'show databases'`
for db in $existing_databases; do
    if [ "$db" = "$service" ] ; then
        juju-log "Database already exists, publishing details and exiting"
        service_password=`cat /var/lib/juju/$service.passwd`
        # Save these settings on the relation; this will trigger the remote
        # service unit
        relation-set database="$service" user="$service" password="$service_password"
        exit 0 # database already exists
    fi
done

# Generate a strong password for the database, using /dev/urandom
service_password=`pwgen 10 1`
# Store service password, new service units of same service would need it
echo $service_password >> /var/lib/juju/$service.passwd

# Create new database and corresponding security settings
juju-log "Creating new database and corresponding security settings"
mysqladmin --password="$password" create "$service"
echo "grant all on $service.* to $service identified by '$service_password'" | mysql --password="$password" --database="$service"
mysqladmin --password="$password" flush-privileges

# Save these settings on the relation; this will trigger the remote
# service unit
relation-set database="$service" user="$service" password="$service_password"
