#!/bin/bash

# Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA

# Scripts to run by MySQL systemd service
#
# Needed argument: pre
#
# pre mode  :  try to perform sanity check for configuration, log, data

get_path () {
	my_print_defaults mysqld | grep "$1" | cut -d= -f2 | tail -n 1
}

# Runs an arbitrary init sql file supplied in $1. Does not require login access
run_init_sql() {
	tmpdir=$(mktemp -d)
	chown mysql:mysql "$tmpdir"
	mysqld --user=mysql --init-file="$1" --socket="$tmpdir/mysqld.sock" --pid-file="$tmpdir/mysqld.pid" > /dev/null 2>&1
	result=$?
	rm -rf "$tmpdir"
	return $result
}

sanity () {
	MYSQLRUN=/var/run/mysqld
	MYSQLDATA=/var/lib/mysql
	MYSQLFILES=/var/lib/mysql-files
	MYSQLKEYRING=/var/lib/mysql-keyring
	MYSQLLOG=/var/log/mysql

	if [ ! -d ${MYSQLDATA} -a ! -L ${MYSQLDATA} ];
	then
		mkdir ${MYSQLDATA}
		chown mysql:mysql ${MYSQLDATA}
		chmod 750 ${MYSQLDATA}
	fi

	if [ ! -d ${MYSQLFILES} -a ! -L ${MYSQLFILES} ];
	then
		mkdir ${MYSQLFILES}
		chown mysql:mysql ${MYSQLFILES}
		chmod 770 ${MYSQLFILES}
	fi

	if [ ! -d ${MYSQLKEYRING} -a ! -L ${MYSQLKEYRING} ];
	then
		mkdir ${MYSQLKEYRING}
		chown mysql:mysql ${MYSQLKEYRING}
		chmod 750 ${MYSQLKEYRING}
	fi

	if [ ! "$(ls -A ${MYSQLDATA}/mysql)" ];
	then
		SQL=$(mktemp --tmpdir=/var/lib/mysql-files/)
		touch ${SQL}
		chmod 600 ${SQL}
		chown mysql:mysql ${SQL}

		cat << EOF > ${SQL}
USE mysql;
INSTALL PLUGIN auth_socket SONAME 'auth_socket.so';
ALTER USER 'root'@'localhost' IDENTIFIED WITH 'auth_socket';
SHUTDOWN;
EOF
		mysqld --initialize-insecure --user=mysql > /dev/null
		run_init_sql "$SQL"
		rm -f "$SQL"
	fi

	if [ -x /usr/bin/mysql_ssl_rsa_setup -a ! -e "${MYSQLDATA}/server-key.pem" ];
	then
		/usr/bin/mysql_ssl_rsa_setup --datadir="${MYSQLDATA}" --uid=mysql >/dev/null 2>&1
	fi

	if [ ! -d ${MYSQLLOG} -a ! -L ${MYSQLLOG} ];
	then
		mkdir ${MYSQLLOG}
		chown mysql:adm ${MYSQLLOG}
		chmod 750 ${MYSQLLOG}
		touch ${MYSQLLOG}/error.log
		chmod 640 ${MYSQLLOG}/error.log
		chown mysql:adm ${MYSQLLOG}/error.log
	fi

	/lib/init/apparmor-profile-load usr.sbin.mysqld

	if [ ! -r /etc/mysql/my.cnf ]; then
		echo "MySQL configuration not found at /etc/mysql/my.cnf. Please install one using update-alternatives."
		exit 1
	fi
}

case $1 in
	"pre")  sanity ;;
esac
