#!/bin/bash

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

cd $(dirname $0)
ORGA_DIR="$(basename "$(pwd)")"

ORGA=${ORGA_DIR%-orga}
if [[ -z "${ORGA}" ]]
then
    printKazError "it's not an orga dir"
    exit
fi


waitContainerHealthy "${ORGA}-DB" 180
[ $? -ne 0 ] && printKazError "\n  La base de donnée démarre pas : impossible de terminer l'install" && exit

SQL=""

for ARG in "$@"; do
    case "${ARG}" in
	'cloud' )
		. $KAZ_KEY_DIR/orgas/$ORGA/env-nextcloudDB
	    SQL="$SQL
CREATE DATABASE IF NOT EXISTS ${MYSQL_DATABASE};

DROP USER IF EXISTS '${MYSQL_USER}';
CREATE USER '${MYSQL_USER}'@'%';

GRANT ALL ON ${MYSQL_DATABASE}.* TO '${MYSQL_USER}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}';

FLUSH PRIVILEGES;"
        ;;
	'agora' )
	
		. $KAZ_KEY_DIR/orgas/$ORGA/env-mattermostDB
	    SQL="$SQL
CREATE DATABASE IF NOT EXISTS ${MYSQL_DATABASE};

DROP USER IF EXISTS '${MYSQL_USER}';
CREATE USER '${MYSQL_USER}'@'%';

GRANT ALL ON ${MYSQL_DATABASE}.* TO '${MYSQL_USER}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}';

FLUSH PRIVILEGES;"
	    ;;
	'wp' )
	
		. $KAZ_KEY_DIR/orgas/$ORGA/env-wpDB
	    SQL="$SQL
CREATE DATABASE IF NOT EXISTS ${MYSQL_DATABASE};

DROP USER IF EXISTS '${MYSQL_USER}';
CREATE USER '${MYSQL_USER}'@'%';

GRANT ALL ON ${MYSQL_DATABASE}.* TO '${MYSQL_USER}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}';

FLUSH PRIVILEGES;"
	    ;;
	'castopod' )
	
		. $KAZ_KEY_DIR/orgas/$ORGA/env-castopodDB
	    SQL="$SQL
CREATE DATABASE IF NOT EXISTS ${MYSQL_DATABASE};

DROP USER IF EXISTS '${MYSQL_USER}';
CREATE USER '${MYSQL_USER}'@'%';

GRANT ALL ON ${MYSQL_DATABASE}.* TO '${MYSQL_USER}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}';

FLUSH PRIVILEGES;"
	    ;;
	'spip' )
	
		. $KAZ_KEY_DIR/orgas/$ORGA/env-spipDB
           SQL="$SQL
CREATE DATABASE IF NOT EXISTS ${MYSQL_DATABASE};

DROP USER IF EXISTS '${MYSQL_USER}';
CREATE USER '${MYSQL_USER}'@'%';

GRANT ALL ON ${MYSQL_DATABASE}.* TO '${MYSQL_USER}'@'%' IDENTIFIED BY '${MYSQL_PASSWORD}';

FLUSH PRIVILEGES;"
	    ;;

 
    esac
done

echo $SQL | docker exec -i ${ORGA}-DB bash -c "mariadb --user=root --password=${MYSQL_ROOT_PASSWORD}"
