#!/bin/bash

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

# pour mise au point
# SIMU=echo

# Améliorations à prévoir
# - donner en paramètre les services concernés (pour limité les modifications)
# - pour les DB si on déclare un nouveau login, alors les privilèges sont créé mais les anciens pas révoqués

. "${DOCKERS_ENV}"

createMysqlUser(){
    # $1 = envName
    # $2 = containerName of DB

	. $KAZ_KEY_DIR/env-$1
    
    # seulement si pas de mdp pour root
    # pb oeuf et poule (il faudrait les anciennes valeurs) :
    # * si rootPass change, faire à la main
    # * si dbName change, faire à la main
    checkDockerRunning "$2" "$2" || return
    echo "change DB pass on docker $2"
    echo "grant all privileges on ${MYSQL_DATABASE}.* to '${MYSQL_USER}' identified by '${MYSQL_PASSWORD}';" | \
	docker exec -i $2 bash -c "mysql --user=root --password=${MYSQL_ROOT_PASSWORD}"
}



framadateUpdate(){
    [[ "${COMP_ENABLE}" =~ " framadate " ]] || return
    if [ ! -f "${DOCK_LIB}/volumes/framadate_dateConfig/_data/config.php" ]; then
	return 0
    fi
	. $KAZ_KEY_DIR/env-framadateDB 
    . $KAZ_KEY_DIR/env-framadateServ
    
    checkDockerRunning "${framadateServName}" "Framadate" &&
	${SIMU} docker exec -ti "${framadateServName}" bash -c -i "htpasswd -bc /var/framadate/admin/.htpasswd ${HTTPD_USER} ${HTTPD_PASSWORD}"
    ${SIMU} sed -i \
	    -e "s/^#*const DB_USER[ ]*=.*$/const DB_USER= '${DB_MYSQL_USER}';/g" \
	    -e "s/^#*const DB_PASSWORD[ ]*=.*$/const DB_PASSWORD= '${DB_MYSQL_PASSWORD}';/g" \
	    "${DOCK_LIB}/volumes/framadate_dateConfig/_data/config.php"
}

jirafeauUpdate(){
    [[ "${COMP_ENABLE}" =~ " jirafeau " ]] || return
    if [ ! -f "${DOCK_LIB}/volumes/jirafeau_fileConfig/_data/config.local.php" ]; then
	return 0
    fi
	. $KAZ_KEY_DIR/env-jirafeauServ
    SHA=$(echo -n "${_HTTPD_PASSWORD}" | sha256sum | cut -d \  -f 1)
    ${SIMU} sed -i \
	    -e "s/'admin_password'[ ]*=>[ ]*'[^']*'/'admin_password' => '${SHA}'/g" \
	    "${DOCK_LIB}/volumes/jirafeau_fileConfig/_data/config.local.php"
}

####################
# main

createMysqlUser "etherpadDB" "${etherpadDBName}"
createMysqlUser "framadateDB" "${framadateDBName}"
createMysqlUser "giteaDB" "${gitDBName}"
createMysqlUser "mattermostDB" "${mattermostDBName}"
createMysqlUser "nextcloudDB" "${nextcloudDBName}"
createMysqlUser "roundcubeDB" "${roundcubeDBName}"
createMysqlUser "sympaDB" "${sympaDBName}"
createMysqlUser "vigiloDB" "${vigiloDBName}"
createMysqlUser "wpDB" "${wordpressDBName}"
createMysqlUser "vaultwardenDB" "${vaultwardenDBName}"
createMysqlUser "castopodDB" "${castopodDBName}"
createMysqlUser "spipDB" "${spipDBName}"
createMysqlUser "mastodonDB" "${mastodonDBName}"


framadateUpdate
jirafeauUpdate
exit 0
