#!/usr/bin/bash
#
# MySQL Initialisation
#
# Usage: $0 [--force] [ExecStartPost] [--force]
#
# Note that --force will overwrite existing passwords/settings
# but will fail if the root user is unable to connect to the database
# using the credentials in /root/.my.cnf (if any exist)
#

FORCE=
if [ "$1" == "--force" ]; then
	FORCE="$1"
	shift
fi

CALLER="$1"
shift

# Check again in case  the --force was after CALLER instead of before
if [ "$1" == "--force" ]; then
	FORCE="$1"
	shift
fi

# Basic database setup including "common" schemas and root credentials
if [ -n "$FORCE" ] || [ ! -f /root/.my.cnf ] || ! grep -Pq '^\s*password\s*=' /root/.my.cnf; then

	if ! env HOME=/root mysqladmin ping >&/dev/null; then
		systemctl start mysqld
		systemctl --quiet enable mysqld
	fi

	PASSWD=$(/usr/libexec/ng-server-config/mk-auth-token mysql:root@localhost 16)

	# The "local" database is ignored for replication (but still binlogged)
	env HOME=/root mysql -NB -e 'CREATE DATABASE IF NOT EXISTS local;'
	# The "unlogged" database is not binlogged (and therefore not replicated)
	env HOME=/root mysql -NB -e 'CREATE DATABASE IF NOT EXISTS unlogged;'

	# Crude success check
	if [ -d /var/lib/mysql/local ]; then

		env HOME=/root mysql -NB -e "SET PASSWORD FOR 'root'@'localhost' = PASSWORD('$PASSWD');"

		# (Re)set the client password in root's .my.cnf
		augtool --noautoload --autosave <<-EOD
			set /augeas/load/MySQL/lens "MySQL.lns"
			set /augeas/load/MySQL/incl "/root/.my.cnf"
			load
			set /files/root/.my.cnf/target[.='client'] 'client'
			set /files/root/.my.cnf/target[.='client']/password '$PASSWD'

			set /files/root/.my.cnf/target[.='mysql'] 'mysql'
			set /files/root/.my.cnf/target[.='mysql']/ssl-cipher 'DHE-RSA-AES256-SHA'

                        set /files/root/.my.cnf/target[.='mysqldump'] 'mysqldump'
			set /files/root/.my.cnf/target[.='mysqldump']/ssl-cipher 'DHE-RSA-AES256-SHA'

			set /files/root/.my.cnf/target[.='mysqladmin'] 'mysqladmin'
			set /files/root/.my.cnf/target[.='mysqladmin']/ssl-cipher 'DHE-RSA-AES256-SHA'

		EOD

		# Make sure the permissions are secure too...
		chmod 0640 /root/.my.cnf

		ln -St /root/.my.cnf /.my.cnf
	else
		echo "$(basename $0): Basic MySQL setup failed, aborting" >&2
		exit 1
	fi
elif [ "$CALLER" != "ExecStartPost" ]; then
	echo "$(basename $0): Skipping MySQL root password setup as it appears to already be configured, specify --force to override" >&2
fi

if env HOME=/root mysqladmin ping >&/dev/null; then

	# These are repeated from above since they are idempotent and this section runs every time
	# The "local" database is ignored for replication (but still binlogged)
	env HOME=/root mysql -NB -e 'CREATE DATABASE IF NOT EXISTS local;'
	# The "unlogged" database is not binlogged (and therefore not replicated)
	env HOME=/root mysql -NB -e 'CREATE DATABASE IF NOT EXISTS unlogged;'

	# Drop the test database, remove anonymous users, remove remote root logins
	env HOME=/root mysql -NB -e "DROP DATABASE IF EXISTS test;"
	env HOME=/root mysql -NB -e "DELETE FROM mysql.user WHERE (User = '') OR (User = 'root' AND Host <> 'localhost' AND Password = '');"


	# Load the timezone data if the table is empty
	if [ "0" == "$(env HOME=/root mysql -NB -e "SELECT COUNT(*) FROM mysql.time_zone_name" 2>/dev/null)" ]; then
		CMD_LOADTZDATA=`command -v mysql_tzinfo_to_sql 2>/dev/null`
		DIR_ZONEINFO=/usr/share/zoneinfo/posix
		$CMD_LOADTZDATA $DIR_ZONEINFO | env HOME=/root mysql mysql
	fi

	# Don't do replication setup from ExecStartPost, since we'll trigger a restart of mysqld
	[ "$CALLER" == "ExecStartPost" ] && exit 0;
	
	
	# Configure the cluster if details are provided AND replication hasn't already been configured
	# TODO: We should split this up so that 
	# TODO : Appears to be broken for newer versionf of MySQL, 'SHOW SLAVE STATUS' returns nothing
	if [ -f /etc/sysconfig/ng-kickstart ]; then
		if [ -z "$FORCE" ] && env HOME=/root mysql -BEe 'SHOW SLAVE STATUS' | grep -qP 'Master_Host:\s*\S'; then
			echo "$(basename $0): Skipping MySQL replication setup as Master_Host: appears to be already set, specify --force to override" >&2
		else
			source /etc/sysconfig/ng-kickstart
			if [[ -n "$clustersoa" && -n "$clusterhosts" ]]; then
				env HOME=/root /usr/libexec/ng-server-config/init-mysql-cluster $FORCE \
					"${clustersoa}${clusterdomain:+.$clusterdomain}" \
					"${clusterhosts%%,*}${clustersoa:+.$clustersoa}${clusterdomain:+.$clusterdomain}" \
					"${clusterhosts##*,}${clustersoa:+.$clustersoa}${clusterdomain:+.$clusterdomain}"

				env HOME=/root /usr/libexec/ng-server-config/join-mysql-cluster $FORCE \
					"$HOME/mysql-cluster/X.509/${clustersoa}${clusterdomain:+.$clusterdomain}"
			else
				echo "$(basename $0): Skipping MySQL replication setup as clustersoa and/or clusterdomain are not defined in /etc/sysconfig/ng-kickstart" >&2
			fi
		fi
	else
		echo "$(basename $0): Skipping MySQL replication setup as /etc/sysconfig/ng-kickstart does not exist" >&2
	fi
	
fi

