#!/bin/bash

KAZ_ROOT=$(cd $(dirname $0)/../..; pwd)
. "${KAZ_ROOT}/bin/.commonFunctions.sh"
setKazVars

cd $(dirname $0)
. "${DOCKERS_ENV}"
. "${KAZ_KEY_DIR}/env-${framadateServName}"
. "${KAZ_KEY_DIR}/env-${framadateDBName}"

FRAMADATE_URL="${httpProto}://${dateHost}.${domain}"

checkDockerRunning "${framadateServName}" "Framadate" || exit

if [ ! -f "${DOCK_LIB}/volumes/framadate_dateConfig/_data/config.php" ]; then
    printKazMsg "\n  *** Premier lancement de Framadate"

    waitUrl "${FRAMADATE_URL}"

    ${SIMU} docker exec "${framadateServName}" bash -c -i "htpasswd -bc /var/framadate/admin/.htpasswd ${HTTPD_USER} ${HTTPD_PASSWORD}"
    ${SIMU} docker exec "${framadateServName}" bash -c -i "chown www-data: /var/framadate/.htaccess /var/framadate/admin/.htpasswd"

    curl -X POST \
	 -u "${HTTPD_USER}:${HTTPD_PASSWORD}" \
	 -d "appMail=framadate@kaz.bzh" \
	 -d "responseMail=no-reply@kaz.bzh" \
	 -d "defaultLanguage=fr" \
	 -d "cleanUrl=on" \
	 -d "dbConnectionString=mysql:host=db;dbname=${MYSQL_DATABASE};port=3306" \
	 -d "dbUser=${MYSQL_USER}" \
	 -d "dbPassword=${MYSQL_PASSWORD}" \
	 -d "dbPrefix=fd_" \
	 -d "migrationTable=framadate_migration" \
	 "${FRAMADATE_URL}/admin/install.php"

    curl -X POST \
	 -u "${HTTPD_USER}:${HTTPD_PASSWORD}" \
	 "${FRAMADATE_URL}/admin/migration.php"

    sed	-e "s/'host'\s*=>\s*'[^']*',/'host' => 'smtp',/" \
	-e "s/const\s*NOMAPPLICATION\s*=\s*'[^']*';/const NOMAPPLICATION = 'Sondage';/" \
	-i "${DOCK_LIB}/volumes/framadate_dateConfig/_data/config.php"
fi
