#! /bin/sh

# run-msqld - A wrapper for msqld
# Copyright (c) 1997  Martin Schulze <joey@debian.org>
# 
# 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; either version 2 of the License, or
# (at your option) any later version.
# 
# 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.,59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
# This script is written especially for Debian GNU/Linux.

cfg=/etc/msql.acl
TMPDIR=/var/log/msql
prg=msqld

while :
do

    # Read the configuration
    #
    ADMIN=`grep '^#[ ]*MailTo=' $cfg|sed 's/^#[ ]*MailTo=\(.*\)$/\1/g'`
    SUPPRESS=`grep '^#[ ]*SuppressMail=' $cfg|sed 's/^#[ ]*SuppressMail=\(.*\)$/\1/g'`
    MSQL_DEBUG=`grep '^#[ ]*Debug=' $cfg|sed 's/^#[ ]*Debug=\(.*\)$/\1/g'`
    export MSQL_DEBUG

    rm -f ${TMPDIR}/* > /dev/null 2>&1

    touch ${TMPDIR}/${prg}.$$
    chmod 600 ${TMPDIR}/${prg}.$$
    /usr/sbin/${prg} > ${TMPDIR}/${prg}.$$ 2>&1

    if [ -s ${TMPDIR}/${prg}.$$ -a "`grep '^\[msqld\]' | wc -l`" -gt 0 ]; then
	if [ "$SUPPRESS" = "no" -a -x /usr/lib/sendmail ]; then
	    (printf "Subject: Mini SQL Crash Report\nTo: %s\n" ${ADMIN}
	     echo
	     echo "Program: $prg"
	     echo "Date   : `date`"
	     echo
	     echo "Program Output"
	     echo "--------------"
	     echo
	     cat ${TMPDIR}/${prg}.$$
	    )| /usr/lib/sendmail -t
	fi
    fi

    # Try to find out if another msqld (or other program) is already
    # running using our port
    other=`head -30 ${TMPDIR}/${prg}.$$ | grep 'Address already in use'|wc -l`
    rm -f ${TMPDIR}/${prg}.$$

    test $other -gt 0 && exit 0

    if [ ! -f /var/run/${prg}/shutdown ]; then
	sleep 15
    else
	rm -f /var/run/${prg}/shutdown /var/run/${prg}/${prg}.pid
	exit 0
    fi
done
