#!/bin/bash
#

if [ -f /usr/bin/ParseDico ];then
    #EOLE 2.3
    . ParseDico
    . /etc/eole/containers.conf
    . /usr/share/eole/FonctionsEoleNg
	RunCmd=RunCmd
else
    #EOLE 2.4
    container_path_web=$(CreoleGet container_path_web)
    web_url=$(CreoleGet web_url)
    activer_moodle=$(CreoleGet activer_moodle)
    adresse_ip_web=$(CreoleGet adresse_ip_web)
    eolesso_adresse=$(CreoleGet eolesso_adresse)
    eolesso_port=$(CreoleGet eolesso_port)
    adresse_ip_mysql=$(CreoleGet adresse_ip_mysql)
    adresse_ip_ldap=$(CreoleGet adresse_ip_ldap)
    ldap_base_dn=$(CreoleGet ldap_base_dn)
    activer_addadmin=$(CreoleGet activer_addadmin)
    uid_addadmin=$(CreoleGet uid_addadmin null)
    RunCmd=CreoleRun
fi

declare APACHE_USER="www-data"
declare BIN_PHP="/usr/bin/php"
declare BIN_SU="/bin/su"
declare INSTALL_SCRIPT="admin/cli/install.php"
declare UPGRADE_SCRIPT="admin/cli/upgrade.php"
declare INSTALL_DIR="/var/www/html/moodle"
declare DATA_DIR="/home/www-data/var/www/html/moodle"
declare LANG="fr"
declare LOCK="${INSTALL_DIR}/.config.lock"
declare MOODLE_CFG_FILE="${INSTALL_DIR}/config.php"
declare DBUSER="root"
declare DBPASS='123456';

#
# Crée la configuration de moodle pour les fresh install
# Tout se fait en base via du SQL
#
function make_config()
{

    if [[ -n ${eolesso_port} ]]
    then
        SSO_PORT=${eolesso_port}
    else
        SSO_PORT=8443
    fi

    if [[ -n ${eolesso_adresse} ]]
    then
        SSO_ADDR=${eolesso_adresse}
    else
        SSO_ADDR=${adresse_ip_web}
    fi

    if [[ -n ${web_url} ]]
    then
        EMAIL="noreply@${web_url}"
        CHAT_SRV_HOST=${web_url}
    fi

    mysql -h ${adresse_ip_mysql} -u ${DBUSER} --password=${DBPASS} <<__EOF__
    \r moodle
    INSERT INTO \`mdl_config_plugins\` (\`plugin\`, \`name\`, \`value\`) VALUES
    ('auth/cas', 'hostname', '${SSO_ADDR}'),
    ('auth/cas', 'port', '${SSO_PORT}'),
    ('auth/cas', 'casversion', '2.0'),
    ('auth/cas', 'baseuri', ''),
    ('auth/cas', 'language', 'French'),
    ('auth/cas', 'proxycas', '0'),
    ('auth/cas', 'logoutcas', '1'),
    ('auth/cas', 'multiauth', '0'),
    ('auth/cas', 'certificate_check', '0'),
    ('auth/cas', 'certificate_path', ''),
    ('auth/cas', 'host_url', 'ldap://${adresse_ip_ldap}'),
    ('auth/cas', 'ldapencoding', 'utf-8'),
    ('auth/cas', 'contexts', '${ldap_base_dn}'),
    ('auth/cas', 'user_type', 'default'),
    ('auth/cas', 'user_attribute', 'uid'),
    ('auth/cas', 'search_sub', '1'),
    ('auth/cas', 'opt_deref', '0'),
    ('auth/cas', 'bind_dn', ''),
    ('auth/cas', 'bind_pw', ''),
    ('auth/cas', 'ldap_version', '2'),
    ('auth/cas', 'objectclass', '(&(objectclass=inetOrgPerson)(!(description=Computer)))'),
    ('auth/cas', 'memberattribute', 'memberuid'),
    ('auth/cas', 'memberattribute_isdn', ''),
    ('auth/cas', 'attrcreators', 'ENTPersonProfils=enseignant'),
    ('auth/cas', 'groupecreators', 'ENTPersonProfils=enseignant'),
    ('auth/cas', 'removeuser', '2'),
    ('auth/cas', 'field_map_firstname', 'givenName'),
    ('auth/cas', 'field_updatelocal_firstname', 'oncreate'),
    ('auth/cas', 'field_updateremote_firstname', '0'),
    ('auth/cas', 'field_lock_firstname', 'unlocked'),
    ('auth/cas', 'field_map_lastname', 'sn'),
    ('auth/cas', 'field_updatelocal_lastname', 'oncreate'),
    ('auth/cas', 'field_updateremote_lastname', '0'),
    ('auth/cas', 'field_lock_lastname', 'unlocked'),
    ('auth/cas', 'field_map_email', 'mail'),
    ('auth/cas', 'field_updatelocal_email', 'oncreate'),
    ('auth/cas', 'field_updateremote_email', '0'),
    ('auth/cas', 'field_lock_email', 'unlocked'),
    ('auth/cas', 'field_map_city', ''),
    ('auth/cas', 'field_updatelocal_city', 'oncreate'),
    ('auth/cas', 'field_updateremote_city', '0'),
    ('auth/cas', 'field_lock_city', 'unlocked'),
    ('auth/cas', 'field_map_country', ''),
    ('auth/cas', 'field_updatelocal_country', 'oncreate'),
    ('auth/cas', 'field_updateremote_country', '0'),
    ('auth/cas', 'field_lock_country', 'unlocked'),
    ('auth/cas', 'field_map_lang', ''),
    ('auth/cas', 'field_updatelocal_lang', 'oncreate'),
    ('auth/cas', 'field_updateremote_lang', '0'),
    ('auth/cas', 'field_lock_lang', 'unlocked'),
    ('auth/cas', 'field_map_description', ''),
    ('auth/cas', 'field_updatelocal_description', 'oncreate'),
    ('auth/cas', 'field_updateremote_description', '0'),
    ('auth/cas', 'field_lock_description', 'unlocked'),
    ('auth/cas', 'field_map_url', ''),
    ('auth/cas', 'field_updatelocal_url', 'oncreate'),
    ('auth/cas', 'field_updateremote_url', '0'),
    ('auth/cas', 'field_lock_url', 'unlocked'),
    ('auth/cas', 'field_map_idnumber', ''),
    ('auth/cas', 'field_updatelocal_idnumber', 'oncreate'),
    ('auth/cas', 'field_updateremote_idnumber', '0'),
    ('auth/cas', 'field_lock_idnumber', 'unlocked'),
    ('auth/cas', 'field_map_institution', ''),
    ('auth/cas', 'field_updatelocal_institution', 'oncreate'),
    ('auth/cas', 'field_updateremote_institution', '0'),
    ('auth/cas', 'field_lock_institution', 'unlocked'),
    ('auth/cas', 'field_map_department', ''),
    ('auth/cas', 'field_updatelocal_department', 'oncreate'),
    ('auth/cas', 'field_updateremote_department', '0'),
    ('auth/cas', 'field_lock_department', 'unlocked'),
    ('auth/cas', 'field_map_phone1', ''),
    ('auth/cas', 'field_updatelocal_phone1', 'oncreate'),
    ('auth/cas', 'field_updateremote_phone1', '0'),
    ('auth/cas', 'field_lock_phone1', 'unlocked'),
    ('auth/cas', 'field_map_phone2', ''),
    ('auth/cas', 'field_updatelocal_phone2', 'oncreate'),
    ('auth/cas', 'field_updateremote_phone2', '0'),
    ('auth/cas', 'field_lock_phone2', 'unlocked'),
    ('auth/cas', 'field_map_address', ''),
    ('auth/cas', 'field_updatelocal_address', 'oncreate'),
    ('auth/cas', 'field_updateremote_address', '0'),
    ('auth/cas', 'field_lock_address', 'unlocked');

    UPDATE \`mdl_config\` SET value = 1 WHERE name = 'forcelogin';

    INSERT IGNORE INTO mdl_config (name, value) VALUES ('siteadmins','');
__EOF__
}

#
# Met à jour des paramètres de configuration qui peuvent changer 
# cette fonction est lancée a chaque reconfigure.
#
function update_config()
{
    if [[ -n ${eolesso_port} ]]
    then
        SSO_PORT=${eolesso_port}
    else
        SSO_PORT=8443
    fi

    if [[ -n ${eolesso_adresse} ]]
    then
        SSO_ADDR=${eolesso_adresse}
    else
        SSO_ADDR=${adresse_ip_web}
    fi

    if [[ -n ${web_url} ]]
    then
        EMAIL="noreply@${web_url}"
        CHAT_SRV_HOST=${web_url}
    fi

    mysql -h ${adresse_ip_mysql} -u ${DBUSER} --password=${DBPASS} <<__EOF__
\r moodle
UPDATE \`mdl_user\`   SET auth = 'cas', password = 'not cached' WHERE username = 'admin';
UPDATE \`mdl_config\` SET value = 'cas' WHERE name = 'auth';
UPDATE \`mdl_config\` SET value = '${EMAIL}'  WHERE name = 'noreplyaddress';
UPDATE \`mdl_config\` SET value = '${CHAT_SRV_HOST}' WHERE name = 'chat_serverhost';
UPDATE \`mdl_config\` SET value='0' WHERE name='dbsessions';

UPDATE \`mdl_config_plugins\` SET value = 'ldap://${adresse_ip_ldap}' WHERE plugin = 'auth/cas' AND name = 'host_url';
UPDATE \`mdl_config_plugins\` SET value = '${ldap_base_dn}' WHERE plugin = 'auth/cas' AND name = 'contexts';
UPDATE \`mdl_config_plugins\` SET value = '${SSO_ADDR}' WHERE plugin = 'auth/cas' AND name = 'hostname';
UPDATE \`mdl_config_plugins\` SET value = '${SSO_PORT}'  WHERE plugin = 'auth/cas' AND name = 'port';
UPDATE \`mdl_config_plugins\` SET value = '2' WHERE plugin = 'auth/cas' AND name = 'casversion';
UPDATE \`mdl_config_plugins\` SET value = 'onlogin'  WHERE plugin = 'auth/cas' AND name = 'field_updatelocal_firstname';
UPDATE \`mdl_config_plugins\` SET value = 'onlogin'  WHERE plugin = 'auth/cas' AND name = 'field_updatelocal_lastname';
UPDATE \`mdl_config_plugins\` SET value = 'onlogin'  WHERE plugin = 'auth/cas' AND name = 'field_updatelocal_email';
UPDATE \`mdl_config_plugins\` SET value = '(&(objectclass=inetOrgPerson)(!(description=Computer)))'  WHERE plugin = 'auth/cas' AND name = 'objectclass';
UPDATE \`mdl_config_plugins\` SET value = '2'  WHERE plugin = 'auth/cas' AND name = 'removeuser';
UPDATE \`mdl_config_plugins\` SET value = 'French'  WHERE plugin = 'auth_cas' AND name = 'language';

__EOF__

ret1=$(mysql -h ${adresse_ip_mysql} -u ${DBUSER} --password=${DBPASS} --batch --skip-column-names -Dmoodle -e "SELECT value FROM mdl_config WHERE name = 'siteadmins'")
ret2=$(mysql -h ${adresse_ip_mysql} -u ${DBUSER} --password=${DBPASS} --batch --skip-column-names -Dmoodle -e "SELECT id FROM mdl_user WHERE username='admin' OR username='${uid_addadmin}' OR id IN("$ret1") GROUP BY id")
ret3=`echo $ret2 | sed 's/ /,/g'`
ret4=$(mysql -h ${adresse_ip_mysql} -u ${DBUSER} --password=${DBPASS} --batch --skip-column-names -Dmoodle -e "UPDATE mdl_config SET value = '$ret3' WHERE name = 'siteadmins'")


}

#
# Sauvegarde le fichier de configuration de moodle 
#
function backup_moodle_conf 
{

   if [[ -f "${container_path_web}/${MOODLE_CFG_FILE}" ]]
   then
      $RunCmd "mv ${MOODLE_CFG_FILE} ${MOODLE_CFG_FILE}.bck" web
   fi
}

#
# Refresh du cache
#
function refresh_cache 
{
   if [[ -d "${container_path_web}/${DATA_DIR}" ]]
   then
      $RunCmd "rm -rf ${DATA_DIR}/cache/*" web
   fi
}


#
# Lance l'installation de moodle 
# ceci est appellé lors des fresh install
#
function install_moodle
{

   backup_moodle_conf

   if [[ -n ${web_url} ]]
   then
       URL="https://${web_url}/moodle"
   else
       URL="https://${adresse_ip_web}/moodle"
   fi

   DATA_ROOT="/home/www-data/var/www/html/moodle"
 
   CMD="cd ${INSTALL_DIR} ; ${BIN_PHP} ${INSTALL_SCRIPT}        \
       --lang=${LANG}  --wwwroot=${URL} --dataroot=${DATA_ROOT} \
       --dbtype=mysqli --dbhost=${adresse_ip_mysql}             \
       --dbname=moodle --dbuser=${DBUSER} --dbpass=${DBPASS}    \
       --prefix=mdl_ --shortname=envole --fullname=Envole       \
       --adminuser=admin --adminpass=test --non-interactive --agree-license \
       --chmod=2750"

   $RunCmd "/bin/bash -c \"${CMD}\"" web
	
   make_config

   $RunCmd "touch ${LOCK}" web
   $RunCmd "chmod 600 ${LOCK}" web

}

#
# Lance la mise à jour de la base de moodle
#
function update_moodle
{
   CMD="cd ${INSTALL_DIR} ; ${BIN_PHP} ${UPGRADE_SCRIPT} --non-interactive"

   $RunCmd "/bin/bash -c \"${CMD}\"" web
   RET=${?}

   $RunCmd "touch ${LOCK}" web
   $RunCmd "chmod 600 ${LOCK}" web

   return ${RET}
}

function droits_moodle
{
    file_path="/var/www/html/moodle/writeable_folders"
    con_path=${container_path_web}/${file_path}
    for i in `cat ${con_path}`;
    do  
        $RunCmd "chmod g+w ${i}" web 
    done
}

$RunCmd "chgrp www-data ${MOODLE_CFG_FILE}" web
$RunCmd "chown -R www-data ${DATA_DIR}" web
droits_moodle

# On lance la mise à jour de la base de moodle
echo "Mise à jour de Moodle"
update_moodle
if [[ ${?} -eq 1 ]] 
then
    # En cas de problème on lance l'installation complète
    echo "Moodle n'est pas installé"
    echo "Installation de Moodle"
    install_moodle
fi

# Mise à jour des paramètres configurations de moodle
echo "Mise à jour de la configuration"
update_config 

$RunCmd "chgrp www-data ${MOODLE_CFG_FILE}" web
$RunCmd "chown -R www-data ${DATA_DIR}" web
droits_moodle

# Refresh du cache
echo "Refresh du cache"
refresh_cache

