#!/bin/sh

set -e

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

conf=/etc/sympa/sympa.conf
wwconf=/etc/sympa/wwsympa.conf

# creating sympa user if he isn't already there
if ! id sympa >/dev/null 2>/dev/null ; then
	echo "Adding system user: sympa."
	adduser --system --group --gecos "Sympa mailing list manager" --no-create-home --home /var/lib/sympa sympa >/dev/null
fi

# Stop the daemon if it has already been started
# This is necessary when you run dpkg-reconfigure
if [ "$1" = "configure" ]; then
	if [ -f /var/run/sympa/sympa.pid ]; then
		if which invoke-rc.d >/dev/null 2>&1; then
			invoke-rc.d sympa stop || true
		else
			etc/init.d/sympa stop || true
		fi
	fi
fi

# Ensure that directory exists
if [ ! -d /etc/sympa ]; then
	mkdir /etc/sympa
fi

# Ensure that data structure version file exists
# and is writable for Sympa
if [ ! -f /etc/sympa/data_structure.version ]; then
	if [ "$1" = "configure" ]; then
		if [ -n "$2" ] && dpkg --compare-versions "$2" lt "5.2.3"; then
			echo "$2" > /etc/sympa/data_structure.version
		else
			touch /etc/sympa/data_structure.version
		fi
	fi
fi
chown sympa:sympa /etc/sympa/data_structure.version

# Install sympa.conf
if [ -f "$conf" ]; then
	# Replace/disable obsolete settings in configuration file
	perl -i~ -pe 's%^\s*msgcat(.*)%localedir /usr/lib/sympa/locale%; s%(\s*queueexpire.*)%# $1%;' "$conf"
	rm -f "$conf"~
fi

if [ ! -f "$conf" ]; then
	/usr/lib/sympa/bin/sympa_wizard.pl --create sympa.conf --target "$conf"
	perl -i~ -pe 's%^#?(cookie\s+).*%cookie `cat /etc/sympa/cookie`%; s%^(syslog\s+).*%syslog `cat /etc/sympa/facility`%;' "$conf"
	rm -f "$conf"~
fi

# Install wwsympa.conf
# Even if WWSympa is not used, we need to provide a default wwsympa.conf
if [ ! -f "$wwconf" ]; then
	/usr/lib/sympa/bin/sympa_wizard.pl --create wwsympa.conf --target "$wwconf"
	perl -i~ -pe 's%^(arc_path\s+).*%$1/var/lib/sympa/wwsarchive%; s%^(bounce_path\s+).*%$1/var/spool/sympa/wwsbounce%' "$wwconf"
	rm -f "$wwconf"~
fi

# Configure the language
db_get sympa/language
lang="$RET"

perl -pi~ -e "s/^\s*lang.*$/lang\t\t$lang/;" "$conf"
rm -f "$conf"~

# Fixing supported_lang if empty
perl -i -pe "s/^\s*(supported_lang)\s*\$/\$1\t\tnone\n/;" "$conf"

# Get the hostname
db_get sympa/hostname
hostn="$RET"
if grep -q "^[ 	]*host" "$conf" ; then
	perl -pi~ -e "s/^\s*host.*$/domain\t\t$hostn/;" "$conf"
else
	perl -pi~ -e "s/^\s*domain.*$/domain\t\t$hostn/;" "$conf"
fi
rm -f "$conf"~

# Get the listmasters and escape '@' caracters for Perl processing. Ugly, anyway ...
db_get sympa/listmaster
listmaster=`echo $RET | sed 's/@/\\\\@/g'`
perl -pi~ -e "s/^\s*listmaster.*$/listmaster\t\t$listmaster/;" "$conf"
rm -f "$conf"~

if [ "$1" = "configure" ]; then
	if [ -n "$2" ] && dpkg --compare-versions "$2" lt "6.0.1"; then
		# add required parameters in Sympa 6
		if grep -q bounce_warn_rate $conf; then
			echo "bounce_warn_rate 30" >> $conf;
		fi
		if grep -q bounce_halt_rate $conf; then
			echo "bounce_halt_rate 50" >> $conf;
		fi
		# fix paths
		perl -pi~ -e "s%^home\s+/usr/lib/sympa/expl$%home /var/lib/sympa/expl%; s%^static_content_path\s+/usr/lib/sympa/static_content%static_content_path /var/lib/sympa/static_content%;" "$conf"
		rm -f "$conf"~
	fi
fi

## ensure permissions and ownerships are right
chown -R root:root /usr/lib/sympa
chown -R sympa:sympa /var/spool/sympa /var/lib/sympa
chmod -R ug=rwX,o=X /var/spool/sympa /var/lib/sympa
if [ -e /var/log/sympa.log ] && [ ! -f /var/log/sympa.log ]; then
	echo "Problem: /var/log/sympa.log already exists and it isn't a file !"
fi

## Upgrade workaround problem in case of the old list home
## directory does not contain any list configuration and was
## removed on upgrade.
if [ ! -d /var/spool/sympa/expl ]; then
	sed -i~ -e "s;\([^#]*\)/var/spool/sympa/expl;\1/var/lib/sympa/expl;" "$conf"
	rm -f "$conf"~
fi

chown -R sympa:sympa /etc/sympa/*
chmod 0640 "$conf" /etc/sympa/sympa.conf-smime.in

touch /var/log/sympa.log || true
chown sympa:sympa /var/log/sympa.log
chmod 0640 /var/log/sympa.log

# Get rid of the old /etc/sympa/config directory
if [ -d /etc/sympa/config ]; then
	rm -f /etc/sympa/config/helpfile
	rm -f /etc/sympa/config/helpfile.advanced
	rm -f /etc/sympa/config/lists
	rmdir /etc/sympa/config || true
fi

## Add the sympa aliases
if ! grep -q "#-- SYMPA begin" /etc/aliases
then
	cat >>/etc/aliases <<EOF
#-- SYMPA begin
## Aliases used for the sympa mailing-list manager
sympa:		"|/usr/lib/sympa/bin/queue sympa"
sympa-request:	postmaster
sympa-owner:	postmaster
listmaster:	postmaster
#-- SYMPA end
EOF
	newaliases
fi

## Create file for mailing list aliases
if ! [ -f /etc/mail/sympa.aliases ]; then
	echo "## List aliases used for the sympa mailing-list manager" > /etc/mail/sympa.aliases
	chown sympa:sympa /etc/mail/sympa.aliases
fi

## Setup a syslog facility
if which syslog-facility >/dev/null 2>&1 \
  && [ -e /etc/syslog.conf ] \
  && ! grep -q "/var/log/sympa.log" /etc/syslog.conf \
  && syslog-facility set all /var/log/sympa.log > /etc/sympa/facility \
  && [ -x /etc/init.d/sysklogd ]; then
	if which invoke-rc.d >/dev/null 2>&1; then
		invoke-rc.d sysklogd reload
	else
		etc/init.d/sysklogd reload
	fi
fi
## ...and ensure existence and access rights of facility file even if unused
[ -e /etc/sympa/facility ] || touch /etc/sympa/facility
chown sympa:sympa /etc/sympa/facility

## Create a unique cookie for this host
if [ ! -e /etc/sympa/cookie ]; then
	touch /etc/sympa/cookie
	chmod 0660 /etc/sympa/cookie
	chown sympa:sympa /etc/sympa/cookie
	if [ -r /dev/urandom ]; then
		dd if=/dev/urandom bs=1k count=1 2>/dev/null \
		| md5sum | cut -d " " -f 1 >>/etc/sympa/cookie
	else
		(free; uptime; ps aux) | md5sum | cut -d " " -f 1 >>/etc/sympa/cookie
	fi
fi

if [ ! -e /etc/sympa/cookies.history ]; then
	cp /etc/sympa/cookie /etc/sympa/cookies.history
	chmod 0660 /etc/sympa/cookies.history
	chown sympa:sympa /etc/sympa/cookies.history
fi

## Look for bad path in aliases file (why the hell did they move the files ?)
if grep -q "/usr/lib/sympa/queue" /etc/aliases ; then
	echo "WARNING : The path of the queue program is bad in the aliases file"
	echo "Change /usr/lib/sympa/queue by /usr/lib/sympa/bin/queue !"
	echo "I'll create a symlink to prevent problems from happening..."
	echo ""
	ln -sf bin/queue /usr/lib/sympa/queue
fi

# setup Sendmail smrsh links
if [ -d /etc/mail/smrsh ]; then
	ln -sf /usr/lib/sympa/bin/bouncequeue /etc/mail/smrsh
	ln -sf /usr/lib/sympa/bin/queue /etc/mail/smrsh
fi

. /usr/share/debconf/confmodule
. /usr/share/dbconfig-common/dpkg/postinst
dbc_first_version="5.3.4-6~"
dbc_dbfile_owner="sympa:sympa"
dbc_go sympa $@

# Check whether a DB driver is installed
installed_dbd() {
	driver=$1
	if perl -MDBD::$driver -e ';' >/dev/null 2>&1 ; then
		return 0
	fi
	return 1
}

# Translate database parameters from dbconfig-common to Sympa's db_xxx configuration values
name=$dbc_dbname
case "$dbc_dbtype" in 
	mysql) 
		type=mysql;;
	pgsql) 
		type=Pg;;
	sqlite*) 
		type=SQLite; 
		name="$dbc_basepath/$dbc_dbname";;
	*) 
		echo "Unknown database type $dbc_dbtype.";
		exit 1;;
esac

# Install the database configuration
NEW=`perl -i~ -pe "BEGIN {
%db= (type => '$type', name => '$name', host => '$dbc_hostname', user => '$dbc_dbuser', passwd => '$dbc_dbpass', options => '$dbc_dboptions', port => '$dbc_dbport');}; "'
END {
	for (keys %db) {
		if ($db{$_}) {
			print "db_$_ $db{$_}\n"
		}
	}
};
s%^(\s*db_)(\w+)(\s+)(.*)%
if (exists $db{$2}) {
	if ($db{$2}) {
		$var = $db{$2};
		$db{$2} = "";
		"$1$2$3$var";
	} else {
		"# $1$2$3$4";
	}
} else {
	"$1$2$3$4";
}%e;' "$conf"`
rm -f "$conf"~

if [ -n "$NEW" ]; then
	echo "$NEW" >> "$conf"
fi

chown sympa:sympa "$conf"
chmod 0640 "$conf"

# Ensure permissions and ownerships are right
chown -R sympa:sympa /var/spool/sympa/wws* /var/lib/sympa/wws*
chmod -R ug=rwX,o=X /var/spool/sympa/wws* /var/lib/sympa/wws*

find /var/lib/sympa/static_content -type f | xargs chmod 664

## Upgrade workaround problem in case of the old web archive
## directory does not contain any archive file and was
## removed on upgrade.
if [ ! -d /var/spool/sympa/wwsarchive ]; then
	sed -i~ -e "s;\([^#]*\)/var/spool/sympa/wwsarchive;\1/var/lib/sympa/wwsarchive;" "$wwconf"
	rm -f "$wwconf"~
fi

chown sympa:sympa "$wwconf" /etc/sympa/topics.conf
chmod 0640 "$wwconf"

chown sympa:sympa /usr/lib/cgi-bin/sympa/wwsympa.fcgi
chmod 6755 /usr/lib/cgi-bin/sympa/wwsympa.fcgi

# WebServer configuration
db_get wwsympa/webserver_type
webserver="$RET"

case $webserver in
    "Apache 2")
	webserver="apache2"
	;;
    *)
	webserver="none"
	;;
esac

# Check whether the Web server is installed
if [ -f /etc/$webserver/httpd.conf ]; then
	echo "$webserver: installation seems OK ..."
else
	webserver="none"
fi

# Read FastCGI setting
db_get wwsympa/fastcgi
fastcgi="$RET"

if [ $fastcgi = "true" ]; then
	if [ $webserver = "apache2" ]; then
		if [ ! -f /etc/apache2/mods-enabled/fcgid.load ] && [ ! -f /etc/apache2/mods-enabled/fastcgi.load ]; then
			echo "FastCGI module not installed or enabled, skipping."
			fastcgi="false"
		fi
	fi
fi

## Generate "$wwconf"
case $fastcgi in
    "true")
	fastcgi="1"
	;;
    *)
	fastcgi="0"
	;;
esac

db_get wwsympa/wwsympa_url
wwsympa_url="$RET"

perl -i -pe "s%^(wwsympa_url\s+).*%wwsympa_url ${wwsympa_url}%" "$conf"

if [ "$fastcgi" = "1" ]; then
	db_get sympa/use_soap
	use_soap="$RET"

	# Use SOAP
	if [ "$use_soap" = "true" ]; then
		chown sympa:sympa /usr/lib/cgi-bin/sympa/sympa_soap_server.fcgi
		chmod 6755 /usr/lib/cgi-bin/sympa/sympa_soap_server.fcgi
		if ! grep -q soap_url "$conf"; then
			echo "soap_url http://${hostn}/sympasoap" >> "$conf"
		else
			perl -pi~ -e "s%^(soap_url\s+).*%soap_url  http://$hostn/sympasoap%" "$conf"
			rm -f "$conf"~
		fi
	fi
fi

# WebServer configuration
db_get wwsympa/webserver_type
webserver="$RET"

case $webserver in
	"Apache 2")
	webserver="apache2"
	;;
	*)
	webserver="none"
	;;
esac

	# Check whether the Web server is installed
if [ -f /etc/$webserver/httpd.conf ]; then
	echo "$webserver: installation seems OK ..."
else
	webserver="none"
fi

if [ $webserver = "none" ]; then
	echo "Not configuring Web server."
else
	mkdir -p /etc/$webserver/conf.d

	# Activate wwsympa
	if [ ! -f /etc/$webserver/conf.d/sympa ] && [ ! -h /etc/$webserver/conf.d/sympa ]; then
		ln -sf /etc/sympa/apache-wwsympa /etc/$webserver/conf.d/sympa
	fi

	if [ "$use_soap" = "true" ]; then
			# Activate soap
		if [ ! -f /etc/$webserver/conf.d/sympa-soap ] && [ ! -h /etc/$webserver/conf.d/sympa-soap ]; then
			ln -s /etc/sympa/apache-soap /etc/$webserver/conf.d/sympa-soap
		fi
	fi
fi

	# Check whether we have to restart the Web server
db_get wwsympa/webserver_restart
restart="$RET"

if [ "$restart" = "true" ]; then
	if [ -x /etc/init.d/$webserver ]; then
		if which invoke-rc.d >/dev/null 2>&1; then
			invoke-rc.d $webserver force-reload
		else
			etc/init.d/$webserver force-reload
		fi
	fi
fi

su -s /bin/sh -c "/usr/lib/sympa/bin/sympa.pl -f $conf --prepare_db" -l sympa

## End up with debconf
db_stop

#DEBHELPER#
