#!/bin/bash
# Met à jour la clé utilisée pour authentifier les appels à l'API
# Génère les configurations depuis la base de données


activer_envole=$(CreoleGet activer_envole non)
container_path_web=$(CreoleGet container_path_web)
mode_conteneur_actif=$(CreoleGet mode_conteneur_actif)
container_ip_web=$(CreoleGet container_ip_web)
adresse_ip_eth0=$(CreoleGet adresse_ip_eth0)
RunCmd=CreoleRun


if [ "$activer_envole" == "oui" ]
then
    . /usr/share/envole/eoledb/posh

    export MYSQL_PWD=$dbpassPOSH

    DEFPAGE=$container_path_web/var/www/html/posh/indisponible.php
    function resetposhindex(){
        if [ -f $container_path_web/var/www/html/posh/index.php.sav ]
        then
            /bin/mv -f $container_path_web/var/www/html/posh/index.php.sav $container_path_web/var/www/html/posh/index.php
            $RunCmd "chown root:www-data /var/www/html/posh/index.php" web
            chmod 640 $container_path_web/var/www/html/posh/index.php
        fi

        rm -rf /tmp/posh/*
    }

    function defpage() {
        if [ -f $DEFPAGE ]
        then
            if [ ! -f $container_path_web/var/www/html/posh/index.php.sav ]
            then
                # on écrase pas le fichier qui est déjà sauvé (risque d'écraser avec le defpage.php)
                /bin/cp -f $container_path_web/var/www/html/posh/index.php $container_path_web/var/www/html/posh/index.php.sav
            fi
            /bin/cp -f $DEFPAGE $container_path_web/var/www/html/posh/index.php
            $RunCmd "chown root:www-data /var/www/html/posh/index.php" web
            chmod 640 $container_path_web/var/www/html/posh/index.php
        fi
    }



    # == INDISPO ==================================================================
    echo "  >> Placer page indisponibilité"
    resetposhindex



	# == PERMISSIONS ==============================================================
	echo "  >> Permissions"
	LOG_PATH="/var/log/posh"
	mkdir -p "$container_path_web/$LOG_PATH"
	touch "$container_path_web/$LOG_PATH/interface.log"
	touch "$container_path_web/$LOG_PATH/profile.log"
	touch "$container_path_web/$LOG_PATH/api.log"
	touch "$container_path_web/$LOG_PATH/client.log"
	$RunCmd "chown www-data $LOG_PATH $LOG_PATH/interface.log $LOG_PATH/profile.log $LOG_PATH/api.log $LOG_PATH/client.log" web



	# == REPERTOIRE RESSOURCE =====================================================
	echo "  >> Répertoire Ressource"
	ADMIN=/home/a/admin
	PERSO=$ADMIN/perso
	RESSOURCES=$PERSO/ressources
	WRESSOURCES=/var/www/html/ressources

	chmod o+x $ADMIN
	chmod o+x $PERSO
	mkdir -p $RESSOURCES

	if [ ! -f $RESSOURCES/index.php ]; then
		cp /usr/share/envole/posh/ressources.php $RESSOURCES/index.php
	fi
	chown root:www-data $RESSOURCES/index.php
	chmod 640 $RESSOURCES/index.php

	if [ -x /usr/bin/setfacl ]; then
		setfacl -Rbk $RESSOURCES
		setfacl -d -Rm g:www-data:r-x $RESSOURCES
		chmod 750 $RESSOURCES
		chown admin:www-data $RESSOURCES
	else
		chown -R root:www-data $RESSOURCES
	fi

	$RunCmd "if [ -d $WRESSOURCES -a ! \( -h $WRESSOURCES \) ] ; then /bin/rmdir $WRESSOURCES ; fi" web
	$RunCmd "/bin/ln -nfs $RESSOURCES $WRESSOURCES" web



    # == DB =======================================================================
    echo "  >> Mise à jour DB"
    echo "UPDATE adm_config SET value='$dbpassPOSH' WHERE parameter='PASS' LIMIT 1;" | mysql -u"posh" -h"$dbhostPOSH" -P"$dbportPOSH" posh
    echo "UPDATE adm_config SET value='$dbhostPOSH' WHERE parameter='SERVER' LIMIT 1;" | mysql -u"posh" -h"$dbhostPOSH" -P"$dbportPOSH" posh



    # == POSHKEY ==================================================================
    echo "  >> Génération de la clé Posh"
    POSHKEY=`pwgen --num-passwords=1 20`
    sed -i "s/define(\"__KEY\",\"\([^)]\+\)\");/define(\"__KEY\",\"$POSHKEY\");/" $container_path_web/var/www/html/posh/includes/config.inc.php

    if [ $? != 0 ]
    then
        echo "Envole :  Erreur à la modification de la clé d'authentification pour l'API posh."
        defpage
        exit 0
    fi
    echo "UPDATE posh.adm_config SET value='$POSHKEY' WHERE parameter='KEY' LIMIT 1;" | mysql -u"posh" -h"$dbhostPOSH" -P"$dbportPOSH" posh



    # == COW KEY ==================================================================
    echo "  >> Génération clé serveur de widget"
    COW_KEY=`cat $container_path_web/var/www/html/posh/includes/config.inc.php | grep "\"__COW_KEY\"" |cut -d "\"" -f4`
    if [[ "$COW_KEY" == "" ]]
    then
	COW_KEY=`pwgen --num-passwords=1 20`
	echo "INSERT IGNORE INTO posh.adm_config (parameter, value, datatype, desttype, category, editable) VALUES ('COW_KEY', '$COW_KEY', 'str', 'P', NULL, '1');" | mysql -uposh -h$dbhostPOSH -P$dbportPOSH posh
    fi

    mkdir -p /tmp/posh/


	# == DEFINITION IP =============================================================
    echo "  >> Définition IP"
    if [[ ${mode_conteneur_actif} == "oui" ]]
    then
        IP_SERVEUR_WEB=${container_ip_web}
    else
        IP_SERVEUR_WEB=${adresse_ip_eth0}
    fi



    # == FICHIER DE CONFIGURATION ==================================================
    echo "  >> Fichier de Configuration"
    wget "https://${IP_SERVEUR_WEB}/envole/api/scr_config_generate_configfiles.php?adminkey=$POSHKEY" -o/tmp/posh/scr_config_generate_configfiles.php.log -O/tmp/posh/scr_config_generate_configfiles.php.txt --no-check-certificate
    WGET_FILE=$(cat /tmp/posh/scr_config_generate_configfiles.php.txt)
    if [[ ! "$WGET_FILE" == *"<status>1</status>"* ]]
    then
        echo "Envole : Erreur à la génération des fichiers de configuration."
        defpage
        exit 0
    fi



    # == PLUGINS ===================================================================
    echo "  >> Plugins"
    wget "https://${IP_SERVEUR_WEB}/envole/api/scr_config_plugins.php?adminkey=$POSHKEY" -o/tmp/posh/scr_config_plugins.php.log -O/tmp/posh/scr_config_plugins.php.txt --no-check-certificate
    WGET_FILE=$(cat /tmp/posh/scr_config_plugins.php.txt)
    if [[ ! "$WGET_FILE" == *"<status>1</status>"* ]]
    then
        echo "Envole : Erreur à la configuration des plugins du portail."
        defpage
        exit 0
    fi



    # == REFRESH CACHE =============================================================
    echo "  >> Refresh Cache"
    wget "https://${IP_SERVEUR_WEB}/envole/api/scr_cache_generate_all.php?adminkey=$POSHKEY" -o/tmp/posh/scr_cache_generate_all.php.log -O/tmp/posh/scr_cache_generate_all.php.txt --no-check-certificate
    if [[ ! "$WGET_FILE" == *"<status>1</status>"* ]]
    then
        echo "Envole : Erreur à la regénération du cache du portail."
    fi



    # == THEMES ====================================================================
    echo "  >> Theme"
    if [ ! -s $container_path_web/var/www/html/posh/styles/main1.css ]
    then
        wget --post-data 'theme0=eole' "https://${IP_SERVEUR_WEB}/envole/api/scr_config_theme.php?adminkey=$POSHKEY" -o/tmp/posh/scr_config_theme.php.log -O/tmp/posh/scr_config_theme.php.txt --no-check-certificate
        WGET_FILE=$(cat /tmp/posh/scr_config_theme.php.txt)
        if [[ ! "$WGET_FILE" == *"<status>1</status>"* ]]
        then
            echo "Envole : Erreur à la mise en place du thème par défaut."
        fi
    fi



    # == VERSION ===================================================================
    echo "  >> Version"
    echo "UPDATE posh.adm_config SET value='3.1.2' WHERE parameter='POSHVERSION';" | mysql -uposh -h$dbhostPOSH -P$dbportPOSH posh

    # == LOCALFOLDER ===============================================================
    echo "  >> Localfolder"
    sed -i "s/define(\"__LOCALFOLDER\",\"http:\/\//define(\"__LOCALFOLDER\",\"https:\/\//" $container_path_web/var/www/html/posh/includes/config.inc.php



	#Plugin cow
	if [ "$activer_plugin_cow" == "oui" ]
	then
    # == PLUGIN COW ACTIVATION =====================================================
        echo "  >> Plugin Cow Activation"

		if ! grep "# PLUGIN COW" $container_path_web/etc/apache2/sites-available/Vhost > /dev/null ; then
			#modules apache requis
			a2enmod proxy
			a2enmod proxy_http
			#ajout ligne include dans Vhost
			sed -i "s/<\/VirtualHost>/# PLUGIN COW\\nInclude cow.*\\n\\n<\/VirtualHost>/" $container_path_web/etc/apache2/sites-available/Vhost
		fi
		if ! grep "# PLUGIN COW" $container_path_web/etc/apache2/sites-available/Vhost-ssl > /dev/null ; then
			#ajout ligne include dans Vhost-ssl
			sed -i "s/<\/VirtualHost>/# PLUGIN COW\\nInclude cow.*\\n\\n<\/VirtualHost>/" $container_path_web/etc/apache2/sites-available/Vhost-ssl
		fi
	fi

    echo " "

fi
exit 0
