#!/bin/sh

help () {
    cat <<EOF
Usage: `basename $0` [command] [option]
Where command must be either one of:
    check	Verify that the database is usable by Roxen3
    delete	Delete all traces of the Roxen3 installation from the database
    create	Update and modify the database for use by Roxen3

Option can be (in combination):
    force	Don't ask, just do it (DANGEROUS!)
    verbose	Show output and success messages
EOF
    exit 1
}

# --------------------------
# Get command line options etc
if [ -z "$1" ]; then
    help
else
    for arg in $*; do
	case "$arg" in
	    delete)
		ACTION=delete
		;;
	    check)
		ACTION=check
		;;
	    create)
		ACTION=create
		;;
	    force)
		FORCE=1
		;;
	    verbose)
		VERBOSE=1
		;;
	    *)
		help
		;;
	esac
    done
fi

# --------------------------
# Get the runtime options (host, user etc)
if [ -f /etc/default/roxen3 ]; then
    . /etc/default/roxen3
else
    echo "Don't know which MySQL server I should talk to..."
    exit 1
fi

if [ "$MYSQL_HOST" = "localhost" ]; then
    ROXEN_HOST="localhost"
else
    # If you're running your MySQL on a remote host,
    # MySQL needs to be updated with the knowledge of
    # what host have access to what. This host is
    # The Roxen Webserver host

    ROXEN_HOST="`/bin/hostname`"
fi

if [ -S /var/cache/roxen3/socket ]; then
    # Locally used MySQL.
    HOST="-S /var/cache/roxen3/socket"
    DBPASS=''

    if mysqladmin $HOST -u roxen3 --password="" ping > /dev/null 2>&1; then
	DBUSER="-u roxen3"
    else
	# Failed connecting with user 'roxen3'. Try original 'rw'.
	if mysqladmin $HOST -u rw --password="" ping > /dev/null 2>&1; then
	    DBUSER="-u rw"
	else
	    cat <<EOF
Did not manage to connect to the MySQL database through a local socket. Don't
quite know how to continue. The command that failed was:

    mysqladmin $HOST -u DBUSER --password="" ping

I first tried user 'roxen3' but that didn't work and neither did 'rw'...
EOF
	    exit 1
	fi
    fi
else
    HOST="-h $MYSQL_HOST"
fi

# --------------------------
# Output warning before proceeding
if [ -z "$FORCE" -a "$ACTION" != "check" ]; then
    case "$ACTION" in
	delete)
	    # We're deleting all references to the Roxen3 installation
	    echo "This script will remove all traces of the Roxen3 installation from the MySQL"
	    echo -n "database. Are you prepared to do this [Y/n]? "
	    ;;
	create)
	    # We're not deleting the Roxen3 tables etc
	    echo "This script will create the database 'roxen3' where the Roxen webserver will"
	    echo -n "store it's cache etc. Are you prepared to do this [Y/n]? "
	    ;;
    esac

    read create
    if echo $create | grep -iq ^n; then
	exit 0
    fi
fi

# --------------------------
# Look for a working user/password combination
if [ -z "$DBUSER" -a -f /root/.my.cnf -a ! -S /var/cache/roxen3/socket ]; then
    DBUSER=`cat /root/.my.cnf | grep ^user | sed 's@.*= @@'`
    DBPASS=`cat /root/.my.cnf | grep ^pass | sed 's@.*= @@'`

    if ! mysqladmin $HOST -u "$DBUSER" --password="$DBPASS" ping > /dev/null 2>&1; then
	# Failed to connect with user/pass combo!
	echo "Failed to connect as $DBUSER, with password (password omitted)."

	if [ "$MYSQL_HOST" = "localhost" ]; then
	    if ! dpkg -l mysql-server > /dev/null 2>&1; then
		echo ; echo -n "ERROR: "
		echo "You've opted to use an external MySQL server on"
		echo "localhost but the package 'mysql-server' isn't installed."
		echo "Please install that before continuing."
		echo
	    fi
	fi

	exit 1
    fi

    DBUSER="-u $DBUSER" ; DBPASS="--password=$DBPASS"
fi

# --------------------------
if [ -z "$DBUSER" -a -z "$DBPASS" ]; then
    # We do not have a user/password combination - die!
    cat <<EOF
Could not find a username/password pair to try connecting with. I was
assuming that it would be located in /root/.my.cnf, but that file
didn't exists (or it didn't contain a username and/or password).

Don't know how to continue without that.
EOF
    exit 1
fi

# --------------------------
# Do our magic - create, delete or check.
case "$ACTION" in
    delete)	# ==========================
	# Remove traces of the Roxen3 installation
	OUTPUT=`cat /usr/share/doc/roxen3/mysql/roxen3.sql-rem | \
	    mysql $HOST -f $DBUSER $DBPASS mysql 2>&1`
	exitcode=$?
	if [ "$exitcode" = "0" ]; then
	    [ ! -z "$VERBOSE" ] && echo "Successfully removed database and all traces of the roxen3 installation"
	    exit 0
	else
	    # Failed to remove database etc
	    cat <<EOF
I could not create databases and do the modifications necessary
to get the MySQL database to work with Roxen 3. The command that
failed was:

    cat /usr/share/doc/roxen3/mysql/roxen3.sql-rem | \\
	mysql $HOST -f $DBUSER --password=(password omitted) mysql

The output from the command was:

    $OUTPUT
EOF
	    exit 1
	fi
	;;

    create)	# ==========================
	# Create database(s) and update rights
	OUTPUT=`cat /usr/share/doc/roxen3/mysql/roxen3.sql-add | \
	    sed "s@%ROXEN_HOST%@$ROXEN_HOST@" | \
	    mysql $HOST -f $DBUSER $DBPASS mysql 2>&1`
	exitcode=$?
	if [ "$exitcode" = "0" ]; then
	    if [ ! -S /var/cache/roxen3/socket -a ! -f /var/cache/roxen3/mysql/user.MYD ]; then
		# Make sure the init script know that it's not Roxen3 MySQL only
		cat <<EOF > /etc/default/roxen3.mysqld
This file is just a place holder to tell the Roxen 3.3
Webserver init script (/etc/init.d/roxen3) that we're
not running the MySQL server solely for Roxen, but for
other uses as well. Please DON'T delete this file.
EOF
	    fi

	    [ ! -z "$VERBOSE" ] && echo "Successfull in creating databases and all modifications"
	    exit 0
	else
	    # Failed to create the databases
	    cat <<EOF
I could not create databases and do the modifications necessary
to get the MySQL database to work with Roxen 3. The command that
failed was:

    cat /usr/share/doc/roxen3/mysql/roxen3.sql-add | \\
        sed "s@%ROXEN_HOST%@$ROXEN_HOST@" | \\
        mysql $HOST -f $DBUSER $DBPASS mysql

The output from the command was:

    $OUTPUT
EOF
	    exit 1
	fi
	;;

    check)	# ==========================
	# Is there such a database as 'roxen3'?
	[ ! -z "$VERBOSE" ] && echo -n "Looking for database 'roxen3': "
	COUNT=`mysqlshow $HOST $DBUSER $DBPASS 2>&1 | grep roxen3 | wc -l | sed 's@\ @@g'`
	if [ "$COUNT" = "0" ]; then
	    # No such database!
	    [ ! -z "$VERBOSE" ] && echo "no such database."
	    exit 1
	else
	    # Database exists. Look for the roxen3 user
	    [ ! -z "$VERBOSE" ] && echo "exists."
	    [ ! -z "$VERBOSE" ] && echo -n "Looking for username 'roxen3': "
	    COUNT=`mysql $HOST -f $DBUSER $DBPASS mysql \
		--batch --skip-column-names --execute="select * from user where user='roxen3';" \
		2> /dev/null | wc -l | sed 's@\ @@g'`
	    if [ "$COUNT" = "0" ]; then
		# No 'roxen3' user!
		[ ! -z "$VERBOSE" ] && echo "no such user."
		exit 1
	    else
		[ ! -z "$VERBOSE" ] && echo "exists."
	    fi
	fi
	;;
esac

exit 0
