#!/bin/sh
# $OpenBSD: INSTALL,v 1.5 2000/04/08 06:06:25 brad Exp $
#
# Pre/post-installation setup of MySQL

# exit on errors, use a sane path and install prefix
#
set -e
PATH=/bin:/usr/bin:/sbin:/usr/sbin
PREFIX=${PKG_PREFIX:-/usr/local}
DB_DIR=${PKG_DB_DIR:-/var/mysql}

MYSQLGID=40
MYSQLUID=40

# Function: tell the user that an existing database directory was
#	    found on their system
do_notice_pre_install()
{
    echo
    echo "+---------------"
    echo "| You appear to already have a MySQL database directory in ${DB_DIR}"
    echo "|"
    echo "| In order to preserve your existing data, you should:"
    echo "|          - dump all your databases"
    echo "|          - kill MySQL if it's running"
    echo "|          - delete the ${DB_DIR} directory"
    echo "|          - install MySQL"
    echo "|          - start up MySQL"
    echo "|          - re-create all of your database"
    echo "|          - re-load your data"
    echo "+---------------"
    echo
    exit 1
}

# Function: install the MySQL user account and group
#
do_pre_install()
{
# Add group 'mysql' to /etc/group
if [ "`egrep '^mysql:' /etc/group`" = "" ]; then
      	echo "===> Creating mysql group, gid $MYSQLGID"
        echo "mysql:*:${MYSQLGID}:" 2>/dev/null >> /etc/group || {
             echo "===> Problem creating group mysql" >&2
             exit 1
        }
fi

# Add user 'mysql' in /etc/passwd
if [ "`egrep '^mysql:' /etc/passwd`" = "" ]; then
        echo "===> Creating mysql user, uid $MYSQLUID"
	adduser -batch mysql mysql "MySQL Account" "" -uid_start ${MYSQLUID} > /dev/null 2>&1 /dev/null
	if [ $? -eq 0 ]; then
		echo "===> Using account mysql for MySQL, uid $MYSQLUID, gid $MYSQLGID"
	else
		echo "===> Problem creating account mysql"
		exit 1
	fi
fi
}

# Function: create database directory and the initial database
#
do_post_install()
{
install -d -o mysql -g mysql -m 775 ${DB_DIR}

# The shell is switched back to /bin/sh to ensure that the database
# creation can proceed successfully
chpass -s /bin/sh mysql
su mysql -c ${PREFIX}/bin/mysql_install_db
chpass -s /sbin/nologin mysql
}

# Verify/process the command
#
case $2 in 
    PRE-INSTALL)
	if [ -d $DB_DIR ]; then
	    do_notice_pre_install $1
	fi
	do_pre_install
	;;
    POST-INSTALL)
	do_post_install
	;;
    *)
	echo "usage: $0 distname { PRE-INSTALL | POST-INSTALL }" >&2
	exit 1
	;;  
esac

exit 0
