#!/bin/sh
#
# Master side of master/slave replication

set -e

. /usr/share/charm-helper/sh/net.sh

ROOTARGS="-uroot -p`cat /var/lib/mysql/mysql.passwd`"
snapdir=/var/www/snaps
mkdir -p $snapdir
apt-get -y install apache2
# disable wide-open access (restrict to each db IP)
rhosts=""
remote_ip=""
for r in $(relation-ids master) ; do
    for runit in $(relation-list -r $r) ; do
        rhost=$(relation-get -r $r hostname $runit)
        if [ -n "$rhost" ] ; then
            rhosts=${rhosts},$rhost
            if [ "$runit" = "$JUJU_REMOTE_UNIT" ] ; then
                remote_ip=$rhost
                if ! ch_is_ip $remote_ip ; then
                    remote_ip=$(ch_get_ip $remote_ip)
                fi
            fi
        fi
    done
done
# remove any leading comma
rhosts=${rhosts##,}

# if there are no hosts, we simply disable all access
target=/etc/apache2/sites-available/mysql-dumps
cat > $target <<EOF
DocumentRoot /var/www
<Directory /var/www>
  Order deny,allow
  Deny from all
EOF
if [ -n "$rhosts" ] ; then
cat >> $target <<EOF
  allow from ${rhosts}
EOF
fi
cat >> $target <<EOF
  Options -Indexes
</Directory>
EOF
a2ensite mysql-dumps
a2dissite default
service apache2 reload

pass=`pwgen -s 16`
# TODO: settings.. make mmin tunable as it is highly subjective
recent_backup=`find $snapdir -name 'replication_seed.*.sql.gz' -mmin -60|head -1`
if [ -z "$recent_backup" ] ; then
    name=replication_seed.`date +%Y%m%d%H%M%S`.sql.gz
    echo `date`: Creating snapshot $recent_backup
    # Assumes transactional storage -- MyISAM please GO AWAY
    mysqldump $ROOTARGS --add-drop-database --all-databases --single-transaction --master-data |gzip>$snapdir/$name
    # Make sure webserver can serve it
else
    name=`basename $recent_backup`
fi
chown -v -R www-data.www-data /var/www

user=${JUJU_REMOTE_UNIT%%/*}
action=$(basename $0)
action=${action##master-relation-}
case "$action" in
changed)
    mysql $ROOTARGS -e "GRANT REPLICATION SLAVE, REPLICATION CLIENT ON *.* TO \`$user\`@\`$remote_ip\` IDENTIFIED BY '$pass'"
    relation-set dumpurl=/snaps/$name \
                         user=$user \
                         password=$pass \
                         hostname=`unit-get private-address` \
                         port=3306
    ;;
departed)
    mysql $ROOTARGS -e "REVOKE REPLICATION SLAVE, REPLICATION CLIENT ON *.* FROM `$user`@`$remote_ip`"
    ;;
broken)
    # XXX Need some way to tie users to relation ID
    ;;
esac
