#! /bin/sh -e
#
# Copyright 2004,2006 Stefan Hornburg (Racke) <racke@linuxia.de>
#
# 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.

# source debconf library
. /usr/share/debconf/confmodule

conffile=/etc/sympa/sympa.conf

db_get sympa/db_configured

if [ "$RET" = "false" ]; then
    db_get sympa/db_type
    db_type="$RET"

	db_get sympa/db_authtype
	db_authtype="$RET"

	# create database if missing
	db_get sympa/db_adminpasswd
	adminpassfile=`tempfile -m 0600`
	cat <<EOT >> $adminpassfile
$RET
EOT
	OPTS="-a $adminpassfile"

	db_get sympa/db_passwd
	userpassfile=`tempfile -m 0600`
	cat <<EOT >> $userpassfile
$RET
EOT
	
	db_get sympa/db_name
	db_name="$RET"

	db_get sympa/db_hostname
	db_hostname="$RET"

	db_get sympa/db_port
	if [ "$RET" ]; then
		OPTS="-p $RET $OPTS"
	fi

	db_get sympa/db_options
	if [ "$RET" ]; then
		OPTS="-o $RET $OPTS"
	fi
	
	db_get sympa/db_user
	if [ "$RET" ]; then
		OPTS="-w $RET $OPTS"
	fi

	case $db_type in
		"PostgreSQL")
			db_get sympa/db_authtype
			if [ "$RET" = "Ident-based" ]; then
				OPTS="-i $OPTS"
			fi
			/usr/share/sympa/db/install-pg-db $OPTS -d "$db_name" -h "$db_hostname" -u "$userpassfile"
		    ;;
		"MySQL")
			/usr/share/sympa/db/install-mysql-db $OPTS -d "$db_name" -h "$db_hostname" -u "$userpassfile"
		    ;;
	esac
fi

sympaerrors=`tempfile -m 0600`

if /usr/lib/sympa/bin/sympa.pl -f $conffile --prepare_db 2>$sympaerrors; then
	db_set sympa/db_configured true
	rm -f $sympaerrors
else 
	cat $sympaerrors
	echo "Sympa failed to prepare database."
	rm -f $sympaerrors
	exit 1
fi

