#!/bin/bash

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

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' )
	    SQL="$SQL
CREATE DATABASE IF NOT EXISTS ${nextcloud_MYSQL_DATABASE};

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

GRANT ALL ON ${nextcloud_MYSQL_DATABASE}.* TO '${nextcloud_MYSQL_USER}'@'%' IDENTIFIED BY '${nextcloud_MYSQL_PASSWORD}';

FLUSH PRIVILEGES;"
        ;;
	'agora' )
	    SQL="$SQL
CREATE DATABASE IF NOT EXISTS ${mattermost_MYSQL_DATABASE};

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

GRANT ALL ON ${mattermost_MYSQL_DATABASE}.* TO '${mattermost_MYSQL_USER}'@'%' IDENTIFIED BY '${mattermost_MYSQL_PASSWORD}';

FLUSH PRIVILEGES;"
	    ;;
	'wp' )
	    SQL="$SQL
CREATE DATABASE IF NOT EXISTS ${wp_MYSQL_DATABASE};

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

GRANT ALL ON ${wp_MYSQL_DATABASE}.* TO '${wp_MYSQL_USER}'@'%' IDENTIFIED BY '${wp_MYSQL_PASSWORD}';

FLUSH PRIVILEGES;"
	    ;;
	'castopod' )
	    SQL="$SQL
CREATE DATABASE IF NOT EXISTS ${castopod_MYSQL_DATABASE};

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

GRANT ALL ON ${castopod_MYSQL_DATABASE}.* TO '${castopod_MYSQL_USER}'@'%' IDENTIFIED BY '${castopod_MYSQL_PASSWORD}';

FLUSH PRIVILEGES;"
	    ;;
 
    esac
done

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