#!/bin/bash

echo "Configuring for ${DOMAIN_SYMPA}"
sed -i -e "s/MAILNAME.DOMAINNAME/${DOMAIN_SYMPA}/g" /etc/postfix/main.cf
sed -i -e "s/MAILNAME.DOMAINNAME/${DOMAIN_SYMPA}/g" /etc/sympa/sympa/sympa.conf
sed -i -e "s/MAILNAME.DOMAINNAME/${DOMAIN_SYMPA}/g" /etc/mailname
sed -i -e "s/ADMIN_EMAIL/$ADMINEMAIL/g" /etc/aliases
postalias /etc/aliases


sed -i -e "s%ENVKEY%$KEY%g" /etc/postfix/main.cf
sed -i -e "s%ENVCERT%$CERT%g" /etc/postfix/main.cf

sed -i -e "s%ENVKEY%$KEY%g" /etc/apache2/sites-available/default-ssl.conf
sed -i -e "s%ENVCERT%$CERT%g" /etc/apache2/sites-available/default-ssl.conf
sed -i -e "s/MAILNAME.DOMAINNAME/${DOMAIN_SYMPA}/g" /etc/apache2/sites-available/000-default.conf
sed -i -e "s/MAILNAME.DOMAINNAME/${DOMAIN_SYMPA}/g" /var/www/html/index.html

sed -i -e "s/MAILNAME.DOMAINNAME/${DOMAIN_SYMPA}/g" /etc/sympa/aliases.sympa.postfix
postalias hash:/etc/sympa/aliases.sympa.postfix
/usr/lib/sympa/bin/sympa_newaliases.pl

postmap /etc/postfix/transport

# sed -i -e "s/LISTMASTERS/$LISTMASTERS/g" /etc/sympa/sympa/sympa.conf

# Passage de SQLite à MySQL
sed -i -e "s/db_name.*//g" /etc/sympa/sympa/sympa.conf
sed -i -e "s/db_type.*//g" /etc/sympa/sympa/sympa.conf
echo -e "db_type	mysql\ndb_host	db\ndb_port	3306\ndb_name	${MYSQL_DATABASE}\ndb_user	${MYSQL_USER}\ndb_passwd	${MYSQL_PASSWORD}" >> /etc/sympa/sympa/sympa.conf

# set des listmasters
sed -i -e "s/listmaster.*//g" /etc/sympa/sympa/sympa.conf
echo -e "listmaster $LISTMASTERS" >> /etc/sympa/sympa/sympa.conf

# passage en https
sed -i -e "s/http:/https:/g" /etc/sympa/sympa/sympa.conf

# Initialisation/Vérification de la database
until /usr/lib/sympa/bin/sympa.pl --health_check # creates the database if needed, wait for the DB to be ready
do
  sleep 0.1
done

# préparation du SOAP
sed -i -e "s%SOAP_USER%${SOAP_USER}%g" /etc/sympa/trusted_applications.conf
MD5PASS=$(/usr/lib/sympa/bin/sympa.pl --md5_digest=${SOAP_PASSWORD} | cut -d':' -f2 | sed -e "s/[[:space:]]*//g")
sed -i -e "s%SOAP_MD5PASS%${MD5PASS}%g" /etc/sympa/trusted_applications.conf

echo "Starting supervisord"
supervisord -n -c /etc/supervisord.conf
