#!/usr/bin/openrc-run
extra_stopped_commands="setup"

retry="60"
piddir="/run/mysqld"
pidfile="$piddir/$RC_SVCNAME.pid"
command="/usr/bin/mariadbd-safe"
command_args="--syslog --nowatch --pid-file=$pidfile"

depend() {
	use net.lo
	need localmount
	keyword -timeout
}

start_pre() {
	required_dirs=$(getconf datadir "/var/lib/mysql")
	checkpath -d --owner mysql:mysql --mode 0755 "$piddir"

	if [ ! -d $required_dirs/mysql ]; then
		eerror "Datadir '$required_dirs' is empty or invalid."
		eerror "Run '/etc/init.d/mariadb setup' to create new database."
	fi
}

start_post() {
	ewaitfile 10 $(getconf socket "/run/mysqld/mysqld.sock")
}

setup() {
	ebegin "Creating a new MySQL database"
	mariadb-install-db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
	eend $?
}

getconf() {
	v=$(my_print_defaults --mysqld | grep ^--$1)
	[ -z $v ] && echo $2 || echo ${v#*=}
}
