#! /bin/sh -e
#
# Copyright 2004, 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

if [ "$pass_required" = 1 ]; then
	# create temporary sympa configuration file with
	# adminstrative credentials

	db_get sympa/db_adminpasswd
	conffile=`tempfile -m 0600`
	perl -ne 'print unless /^\s+db_(passwd|user)/' /etc/sympa/sympa.conf > $conffile
	cat <<EOT >> $conffile
db_passwd $RET
EOT
else 
	conffile=/etc/sympa/sympa.conf
fi

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
	if [ "$pass_required" = 1 ]; then
		db_get sympa/db_adminpasswd
		adminpassfile=`tempfile -m 0600`
		cat <<EOT >> $adminpassfile
$RET
EOT
		OPTS="-a $adminpassfile"
	elif [ "$db_type" = "MySQL" ]; then
		OPTS="-o mysql_read_default_file=/root/.my.cnf"
	fi

	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
			if /usr/share/sympa/db/install-pg-db $OPTS -d "$db_name" -h "$db_hostname" -u "$userpassfile"; then
				exit 1
			fi
		    ;;
		"MySQL")
			if /usr/share/sympa/db/install-mysql-db $OPTS -d "$db_name" -h "$db_hostname" -u "$userpassfile"; then
				exit 1
			fi
		    ;;
	esac
fi

if /usr/lib/sympa/bin/sympa.pl -f $conffile --prepare_db; then
	db_set sympa/db_configured true
fi
