#!/bin/bash
#
# Copyright 2013 Hewlett-Packard Development Company, L.P.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

set -eux
set -o pipefail

DISTRO=`lsb_release -si`

# Quietly go away unless a migration has been asked for
DEFAULTS=/etc/mysql/migration_default
[ -e $DEFAULTS ] || exit 0
source $DEFAULTS

DONE_FILE=/etc/mysql/migration_done
if [ -e $DONE_FILE ] ; then
    echo migration from [$MIGRATION_HOST] already completed.
    ls -l $DONE_FILE
    exit 0
fi

# MySQL may be stopped pre-configuration, so try to start it
if [ -d /etc/init ] && [ "$DISTRO" = "Ubuntu" ] ; then
    # Upstart: During initial boot, mysql will start in parallel with os-refresh-config
    # wait-for-state is a job that allows blocking until a particular state is reached.
    start wait-for-state WAIT_FOR=mysql WAITER=$(basename $0) WAIT_FOREVER=Y TARGET_GOAL=start WAIT_STATE=running
else
    service mysql start || service mysqld start || :
fi

local_mysql() {
    if [ -e /root/.my.cnf ] ; then
        mysql --defaults-extra-file=/root/.my.cnf "$@"
    else
        mysql "$@"
    fi
}

local_mysql -e 'SHOW GRANTS'
# This runs as root. We assume root has a .my.cnf or access
# via localhost.
if [ -n "$MIGRATION_HOST" ] ; then
    local_mysql -e 'STOP SLAVE' || :
    # If we are planning on setting up a full slave
    SLAVE_OPTS=""
    if [ -n "$MIGRATION_USER" ] && [ -n "$MIGRATION_PASSWORD" ] ; then
        local_mysql -e "CHANGE MASTER TO master_host='${MIGRATION_HOST}', master_user='${MIGRATION_USER}', master_password='${MIGRATION_PASSWORD}'"
        SLAVE_OPTS="--master-data"
    fi
    mysqldump --defaults-extra-file=/root/metadata.my.cnf \
        -u $MIGRATION_DUMP_USER \
        --single-transaction \
        --all-databases \
        $SLAVE_OPTS -h $MIGRATION_HOST | local_mysql

    # After this following command, our ~/.my.cnf may stop working as its
    # password may change due to the dump loaded above.
    local_mysql -e 'FLUSH PRIVILEGES'

    # Now that database has been loaded, use creds that should match
    cp -f /root/metadata.my.cnf /root/.my.cnf
    # Now get the slave going if creds were provided
    if [ -n "$MIGRATION_USER" ] && [ -n "$MIGRATION_PASSWORD" ] ; then
        local_mysql -e "START SLAVE"
    fi
    touch $DONE_FILE
fi
