#! /bin/bash -ex

# NOTE: this is deprecated and probably unnecessary. (-kn)

# prepare secondary/tertiary mysql configuration
# - check slave configuration
# - force monit configuration
# - force nagios configuration

source ${ADDITIONAL_MYSQL_DESCRIPTOR}

[ -z "${DESCRIPTOR_NAME}" ] && echo "Missing parameter: DESCRIPTOR_NAME" >/dev/stderr && exit 1
[ -z "${CONFIG_DIR}" ] &&
	CONFIG_DIR="/etc/mysql-${DESCRIPTOR_NAME}"

[ -z "${CONFIG_FILE}" ] &&
	CONFIG_FILE="${CONFIG_DIR}/my.cnf"

[ -z "${DATA_DIR}" ] &&
	DATA_DIR="/var/lib/mysql-${DESCRIPTOR_NAME}"

[ -z "${LOG_DIR}" ] &&
	LOG_DIR="/var/log/mysql-${DESCRIPTOR_NAME}"

[ -z "${LOCK_DIR}" ] &&
	LOCK_DIR="/var/run/mysqld-${DESCRIPTOR_NAME}"

echo "DESCRIPTOR_NAME: ${DESCRIPTOR_NAME}"
echo "CONFIG_DIR: ${CONFIG_DIR}"
echo -n "- exists? "
if [ -d "${CONFIG_DIR}" ]; then
	echo "yes"

else
	echo "creating"
	mkdir -p ${CONFIG_DIR}

	echo "- creating minimalistic config"
	cat > ${CONFIG_FILE} <<-EOF
		[mysqld]
		user		= mysql
		pid-file	= ${LOCK_DIR}/mysqld.pid
		socket		= ${LOCK_DIR}/mysqld.sock
		port		= 3306
		basedir		= /usr
		datadir		= ${DATA_DIR}
		tmpdir		= /tmp
		lc-messages-dir	= /usr/share/mysql
		skip-external-locking
		key_buffer		= 16M
		max_allowed_packet	= 16M
		thread_stack		= 192K
		thread_cache_size	= 8
		myisam-recover		= BACKUP
		query_cache_limit	= 1M
		query_cache_size	= 16M
		expire_logs_days	= 10
		max_binlog_size		= 100M

		max_connections		= 250
		max_connect_errors	= 50
		open_files_limit	= 262144
		innodb_open_files	= 262144
		optimizer_search_depth	= 0

		key_buffer_size		= 256M
		max_allowed_packet	= 20M
		thread_stack		= 192K
		thread_cache_size	= 100
		table_open_cache	= 65536
		table_definition_cache	= 65536
		max_heap_table_size	= 256M
		tmp_table_size		= 256M
		sort_buffer_size	= 256K
		read_buffer_size	= 128K
		read_rnd_buffer_size	= 256K
		myisam_sort_buffer_size	= 64M

		log-error		= ${LOG_DIR}/mysql-err.log
		log-warnings		= 2

		myisam-recover-options	= BACKUP,FORCE

		query_cache_limit	= 10M
		query_cache_size	= 256M
		query_cache_type	= 1

		innodb_buffer_pool_size		= 1024M
		innodb_log_file_size		= 1024M
		innodb_log_buffer_size		= 16M
		innodb_flush_log_at_trx_commit	= 0
		innodb_thread_concurrency	= 0
		innodb_read_io_threads		= 64
		innodb_write_io_threads		= 64
		innodb_io_capacity		= 50000
		innodb_file_per_table
		innodb_additional_mem_pool_size	= 256M
		transaction-isolation		= READ-COMMITTED
		innodb_support_xa		= 0
		innodb_commit_concurrency	= 0
		innodb_old_blocks_time		= 1000


		[mysqldump]
		quick
		quote-names
		max_allowed_packet	= 16M

		[mysql]


		[isamchk]
		key_buffer		= 16M
	EOF
	
fi

echo "CONFIG_FILE: ${CONFIG_FILE}"
echo -n "- exists? "
if [ -e "${CONFIG_DIR}/my.cnf" ]; then
	echo "yes"

else
	echo "FATAL"
	exit 1
fi

echo "DATA_DIR: ${DATA_DIR}"
echo -n "- ${CONFIG_FILE} configured to use ${DATA_DIR}?"
if [ "$(grep datadir ${CONFIG_FILE} | grep -v ${DATA_DIR})" -lt 1 ]; then
	echo "yes"
else
	echo "FATAL"
	exit 1
fi
