#!/bin/sh

if [ ! -z $DESTDIR ];then
    echo "Creating the Debian package, exit..."
    exit
fi

set -e

echo

# ===========================
# Create the MSQL database...
if ! grep -q "tcpquota" /etc/msql.acl; then
    echo -n "Creating the tcpquota MSQL database config... "

    # Create the config file entry...
    cat >>/etc/msql.acl <<EOF

database=tcpquota
read=*
write=root
host=*
access=local,remote

EOF
    echo "done."
else
    echo "The entry for tcpquota already exists in \`/etc/msql.acl', good..."
fi

chown msql.msql /etc/msql.acl

if [ ! -d /var/lib/msql/msqldb/tcpquota ]; then
    echo -n "Configuring the actual database...            "

    # Create the database...
    su msql -c "/usr/sbin/msqladmin create tcpquota" >/dev/null

    # Fill the database with tables...
    cat /usr/lib/tcpquota/create_database.sql | msql tcpquota      >/dev/null

    echo "done."

    echo -n "Restarting the MSQL daemon...                 "
    su msql -c "/usr/sbin/msqladmin reload" >/dev/null
    echo "done."

    echo -n "Updating runlevels...                         "
    /usr/sbin/update-rc.d tcpquotad defaults 92 >/dev/null
    echo "done."

    echo -n "Touching PID and LOG files...                 "
    touch /var/run/tcpquotad.pid
    touch /var/log/tcpquotad.log
    echo "done."
else
    echo "The database seem to already exist, make sure it contains all the"
    echo "relevant columns... "

    # -------------------

    msqldump tcpquota masq | grep 'open INT' > /dev/null
    if [ "$?" != "0" ]; then
	echo -n " nope, adding the column 'open'... "
	TMP_FILE=`mktemp -q /tmp/$0.XXXXXX`
        if [ $? -ne 0 ]; then
	    echo "$0: Can't create temp file, exiting..."
	    exit 1
	fi

	# Get a dump of the current table...
	msqldump tcpquota masq > $TMP_FILE

	# Drop the current table...
	cat <<EOF | msql tcpquota > /dev/null
drop table masq\g
EOF

	# Change/Add a column with value...
	sed -e 's/count INT/counter INT/' \
	    -e 's/counter INT/counter INT, open INT/' \
	    -e 's/)\\g/\,0)\\g/' \
	    < $TMP_FILE | msql tcpquota > /dev/null

	# Remove the temp file...
	rm -f $TMP_FILE

	echo "done."
    else
        echo "yes, good!"
    fi
fi

# ===========================
# Reconfigure for this specific host...
if [ -f /etc/tcpquota/tcpquota.cf ] && grep -i -q %SERVER% /etc/tcpquota/tcpquota.cf; then
    echo
    echo "The package should be reconfigured for your host to be able to work propperly"
    echo -n "Would you like to do this now? (Y/n)"
    read s
    if [ "$s" != "n" ]; then
	/usr/lib/tcpquota/tcpquotaconfig
    else
	echo
	echo "Oki then, you can always do this later, with the help of the program '/usr/lib/tcpquota/tcpquotaconfig'"
	echo
    fi
fi

if [ -f /etc/tcpquota/tcpquota.cf ] && ! grep -i -q %SERVER% /etc/tcpquota/tcpquota.cf; then
    /etc/init.d/tcpquotad start
fi
