#! /bin/bash
#------------------------------------------------------------------------------
#see licence at the end
ThisScriptVersion="1.26.1 - 14-07 2025 rev 0"
GoeVersion="$ThisScriptVersion Last Update : `stat -c %z $0 | cut -d"." -f1`"
Date=`date +%A_%x-%H:%M:%S`
CurrentUser=`whoami`
AllParameters="$*"
UserLogins=""
# ➡️ ⬅️ ⬆️ ⬇️ ↗️ ↘️ ↙️ ↖️ ↕️ ↔️ 🔄 ⤴️ ⤵️ ‼️ ❗️ ✅ 💾 💽 ⏳ 🛠️ 🖥️ ✅❌
#------------------------------------------------------------------------------
##StartConfig
#------------------------------------------------------------------------------
# This part of the file is copied to goe_panel/data/goe.conf
# Edit the default configuration in goe.local.conf to keep modifications
# panel mode is set /usr/local/etc/goe/goe.mode.conf, check goe --mode command
#

#future plans
# base de donnees: bouton snapshot
# base de donnees: db_update devient reformater
# base de donnees: si admin possibilite de reference pour tout le serveur
# service: code update et code upgrade en boutons séparés
# service: bouton bloquer le redémarrage, mode parking
# service: gestion du contrat du service
# service: changement de mot de passe admin global sur les bases
# serveur: gestion du contrat du VDS
# serveur: bouton et formulaire edition des valeurs par defaut DEF_
# serveur: edition des url du service
# serveur: bouton de refresh du proxy
# serveur; bouton installation et mise à jour du systeme et des dépendances

#Site parameters
#---------------
HttpUser="www-data"
TopImage="images/background.gif"
TopLogo="images/top_background.jpg"
TapeImage="<big>💾 </big>"
DiskImage="<big>💽 </big>"
WarnImage="<big>❗️ </big>"
ServiceImage="🖥️ "
SiteCss="goe.css"
SiteRefreshResult="12"
SiteRefreshPeriod="8"
SiteUrl="."
PanelHelp="http://sisalp.fr/index.php/post/Hebergement-OpenERP-et-Tryton-par-SISalp-Le-panneau-d-administration-du-serveur-VDS"
PanelSupport="https://sisalp.fr/index.php/category/A-propos-de-SISalp"
InputStyle="style=\\\"cursor:pointer; width:300px; padding:3px 20px; margin:3px; background-color:#eeeeee; border:solid 1px #999999;\\\""
ServerMenuAvailable="help support options admin_guide contract openservice closeservice monitor mooc services log"


#goe background tasks parameters
#-------------------------------
XoeAuthorizedUser="sisalpuser"
XoeDir="/home/$XoeAuthorizedUser"
GoeDir="$XoeDir/goe.panel"
GoeConfDir="/usr/local/etc/goe"
GoeConf="$GoeConfDir/goe.conf"
GoeLoginConf="$GoeConfDir/goe.login.conf"
GoeModeConf="$GoeConfDir/goe.mode.conf"

Drawings="$GoeDir/draw"
Actions="$GoeDir/action"
Forms="$GoeDir/form"
Results="$GoeDir/result"
GoeData="$GoeDir/data"
XoeLog="/home/$XoeAuthorizedUser/xoe.logs/server.$XoeAuthorizedUser.log"
XoeServicesData="$GoeData/services.data"
GoeUploads="$GoeDir/uploads"
GoeTranslations="en fr"
GoeTranslationFile="$GoeConfDir/goe.translation"
GoeCustomTranslationFile="$GoeConfDir/goe.custom.translation"
GoeCurrentLanguage="$GoeConfDir/goe.language.conf"
PageRefresh="10"
PageKeep="100"
GoeLogDir="/tmp/goe.logs"
GoeLogFile="$GoeLogDir/goe.log"
GoeLog="/dev/null"
GoeLogMode="$GoeLogDir/goe.log.mode"
GoeTemplatesLog="$GoeLogDir/goe.templates.log"
GoeActionsLog="$GoeLogDir/goe.actions.log"
GoeFormsLog="$GoeLogDir/goe.forms.log"
GoeResultsLog="$GoeLogDir/goe.results.log"
DrawingsLog="$GoeLogDir/goe.drawings.log"
GoeDataLog="$GoeLogDir/goe.data.log"
GoeRefreshConfDir="$GoeDir/goe.refresh"
GoeLocalConf="$GoeRefreshConfDir/goe.local.conf"
GoePagesList="$GoeRefreshConfDir/goe.recent_pages.list"
SiteRefreshPeriodFile="$GoeRefreshConfDir/goe.refresh_period.conf"
SiteRefreshModeFile="$GoeRefreshConfDir/goe.refresh_mode.conf"
SiteRefreshCommentFile="$GoeRefreshConfDir/goe.refresh_comment.conf"
GoeLoopStatusFile="$GoeRefreshConfDir/goe.refresh_loop_status.conf"
GoePaceTimeFile="$GoeRefreshConfDir/goe.pace_time.conf"
GoeLoopStartFile="$GoeRefreshConfDir/goe.loop_start_time.conf"
GoeOnDemandFile="$GoeRefreshConfDir/goe.ondemand.conf"
GoeRatingFile="$GoeRefreshConfDir/goe.rating.conf"
ActivityFile="$GoeRefreshConfDir/goe.activity"
GoeBuzyFlag="$GoeRefreshConfDir/buzy.flag"
GoeActingFlag="$GoeRefreshConfDir/acting"
GoePidFile="$GoeRefreshConfDir/goe.background.pid"
SiteScriptName="index.php"
SiteImages="images"
ImageSource="http://download.sisalp.net/scripts/panel/images/"
GoeDownloadSource="download.sisalp.net/scripts/panel"
PanelDownloadSource="http://download.sisalp.net/scripts/panel/panel.panel"
CssDownloadSource="http://download.sisalp.net/scripts/panel/goe.css"
MoocDownloadSource="http://download.sisalp.net/scripts/panel/mooc"
GoeLoopingFlag="/tmp/goe.looping.flag"
LoopStopFlag="/tmp/goe.loop.stop.flag"
#BackgroundMode Auto | Manual
#RefreshMode All | Displayed
RefreshMode="Displayed"
xTimes="5"
Pace="12"
LogTailLength="20"
LogDetailLength="500"
GeneralLogTailLength="60"
GeneralLogDetailLength="500"
MaxPhpUploadSize="50M"
MaxArchiveUploadSize="20971520"

##LocalConfig
#----------------
# This part of the configuration file is also copied to /usr/local/etc/goe/goe.local.conf
# panel mode is set in /usr/local/etc/goe/goe.mode.conf, check goe --mode command
# mode parameters per default
#set_mode	demo|business|education
ServerMode="demo"
#dashboard list Available :  help support options admin_guide contract openservice closeservice monitor mooc services log
ServerMenuEnabled="help support options admin_guide contract openservice closeservice monitor mooc services log"
#show|hide
HelpMode="show"
SupportMode="show"
ServerMenuMode="hide"
AdminGuideMode="hide"
ServerContractMode="hide"
OpenServiceMode="hide"
CloseServiceMode="hide"
SystemInfoMode="hide"
MoocInfoMode="hide"
ServiceDetailsMode="hide"
ServerLogMode="hide"

#default button lists
ServiceButtonsFullList="editservicemenu renew start stop restart newcase company drop newmooc managemooc exam upload installarchive upgrade"
#" : instructions anomalies servicelog : serviceactionslog "
# downgrade
DatabaseButtonsFullList="editdatabasemenu save snapshot restore clone copy reference delete wipe_out dbupdate"
#" : databaseactionslog databasearchives"

ServiceButtonsDefaultList="editservicemenu start stop"
DatabaseButtonsDefaultList="editdatabasemenu save"
RestrictedButtonsList="editservicemenu start stop restart - editdatabasemenu save restore"
CustomPageHeaderConf="$GoeConfDir/goe.custom_page_header.conf"
CustomPageFooterConf="$GoeConfDir/goe.custom_page_footer.conf"
WelcomeDatabaseScript="populate_fr.script"

#------------------------------------------------------------------------------
##EndConfig
#------------------------------------------------------------------------------
# Gestion des traductions
#------------------------------------------------------------------------------
#TR T_SiteTitle	Administration panel of your ERP server by SISalp : Panneau d administration de votre serveur ERP par SISalp
#TR T_SiteNameEnterprise	Tryton, Odoo and OpenERP on line : Tryton, Odoo et OpenERP en ligne
#TR T_SiteNameAcademy	ERP Academy : Academie ERP
#TR T_SiteSloganEnterprise	Virtual Dedicated Server<br/>by SISalp : Serveur Virtuel Dedie<br/>par SISalp
#TR T_SiteSloganAcademy	Training center for<br/>technical classes in enterprise management : Cas pedagogiques d apprentissage<br/>des techniques avancees de gestion
#TR T_Page_top	Main menu : Menu principal
#TR T_Page_back	Back to dashboard : Retour au tableau de bord

if [ ! -d $GoeDir ] ; then rm -f $GoeDir ; mkdir -p $GoeDir ; fi
if [ ! -d $GoeConfDir ] ; then rm -f $GoeConfDir ; mkdir -p $GoeConfDir ; fi
if [ -f "$GoeLocalConf" ] ; then . $GoeLocalConf ; fi
if [ -f "$GoeLoginConf" ] ; then . $GoeLoginConf ; fi
if [ -f "$GoeLogMode" ] ; then . $GoeLogMode ; fi
if [ -f "$GoeModeConf" ] ; then . $GoeModeConf ; fi
#------------------------------------------------------------------------------
EXIT ()
#------------------------------------------------------------------------------
{
case "$2" in
0)
	#LOG_MESSAGE $1 -g  --- goe $AllParameters exit OK line $1 in ${FUNCNAME[*]}
	exit 0
	;;
*)
	LOG_MESSAGE $1 -g  !!! goe $AllParameters exit on bad condition line $1 in ${FUNCNAME[*]}
	exit 1
	;;
esac
}
#------------------------------------------------------------------------------
# for xoe evolution xoe main dir changed and goe conf update is complex
#Analyse des parametres d appel
case "$1" in
--*)
	LoginUser="guest"
	;;
*)
	LoginUser="$1"
	shift
	;;
esac
case "$1" in
--*)
	if [ -f $GoeCurrentLanguage ] ; then
		Language=`cat $GoeCurrentLanguage`
	else
		Language="en"
	fi
	;;
*)
	Language="$1"
	echo "$Language" > $GoeCurrentLanguage 
	shift
	;;
esac
Option="$1"
case "$Option" in
--*)
	;;
*)
	Option="--$Option"
	;;
esac
shift
OptionParameters="$*"
#----------------------
ZoneName="$1"
NewMode="$1"
Service="$1"
NumberTimes="$1"
UserName="$1"
CodeAltSource="$*"
SetAuthorizedUser="$1"
SearchString="$*"
ShellCommand="$*"
BlablaVersion="$1"
DashboardOption="$1"
#----------------------
shift
Drawing="$1"
Database="$1"
CommentDatabase=`echo "$Database" | sed s/--/-/g`
Period="$1"
UserPassword="$1"
DashboardValue="$1"
DashboardNewService="$*"
DashboardCloseService="$1"
DashboardList="$*"
#----------------------
shift
Action="$1"
UserRole="$*"
#----------------------
shift
ActionParameters="$*"

#------------------------------------------------------------------------------
LOG_MESSAGE ()
#------------------------------------------------------------------------------
{
#$1 line_number $2 code : 404|500|501|502|-[e][g][x] $3 exit|message
case "$2" in
404)
	Message="404 $HOSTNAME|goe|`date +%H:%M:%S:%3N`|WARNING|$CurrentUser|$$|$1|$Option WARNING : Cannot find page $Drawing. goe $AllParameters --- $*"
	echo "$Message" >> $GoeLog
	#echo "$Message" >> $XoeLog
	#echo "$Message"
	;;
500)
	Message="500 $HOSTNAME|goe|`date +%H:%M:%S:%3N`|ERROR|$CurrentUser|$$|$1|$Option ERROR : Cannot execute action $Action. goe $AllParameters --- $*"
	echo "$Message" >> $GoeLog
	echo "$Message" >> $XoeLog
	#echo "$Message"
	;;
501)
	Message="501 $HOSTNAME|goe|`date +%H:%M:%S:%3N`|WARNING|$CurrentUser|$$|$1|$Option WARNING : System freeze or overloaded goe $AllParameters --- $*"
	echo "$Message" >> $GoeLog
	#echo "$Message" >> $XoeLog
	#echo "$Message"
	;;
502)
	Message="502 $HOSTNAME|goe|`date +%H:%M:%S:%3N`|ERROR|$CurrentUser|$$|$1|$Option ERROR : Access denied to internal resource goe $AllParameters --- $*"
	echo "$Message" >> $GoeLog
	echo "$Message" >> $XoeLog
	#echo "$Message"
	;;
*)
	Message="$HOSTNAME|goe|`date +%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$LoginUser|$LoginRole|$Option	$*"
	;;
esac
case "$2" in
*e*)
	echo "$Message"
	;;
esac
#case "$2" in
#*g*)
echo "$Message" >> $GoeLog
#	;;
#esac
case "$2" in
*x*)
echo "$Message" >> $XoeLog
	;;
esac

case "$3" in
exit)
	exit $2
	;;
esac
}
#end 
#------------------------------------------------------------------------------
WAIT_FOR ()
#------------------------------------------------------------------------------
{
#exemple  WAIT_FOR $LINENO 10 ! -f /tmp/toto  #delay in O.01 s
wf_call="$1"
shift
ttle="$1" #in  s
shift
iwf=0
#for ((i=0;i<$ttle;i=i+1)) ; do
#	if [ $* ] ; then
#		break
#	fi
#	sleep 0.01
#done
if [ $* ] ; then
	echo -n "." > /dev/null
#$GoeBuzyFlag.log
else
	echo -n "!$wf_call-$ttle-$*!" >> $GoeBuzyFlag.log
	for ((iwf=0;iwf<$ttle;iwf=iwf+1)) ; do	sleep 0.01 ; done
fi
#if [ $i -ge $ttle ] ; then
#	echo "$LINENO|$$|$wf_call|WAITFOR|`whoami`| goe was BUZY on `date +%A_%x-%H:%M:%S:%3N` `whoami` WAITFOR $Option too long time ${ttle}0ms waiting condition $*" >> $GoeBuzyFlag.log
#	LOG_MESSAGE "$LINENO 501 exit $cb_call|WAITFOR| too long time ${ttle}0ms waiting condition $*"
#else echo "goe did not wait on `date +%A_%x-%H:%M:%S:%3N` $cb_call|WAIT FOR too long time ${ttle}0ms waiting condition $*" >> $GoeBuzyFlag.log
#fi
}
#end 
#------------------------------------------------------------------------------
CHECK_BUZY ()
#------------------------------------------------------------------------------
{
#il faudrait un vrai semaphore
cb_call="$1"
shift
case "$1" in
set)
	echo "$LINENO|$$|$cb_call|CHECK_BUZY|`whoami`|set I am buzy from now on `date +%A_%x-%H:%M:%S:%3N`" > $GoeBuzyFlag
	echo -n "s"  >> $GoeBuzyFlag.log
	#echo "$LINENO|$$|$cb_call|CHECK_BUZY|`whoami`|set I am buzy from now on `date +%A_%x-%H:%M:%S:%3N`"  >> $GoeBuzyFlag.log
	;;
release)
	
	rm -f $GoeBuzyFlag
	echo -n "r"  >> $GoeBuzyFlag.log
	#echo "$LINENO|$$|$cb_call|CHECK_BUZY|`whoami`|release I am free from now on `date +%A_%x-%H:%M:%S:%3N`" >> $GoeBuzyFlag.log
	;;
*)
	if [ -e $GoeBuzyFlag ] ; then
		echo -n "w"  >> $GoeBuzyFlag.log
		#echo "$LINENO|$$|$cb_call|CHECK_BUZY|`whoami`|check and wait I have to WAIT because goe is buzy on `date +%A_%x-%H:%M:%S:%3N`" >> $GoeBuzyFlag.log
		#WAIT_FOR $LINENO 200 ! -e $GoeBuzyFlag
		sleep 1
		echo -n "m"  >> $GoeBuzyFlag.log
	fi
	#chmod 660 $GoeBuzyFlag.log > /dev/null 2>&1
	;;
esac
}
#end 

#------------------------------------------------------------------------------
CAT ()
#------------------------------------------------------------------------------
{
WAIT_FOR $LINENO 200 -f $1
cat $1
}
#end 
#------------------------------------------------------------------------------
GET_XOE_DATA ()
#------------------------------------------------------------------------------
{
LOG_MESSAGE $LINENO -g GET_XOE_DATA $*
gxd_line="$1"
shift
get_xoe_data_service="$1"

if [ ! -f $XoeServicesData ] ; then
	/usr/local/bin/xoe --config -list -data > $XoeServicesData
fi
. $XoeServicesData
if [ ! -z "$get_xoe_data_service" ] ; then
	cat $XoeServicesData | grep "^#Service:" | cut -f2- > /tmp/goe.get_xoe_data.$$.sh
	if [ -f /tmp/goe.get_xoe_data.$$.sh ] ; then
		. /tmp/goe.get_xoe_data.$$.sh $get_xoe_data_service GET_XOE_DATA function of goe line $gxd_line
		rm -f /tmp/goe.get_xoe_data.$$.sh
	else
		LOG_MESSAGE $LINENO -g GET_XOE_DATA service $get_xoe_data_service is not found in xoe service data
	fi
fi
}
#end 
#------------------------------------------------------------------------------
GET_ROLE ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO -g GET_ROLE $LoginUser 
case "$LoginUser" in
guest)
	LoginRole="$LoginUser"
	;;
*)
	LoginRole=`echo "$UserLogins" 2>/dev/null | grep "^$LoginUser " | tail -n 1 | cut -d" " -f3`
	if [ -z "$LoginRole" ] ; then
		#login user should be a service in this case
		GET_XOE_DATA $LINENO-GET_ROLE $LoginUser
		LoginRole="$XoeLoginRole"
	fi
	;;
esac
#LOG_MESSAGE $LINENO -g GET_ROLE LoginUser $LoginUser LoginRole $LoginRole
}
#end 
#-------------------------------------------------------------------------
NEW_PASSWORD ()
#-------------------------------------------------------------------------
{
case "$1" in
-min)
	pw_letters=(a b c d e f g h i j k m n o p q r s t u v w x y z a b c d e f g h i j k m n o p q r s t u v w x z 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 )
	shift
	;;
-letters)
	pw_letters=(a b c d e f g h i j k m n o p q r s t u v w x y z )
	shift
	;;
*)
	pw_letters=(a b c d e f g h i j k m n o p q r s t u v w x y z A B C D E F G H I J K L M N P Q R S T U V W X Y Z 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 )
	;;
esac

if [ -z "$1" ] ; then
	pw_nb_digits=12
else
	pw_nb_digits="$*"
fi
pw_range="${#pw_letters[*]}"
NEW_PWD=""
for nb_digit in $pw_nb_digits ; do
	if [ ! -z "$NEW_PWD" ] ; then NEW_PWD="${NEW_PWD}""_" ; fi
	for ((  pw_digit = 1 ;  pw_digit <= $nb_digit ;  pw_digit++  )) ; do
		pw_index="$(($RANDOM%$pw_range))"
		NEW_PWD="${NEW_PWD}""${pw_letters[$pw_index]}"
	done
done
echo "$NEW_PWD"
}
#end 
#------------------------------------------------------------------------------
GET_DATA ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO -g GET_DATA $* Mode $ServerMode command $Option $AllParameters
#SECURITE il conviendrait d'initialiser les variables avant de jouer le fichier d'affectations
get_line="$1"
shift
collect_function="$1"
collect_service="$2"
collect_database="$3"
case "$collect_function" in
page)
	#LOG_MESSAGE $LINENO -g GET_DATA $get_line Chargement de la liste des services $* Mode $ServerMode command $Option $AllParameters
	GET_XOE_DATA
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Liste des services $* Mode $ServerMode command $Option $AllParameters
	;;
contract)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des informations de gestion du contrat
	#WAIT_FOR $LINENO 200 -f "$GoeData/contract.data"
	. $GoeData/contract.data
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Informations de gestion du contrat
	;;
admin_guide)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des informations d admin du serveur
	#WAIT_FOR $LINENO 200 -f "$GoeData/admin_guide.data"
	. $GoeData/admin_guide.data
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Informations d admin du serveur
	;;
openservice)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des informations ouverture de service
	#WAIT_FOR $LINENO 200 -f "$GoeData/openservice.data"
	. $GoeData/openservice.data
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Informations ouverture de service
	;;
closeservice)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des informations cloture de service
	#WAIT_FOR $LINENO 200 -f "$GoeData/closeservice.data"
	. $GoeData/closeservice.data
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Informations cloture de service
	;;
system)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des informations relatives au systeme
	#WAIT_FOR $LINENO 200 -f "$GoeData/system.data"
	. $GoeData/system.data
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Informations relatives au systeme
	;;
mooc)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des informations relatives aux mooc
	#WAIT_FOR $LINENO 120 -f "$GoeData/mooc.data"
	. $GoeData/mooc.data
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Informations relatives aux mooc
	;;
service)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des donnees du service $collect_service
	. $GoeData/service.data $collect_service
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Donnees du service $Service
	;;
dashboard_menu)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des donnees de menu du service $collect_service
	. $GoeData/dashboard.data $collect_service
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Donnees de menu du service $Service - $ServiceStatus - $ServiceDoc - $DatabaseNumber
	;;
database)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des donnees de la base $collect_database du service $collect_service
	. $GoeData/database.data $collect_service $collect_database
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Donnees de la base $collect_database du service $Service
	;;
general_log)
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Chargement des donnees du log general
	. $GoeData/general_log.data
	#LOG_MESSAGE $LINENO -g GET_DATA  $get_line Donnees du log general
	;;
esac
}
#end 
#------------------------------------------------------------------------------
ZONE_TO_SERVICE ()
#------------------------------------------------------------------------------
{
LOG_MESSAGE $LINENO -g  ZONE_TO_SERVICE $* zone $ZoneName drawing $DrawingName action and parameters $Action $ActionParameters
TemplateFile="$1"
if [ -z "$TemplateFile" ] ; then
	TemplateFile="$ZoneName"
	LOG_MESSAGE $LINENO -g  ZONE_TO_SERVICE $* Template is defaulted to zone $ZoneName
fi
LOG_MESSAGE $LINENO -g  ZONE_TO_SERVICE $* Template is $TemplateFile
case "$ZoneName" in
zone.log*|zone.page*|zone.admin_guide|zone.contract|zone.open_service|zone.close_service)
	Service=""
	Database=""
	;;
*)
	case "$TemplateFile" in
	zone*)
		Service=`echo "$TemplateFile" | cut -d. -f2`
		Database=`echo "$TemplateFile" | cut -d. -f3`
		;;
	*.action|*.form|*.result)
		LOG_MESSAGE $LINENO -g  ZONE_TO_SERVICE Template is $TemplateFile
		if [ -z "`echo "$TemplateFile" | cut -d. -f4`" ] ; then
			Service=`echo "$TemplateFile" | cut -d. -f1`
			Database=""
			TemplateDir=`echo "$TemplateFile" | cut -d. -f3`
			TemplateFile=`echo "$TemplateFile" | cut -d. -f2-`
			TemplateFile="$GoeDir/$TemplateDir/$TemplateFile"
		else
			Service=`echo "$TemplateFile" | cut -d. -f1`
			Database=`echo "$TemplateFile" | cut -d. -f2`
			TemplateDir=`echo "$TemplateFile" | cut -d. -f4`
			TemplateFile=`echo "$TemplateFile" | cut -d. -f3-`
			TemplateFile="$GoeDir/$TemplateDir/$TemplateFile"
		fi
		;;
	*.draw)
		Service=`echo "$TemplateFile" | cut -d. -f1`
		Database=`echo "$TemplateFile" | cut -d. -f2`
		TemplateFile="$GoeDir/draw/$TemplateFile"
		;;
	esac
	if [ ! -z "$Service" ] ; then
		GET_DATA $LINENO service $Service
	fi
	if [ ! -z "$Database" ] ; then
		GET_DATA $LINENO database $Service $Database
	fi
	LANGUAGE $LINENO $Language
	;;
esac
CommentDatabase=`echo "$Database" | sed s/--/-/g`
LOG_MESSAGE $LINENO -g  ZONE_TO_SERVICE service $Service database $Database templatefile $TemplateFile
}
#end 
#------------------------------------------------------------------------------
DRAWING_TO_SERVICE ()
#------------------------------------------------------------------------------
{
LOG_MESSAGE $LINENO -g  DRAWING_TO_SERVICE $* drawing_name $1
Service=""
Database=""
if [ ! -z "$1" ] ; then
	drawingname="$1"
	case "$drawingname" in
	page.draw|log_detail.draw|admin_guide.draw|contract.draw|open_service.draw|close_service.draw)
		;;
	*.log_detail.draw)
		Service=`basename $drawingname .log_detail.draw`
		;;
	*.detail.draw)
		information=`basename $drawingname .detail.draw`
		case "$information" in
		*.*)
			Service=`echo "$information" | cut -d. -f1`
			Database=`echo "$information" | cut -d. -f2`
			CommentDatabase=`echo "$Database" | sed s/--/-/g`
			;;
		*)
			Service="$information"
			;;
		esac
		;;
	*.draw)
		Service=`basename $drawingname .draw`
		;;
	esac
fi
LOG_MESSAGE $LINENO -g  DRAWING_TO_SERVICE service $Service database $Database drawing_name $drawingname
}
#end 
#------------------------------------------------------------------------------
DRAW ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO -g  DRAW $*
DrawingName="$1"
if [ -z "$DrawingName" ] ; then
	DrawingName="page.draw"
fi
if [ ! -e $GoePagesList ] || [ -w $GoePagesList ] ; then
	echo "$DrawingName" >> $GoePagesList
	recentpages=`tail -n $PageKeep $GoePagesList`
	echo "$recentpages" > $GoePagesList
fi
#echo "DRAW write in $GoePagesList `date +'%Hh%Mm%Ss:%3N'` $$ $CurrentUser $Option $DrawingName"  >> $GoeDir/goe.draw.log
case "$DrawingName" in
*.draw)
	if [ -z "$LoginRole" ] ; then
		LOG_MESSAGE $LINENO -g  DRAW refus des demandes sans identifiant utilisateur de role connu
		DrawingName="Access_Denied"
	else
		case "$DrawingName" in
		page*)
			#LOG_MESSAGE $LINENO -g  DRAW Controle des droits sur page.draw
			case "$LoginRole" in
			Admin*|admin*)
				;;
			*)
				LOG_MESSAGE $LINENO -g  DRAW LoginRole $LoginRole Substitution de la page par $LoginUser.draw
				ServiceLandingPage="$LoginUser.draw"
				DrawingName="$ServiceLandingPage"
				echo "$DrawingName" >> $GoePagesList
				;;
			esac
			;;
		*)
			LOG_MESSAGE $LINENO -g  DRAW Controle des droits sur les autres pages
			case "$LoginRole" in
			Admin*|admin*)
				;;
			*)
				LOG_MESSAGE $LINENO -g  DRAW Controle des droits d acces a la page $DrawingName
				case "$DrawingName" in
				*/*|*..*|*'#'*|*'$'*|*'&'*|*';'*|*.draw*.draw)
					# Hacking attempt
					LOG_MESSAGE $LINENO -g  DRAW Tentative de violation de securite par $LoginRole sur la page $DrawingName
					DrawingName="Access_Denied"
					;;
				$LoginRole.*)
					# Authorized
					echo "$DrawingName" >> $GoePagesList
					;;
				*)
					LOG_MESSAGE $LINENO -g  DRAW Refus de l acces demande par $LoginRole a la page $DrawingName
					DrawingName="Access_Denied"
					;;
				esac
				;;
			esac
			;;
		esac

		CHECK_BUZY $LINENO
		WAIT_FOR $LINENO 150 -f "$Drawings/$DrawingName"
		if [ ! -f $GoeOnDemandFile ] ; then
			echo "NO" > $GoeOnDemandFile
		fi
		OnDemand=`cat $GoeOnDemandFile`
		case "$OnDemand" in
		YES)
			DrawNow="YES"
			;;
		*)
			if [ -f "$Drawings/$DrawingName" ] ; then
				cat $Drawings/$DrawingName
				DrawNow="No"
			else
				DrawNow="YES"
			fi
			;;
		esac
		case "$DrawNow" in
		YES)
			# if not available, content is created on the fly
			if [ -z "$ZoneName" ] ; then
				ZoneName="$DrawingName"
			fi
			LOG_MESSAGE $LINENO -g "Looking for missing page $Drawings/$DrawingName, served in real time by $CurrentUser /usr/local/bin/goe --draw_now $ZoneName $DrawingName"
			case "$CurrentUser" in
			$XoeAuthorizedUser)
				/usr/local/bin/goe --draw_now $ZoneName $DrawingName
				;;
			$HttpUser)
				#sudo su $XoeAuthorizedUser -c "/usr/local/bin/goe --draw_now $ZoneName $DrawingName"
				/usr/local/bin/goe --draw_now $ZoneName $DrawingName
				;;
			root)
				su $XoeAuthorizedUser -c "/usr/local/bin/goe --draw_now $ZoneName $DrawingName"
				;;
			esac
			;;
		esac
	fi
	;;
*.action|*.form|*.result)
	TemplateFile="$DrawingName"
	LOG_MESSAGE $LINENO -g "DRAW action $DrawingName"
	ZONE_TO_SERVICE $DrawingName
	CHECK_BUZY $LINENO
	WAIT_FOR $LINENO 100 -f $TemplateFile
	if [ -f "$TemplateFile" ] ; then
		. $TemplateFile
	else
		if [ -f $Drawings/default.detail.draw ] ; then
			LOG_MESSAGE $LINENO -g "looking for template $TemplateFile,  served $Drawings/default.detail.draw instead"
			cat $Drawings/default.detail.draw
		else
			LOG_MESSAGE $LINENO 404 exit "looking for $TemplateFile"
		fi
	fi
	;;
open_service)
	#TR T_Open_service_result	Open new service : Ouverture du nouveau service
	#TR T_Open_service_result_message	Service is going to be configured, set and started : Le service est en cours de configuration, d installation et de demarrage
	#TR T_open_service_result_wait	and will be available soon : et sera bientot disponible

	echo "<zone name=\"zone.open_service_result\">
	<zone_refresh><![CDATA[<meta http-equiv=\"Refresh\" content=\"30;url=../index.php?action=--page zone.open_service open_service.draw\" />]]></zone_refresh>
        <zone_title><![CDATA[<title>$T_Open_service_result</title>]]></zone_title>
        <zone_type>button_result</zone_type>
        <zone_status>ok</zone_status>
	<zone_html><![CDATA[<hr/><br/><br/>$T_Open_service_result_message <br/>$T_open_service_result_wait<br/> ]]></zone_html>
</zone>"
	;;
close_service)
	#TR T_Close_service_result	Close service : Cloture du service
	#TR T_Close_service_result_message	Service is going to be closed and archived : Le service est en cours de cloture et d archivage
	#TR T_close_service_result_wait	and will be deleted from services list soon : et sera bientot supprime de la liste des services
	echo "<zone name=\"zone.toggle_result\">
	<zone_refresh><![CDATA[<meta http-equiv=\"Refresh\" content=\"30;url=../index.php?action=--page zone.close_service close_service.draw\" />]]></zone_refresh>
        <zone_title><![CDATA[<title>$T_Close_service_result</title>]]></zone_title>
        <zone_type>button_result</zone_type>
        <zone_status>ok</zone_status>
	<zone_html><![CDATA[<hr/><br/><br/>$T_Close_service_result_message<br/>$T_close_service_result_wait<br/>]]></zone_html>
</zone>"
	;;
dashboard)
	#goe --page
	#TR T_Toggle	Modification of dashboard display : Modification de l'affichage du tableau de bord
	#TR T_Toggle_return_message	New dashboard format is going to be displayed : Le nouveau format du tableau de bord va etre affiche
	echo "<zone name=\"zone.toggle_result\">
	<zone_refresh><![CDATA[<meta http-equiv=\"Refresh\" content=\"0;url=../index.php\" />]]></zone_refresh>
        <zone_title><![CDATA[<title>$T_Toggle</title>]]></zone_title>
        <zone_type>button_result</zone_type>
        <zone_status>ok</zone_status>
	<zone_html><![CDATA[$BackImage<hr/><br/>$T_Toggle<br/>$T_Toggle_return_message <br/> ]]></zone_html>
</zone>"
	;;
*)
	LOG_MESSAGE $LINENO 404 exit
	;;
esac
}
#end 
#------------------------------------------------------------------------------
RUN_ACTION ()
#------------------------------------------------------------------------------
{
ActionFile="$1"
LOG_MESSAGE $LINENO -g  RUN_ACTION action $*
if [ ! -z "$ActionParameters" ] ; then
	case "$ActionFile" in
	goe)
		$0 $ActionParameters
		;;
	*)
		case "$ActionFile" in
		*.action|*.result|*.form)
			ZONE_TO_SERVICE $ActionFile
			ActionFile="$TemplateFile"
			;;
		esac
		WAIT_FOR $LINENO 100 -x "$ActionFile"
		if [ -x "$ActionFile" ] ; then
			ActionMessage=`$ActionFile --check $ServerMode $ActionParameters`
			case "$ActionMessage" in
			4*|5*)
				ActionResultStatus="fault"
				;;
			*)
				ActionResultStatus="ok"
				CHECK_BUZY $LINENO
				nohup $ActionFile --execute $ServerMode $ActionParameters >> $GoeLog 2>&1 &
				;;
			esac
			LOG_MESSAGE $LINENO -g  Launching action $ActionFile $ActionParameters :: $ActionMessage
		else
			LOG_MESSAGE $LINENO 500 exit "looking for $ActionFile : not found or cannot execute"
		fi
		;;
	esac
else
	LOG_MESSAGE $LINENO -g RUN_ACTION No action parameters found
	ActionResultStatus="ok"
fi
}
#end
#------------------------------------------------------------------------------
TR ()
#------------------------------------------------------------------------------
{
	shift
	if [ ! -z $1 ] ; then
		translator="$1"
		shift
		lang_index="1"
		for tr_lang in $GoeTranslations ; do
			lang_text=`echo "$*" | cut -d: -f$lang_index | sed s/' $'//`
			echo "$translator=\"$lang_text\"" >> $GoeTranslationFile.$tr_lang
			lang_index=$[$lang_index +1]
		done
	fi
}
#end
#------------------------------------------------------------------------------
TRANSLATE ()
#------------------------------------------------------------------------------
{
	new_translation="no"
	for lang in $GoeTranslations ; do
		if [ ! -f $GoeTranslationFile.$lang ] ; then
			rm -f $GoeTranslationFile.*
			new_translation="yes"
			break
		fi
	done
	case "$new_translation" in
	yes)
		old_IFS=$IFS
		IFS=$'\n'
		for TR_line in `cat $0 $0.* | grep "#TR " | grep -v "#Not me"` ; do  #Not me
			IFS=$old_IFS
			TR $TR_line
			IFS=$'\n'
		done
		IFS=$old_IFS
		for lang in $GoeTranslations ; do
			mv $GoeTranslationFile.$lang $GoeTranslationFile.$lang.$$.tmp
			sort $GoeTranslationFile.$lang.$$.tmp > $GoeTranslationFile.$lang
			rm -f $GoeTranslationFile.$lang.$$.tmp
			echo "# $Date $GoeVersion $AllParameters" >> $GoeTranslationFile.$lang
			chmod 777 $GoeTranslationFile.$lang
			sudo chown $XoeAuthorizedUser:$HttpUser $GoeTranslationFile.$lang
		done
		;;
	esac
}
#end
#------------------------------------------------------------------------------
CHECK_ACCESS_RIGHTS ()
#------------------------------------------------------------------------------
{
case "$CurrentUser" in
$HttpUser)
	Sudo="/usr/bin/sudo"
	#sudo su $XoeAuthorizedUser -c "$0 $AllParameters"
	#exit 0
	;;
root)
	Sudo=""
	;;
$XoeAuthorizedUser|*)
	Sudo="/usr/bin/sudo"
	;;
esac
case "$CurrentUser" in
root|$XoeAuthorizedUser)
	for directory in $GoeConfDir $GoeDir $Drawings $Actions $Forms $Results $GoeData $GoeLogDir $GoeRefreshConfDir $GoeUploads ; do
		if [ -h $directory ] ; then
			$Sudo rm -f $directory
		fi
		if [ ! -d $directory ] ; then
			$Sudo mkdir -p $directory
		fi
		$Sudo chmod -R 770 $directory > /dev/null 2>&1
		$Sudo chown -R $XoeAuthorizedUser:$HttpUser $directory  > /dev/null 2>&1
	done
	if [ ! -f $GoeLoginConf ] ; then
		echo "UserLogins=\"$UserLogins\"" > $GoeLoginConf
	fi
	if [ ! -f "$ActivityFile" ] ; then
		echo -n "1234567890123456" > $ActivityFile
	fi
	if [ ! -f $GoeActionsLog ] ; then
		echo "Actions log" > $GoeActionsLog
	fi
	if [ ! -f "$GoeLogFile" ] ; then
		echo "Initializing Goe log in $GoeLogFile" > $GoeLogFile
	fi
	if [ ! -f "$GoeBuzyFlag.log" ] ; then
		echo "List of real time conflicts" > $GoeBuzyFlag.log
	fi
	for conffile in $GoeLoginConf $ActivityFile $GoeActionsLog $GoeLogFile $GoeBuzyFlag.log $GoeCurrentLanguage $XoeLog ; do
		if [ -f $conffile ] ; then
			$Sudo chmod 770 $conffile > /dev/null 2>&1
			$Sudo chown $XoeAuthorizedUser:$HttpUser $conffile > /dev/null 2>&1
		fi
	done
	;;
*)
	if [ ! -w "$ActivityFile" ] ; then
		LOG_MESSAGE $LINENO 502 Cannot notify activity in $ActivityFile
	fi
	;;
esac
}
#end
#------------------------------------------------------------------------------
CHECK_ACCESS_RIGHTS
TRANSLATE
#-------------------------------------------------------------------------
PHP_UPLOAD_MAX ()
#-------------------------------------------------------------------------
{
#should check only 1 php7 version is available
	if [ -f /etc/php/7.*/apache2/php.ini ] ; then
		php_config_ini=`ls /etc/php/7.*/apache2/php.ini 2>/dev/null`
		if [ -f $php_config_ini ] && ! cat $php_config_ini | grep "^upload_max_filesize =" > /dev/null 2>&1 ; then
			echo "upload_max_filesize = $MaxPhpUploadSize" >> $php_config_ini
			echo "upload_max_filesize = $MaxPhpUploadSize is set in $php_config_ini"
		fi
	fi
}
#end 
#------------------------------------------------------------------------------
LANGUAGE ()
{
	#LOG_MESSAGE $LINENO LANGUAGE $*
	lang_line="$1"
	shift
	new_lang="$1"
	#case "$CurrentLanguage" in
	#None)
	#	LOG_MESSAGE $LINENO -g $Option $lang_line LANGUAGE page language is set to $new_lang
	#	;;
	#esac
	if [ -z "$new_lang" ] ; then
		new_lang="en"
	fi
	case "$new_lang" in
	$CurrentLanguage)
	#	LOG_MESSAGE $LINENO -g $Option $lang_line LANGUAGE language is unchanged $Service
		;;
	*)
		if [ -e $GoeTranslationFile.$new_lang ] ; then
			. $GoeTranslationFile.$new_lang
		else
			LOG_MESSAGE $LINENO -g $Option $lang_line LANGUAGE traduction file $GoeTranslationFile.$new_lang not found
		fi
		if [ -e $GoeCustomTranslationFile.$new_lang ] ; then
			. $GoeCustomTranslationFile.$new_lang
		fi
		CurrentLanguage="$new_lang"
		#LOG_MESSAGE $LINENO -g $Option $lang_line LANGUAGE traduction en $CurrentLanguage $Service
		;;
	esac	
}
CurrentLanguage="None"
LANGUAGE $LINENO $Language
BackImage="<a href=\"$SiteUrl\" title=\"$T_Page_back\"><big>⬅️ </big></a>"
BackToTopImage="<a href=\"$SiteUrl\" title=\"$T_Page_top\"><big>⬆️ </big></a>"
#------------------------------------------------------------------------------
LOG_MESSAGE $LINENO -g  ====Call $0 $AllParameters

GET_ROLE
case "$Option" in
#------------------------------------------------------------------------------
--on_duty)
	echo -n "x" > $ActivityFile
	echo "<!--frontend activity is set in  $ActivityFile -->"
	LOG_MESSAGE $LINENO -g --on_duty frontend activity is set in  $ActivityFile
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--on_click)
	LOG_MESSAGE $LINENO -g ON_CLICK action $Action
	RUN_ACTION  $Action
	LOG_MESSAGE $LINENO -g drawing $Drawing
	DRAW $Drawing
	echo -n "x" > $ActivityFile
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--refresh)
	$0 --get_service_data
	$0 --collect
	$0 --draw
	DRAW $Drawing
	echo -n "x" > $ActivityFile
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--page)
	DRAW $Drawing
	echo -n "x" > $ActivityFile
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--config_head_css)
	echo "<link rel=\"stylesheet\" type="text/css" href=\"$SiteCss\" />"
	EXIT $LINENO 0
	;;
--config_head_title)
	echo "<title>$T_SiteTitle</title>"
	EXIT $LINENO 0
	;;
--config_head_refresh)
	if [ -f "$SiteRefreshPeriodFile" ] ; then
		SiteRefreshPeriod=`cat $SiteRefreshPeriodFile`
	fi
	case "$SiteRefreshPeriod" in
	0)
		;;
	*)
		echo "<meta http-equiv=\"Refresh\" content=\"$SiteRefreshPeriod\"/>"
		;;
	esac
	EXIT $LINENO 0
	;;
--config_page_header)
	if [ -f $CustomPageHeaderConf ] ; then
		. $CustomPageHeaderConf
	fi
	case "$ServerMode" in
	demo|education)
		SiteName="$T_SiteNameAcademy"
		SiteSlogan="$T_SiteSloganAcademy"
		;;
	*|*business)
		SiteName="$T_SiteNameEnterprise"
		SiteSlogan="$T_SiteSloganEnterprise"
		;;
	esac
	SiteHeader="<div id=\"top_header\"><a href=\"$SiteUrl\"><div id=\"header\"><h1><span>$SiteName</span></h1><h2>$SiteSlogan</h2></div></a></div>"
	echo "$SiteHeader"
	EXIT $LINENO 0
	;;
--config_welcome_message)
	#TR T_Welcome		Hello,&nbsp; : Bonjour,&nbsp;
	#TR T_DemoMessage	Demonstration Mode - Actions are not executed : Mode Demonstration - Les actions ne sont pas executees
	case "$ServerMode" in
	demo*)
		WelcomeMessage="$T_DemoMessage &nbsp;-&nbsp;$T_Welcome"
		;;
	*)
		WelcomeMessage="$T_Welcome"
		;;
	esac
	echo -n "$WelcomeMessage"
	EXIT $LINENO 0
	;;
--config_page_footer)
	#TR T_Contact_us	CONTACT US : CONTACTEZ NOUS
	SiteFooter="<div id=\"footer\"><div id=\"block_contact_infos\">
<h4>$T_Contact_us</h4>
<strong>SISalp</strong><br/>		
Les Millieres<br/>
74230 SERRAVAL - FRANCE<br/>
Tel: +33 (0)622 616 438<br/>	
<a href=\"http://sisalp.fr\">sisalp.fr</a>
</div></div>"
	if [ -f $CustomPageFooterConf ] ; then
		. $CustomPageFooterConf
	fi
	echo "$SiteFooter"
	EXIT $LINENO 0
	;;
--config_login_form)
	#TR T_User	User : Utilisateur
	#TR T_Password	Password : Mot de passe
	LoginForm="
		<form method=\"post\" action=\".\">
			<label for=\"login\">$T_User</label>&nbsp;<input type=\"text\" name='login' size=\"12\" required >&nbsp;&nbsp;&nbsp;
			<label for=\"pass\">$T_Password</label>&nbsp;<input type=\"password\" name='pass' size=\"12\" required >&nbsp;&nbsp;&nbsp;
			<img src=\"images/fr.jpg\"> <input name=\"language\" type=\"radio\" value=\"fr\" checked=\"yes\">
			<img src=\"images/en.jpg\"> <input name=\"language\" type=\"radio\" value=\"en\">&nbsp;&nbsp;&nbsp;
			<img src=\"images/login.gif\" alt=\"Log me in\" title=\"Log me in\" />&nbsp;&nbsp;&nbsp;
			<input type=\"submit\" name=\"connect\" value=\"Login\">
		</form>"
	echo -n "$LoginForm"
	EXIT $LINENO 0
	;;
--config_denied_message)
	#TR T_Access_denied Access denied. Please try again : Acces refuse. Veuillez essayer de nouveau.

	LOG_MESSAGE $LINENO -g config_denied_message $T_Access_denied $OptionParameters
	DeniedMessage="<p>$T_Access_denied $OptionParameters</p>"
	echo -n "$DeniedMessage"
	EXIT $LINENO 0
	;;
--config_login_footer)
	#TR T_Test_bandwith	Test current bandwidth from server : Testez le debit actuel du serveur
	#TR T_start_test	start test : demarrer le test
	PerformanceScript="<script type=\"text/javascript\">
//<!--
var image = 'images/testimage.jpg';
var size = 620;
var time1 = 0;
var time2 = 0;
function start_test_vitesse()
{
time1 = new Date();
time1 = time1.getTime();
var img = new Image();
img.src = image+'?'+time1;
img.onload=end_test_vitesse;
}
function end_test_vitesse()
{
var time2 = new Date();
time2 = time2.getTime();
var ms = time2-time1;
var vitesse = Math.round(size/ms*800)/100;
document.getElementById('vitesse').value=vitesse+' Mb/s';
}
//-->
</script>"
	LoginFooter="<div id=\"footer\"><div id=\"block_performance\">
$PerformanceScript
$T_Test_bandwith<br/><br/><input type=\"button\" value=\"$T_start_test\" onclick=\"javascript:start_test_vitesse();\" />&nbsp;&nbsp;&nbsp;<input type=\"text\" id=\"vitesse\" size=\"16\" /><br/><br/></div></div> <!-- footer -->"
	echo "$LoginFooter"
	EXIT $LINENO 0
	;;
--config_page_menu)
	#TR T_Help		Help : Aide
	#TR T_Support		Support : Support
	#TR T_Show		✅ : ✅
	#TR T_Hide		❌ : ❌
	#TR T_Show		Add : Ajouter
	#TR T_Hide		Hide : Retirer
	#TR T_SH_Close		Close : Fermer

	#TR T_SH_More		More... : Plus...

	#TR T_SH_admin_guide	Administration guide : Guide d administration
	#TR T_SH_contract	Contract info : Contrat
	#TR T_SH_openservice	Open service : Nouveau service
	#TR T_SH_closeservice	Close service : Cloture de service
	#TR T_SH_monitor	System status : Etat du system
	#TR T_SH_mooc		Mooc courses : Cours mooc
	#TR T_SH_services	Services status : Etat des services
	#TR T_SH_log		Log messages : Messages du serveur
	#TR T_Compose_main_page	Compose this general dashboard : Composer ce tableau de bord
	#TR T_Service_list_title	Go to services detailled information : Acces aux fiches detaillees des services
	

	LOG_MESSAGE $LINENO -g config_page_menu LoginUser $LoginUser LoginPassword $LoginPassword LoginRole $LoginRole
	case "$LoginRole" in
	Admin*|admin*)
		GET_XOE_DATA
		ServicesMenu=`cat $Drawings/menu.draw`
#	SiteMenu="<div id=\"menu\"><a target=\"_blank\" href=\"$PanelHelp\"><div class=\"menu_element\"><div class=\"static\"> $T_Help </div></div></a><a target=\"_blank\" href=\"$PanelSupport\"><div class=\"menu_element\"><div class=\"static\"> $T_Support </div></div></a><a target=\"_blank\" href=\"$PanelSupport\"><div class=\"menu_element\"><div class=\"static\"> $T_Show... </div></div></a> $ServicesMenu"

		for ServerMenuElement in $ServerMenuEnabled ; do
			case "$ServerMenuAvailable" in
			*$ServerMenuElement*)
				;;
			*)
				LOG_MESSAGE $LINENO -g list of enabled server menu contains unavailable item $ServerMenuElement
				ServerMenuMode="hide"
				;;
			esac
		done
		SiteMenu="
<div class=\"menu\">"
		case "$HelpMode" in
		show)
			SiteMenu="$SiteMenu
<a target=\"_blank\" href=\"$PanelHelp\"><div class=\"menu_element\"><div class=\"static\"> $T_Help </div></div></a>"
			;;
		esac
		case "$SupportMode" in
		show)
			SiteMenu="$SiteMenu
<a target=\"_blank\" href=\"$PanelSupport\"><div class=\"menu_element\"><div class=\"static\"> $T_Support </div></div></a>"
			;;
		esac
		case "$AdminGuideMode" in
		show)
			SiteMenu="$SiteMenu
<a target=\"_blank\" href=\"../index.php?action=--page zone.admin_guide admin_guide.draw\" title=\"$T_SH_admin_guide\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_admin_guide </div></div></a>"
			;;
		esac
		case "$ServerContractMode" in
		show)
			SiteMenu="$SiteMenu
<a target=\"_blank\" href=\"../index.php?action=--page zone.contract contract.draw\" title=\"$T_SH_contract\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_contract </div></div></a>"
			;;
		esac
		case "$OpenServiceMode" in
		show)
			SiteMenu="$SiteMenu
<a target=\"_blank\" href=\"../index.php?action=--page zone.open_service open_service.draw\" title=\"$T_SH_openservice\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_openservice </div></div></a>"
			;;
		esac
		case "$CloseServiceMode" in
		show)
			SiteMenu="$SiteMenu
<a target=\"_blank\" href=\"../index.php?action=--page zone.close_service close_service.draw\" title=\"$T_SH_closeservice\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_closeservice </div></div></a>"
			;;
		esac
		case "$SystemInfoMode" in
		show)
			SiteMenu="$SiteMenu
<a href=\"#system_table\" title=\"$T_SH_monitor\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_monitor </div></div></a>"
			;;
		esac
		case "$MoocInfoMode" in
		show)
			SiteMenu="$SiteMenu
<a href=\"#mooc_table\" title=\"$T_SH_mooc\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_mooc </div></div></a>"
			;;
		esac
		case "$ServiceDetailsMode" in
		show)
			SiteMenu="$SiteMenu
<a href=\"#service_status\" title=\"$T_SH_services\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_services </div></div></a>"
			;;
		esac
		case "$ServerLogMode" in
		show)
			SiteMenu="$SiteMenu
<a href=\"#zonelog_tail_map\" title=\"$T_SH_log\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_log </div></div></a>"
			;;
		esac
		case "$ServerMenuMode" in
		show)
			SiteMenu="$SiteMenu
</div>
<div class=\"dashboard_title\">$T_Compose_main_page</div>
<div class=\"menu\">"

			case "$ServerMenuEnabled" in
			*options*)
				SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard options hide\" title=\"$T_SH_Close\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_Close </div></div></a>"
				;;
			esac

			case "$AdminGuideMode" in
			show)
				case "$ServerMenuEnabled" in
				*admin_guide*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard admin_guide hide\" title=\"$T_Hide $T_SH_admin_guide\"><div class=\"menu_element\"><div class=\"static\"> $T_Hide $T_SH_admin_guide </div></div></a>"
					;;
				esac
				;;

			*)
				case "$ServerMenuEnabled" in
				*admin_guide*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard admin_guide show\" title=\"$T_Show $T_SH_admin_guide\"><div class=\"menu_element\"><div class=\"static\"> $T_Show $T_SH_admin_guide </div></div></a>"
					;;
				esac
				;;
			esac
			case "$ServerContractMode" in
			show)
				case "$ServerMenuEnabled" in
				*contract*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard contract hide\" title=\"$T_Hide $T_SH_contract\"><div class=\"menu_element\"><div class=\"static\"> $T_Hide $T_SH_contract </div></div></a>"
					;;
				esac
				;;

			*)
				case "$ServerMenuEnabled" in
				*contract*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard contract show\" title=\"$T_Show $T_SH_contract\"><div class=\"menu_element\"><div class=\"static\"> $T_Show $T_SH_contract </div></div></a>"
					;;
				esac
				;;
			esac
			case "$OpenServiceMode" in
			show)
				case "$ServerMenuEnabled" in
				*openservice*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard openservice hide\" title=\"$T_Hide $T_SH_openservice\"><div class=\"menu_element\"><div class=\"static\"> $T_Hide $T_SH_openservice </div></div></a>"
					;;
				esac
				;;

			*)
				case "$ServerMenuEnabled" in
				*openservice*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard openservice show\" title=\"$T_Show $T_SH_openservice\"><div class=\"menu_element\"><div class=\"static\"> $T_Show $T_SH_openservice </div></div></a>"
					;;
				esac
				;;
			esac
			case "$CloseServiceMode" in
			show)
				case "$ServerMenuEnabled" in
				*closeservice*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard closeservice hide\" title=\"$T_Hide $T_SH_closeservice\"><div class=\"menu_element\"><div class=\"static\"> $T_Hide $T_SH_closeservice </div></div></a>"
					;;
				esac
				;;

			*)
				case "$ServerMenuEnabled" in
				*closeservice*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard closeservice show\" title=\"$T_Show $T_SH_closeservice\"><div class=\"menu_element\"><div class=\"static\"> $T_Show $T_SH_closeservice </div></div></a>"
					;;
				esac
				;;
			esac
			case "$SystemInfoMode" in
			show)
				case "$ServerMenuEnabled" in
				*monitor*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard monitor hide\" title=\"$T_Hide $T_SH_monitor\"><div class=\"menu_element\"><div class=\"static\"> $T_Hide $T_SH_monitor </div></div></a>"
					;;
				esac
				;;
			*)
				case "$ServerMenuEnabled" in
				*monitor*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard monitor show\" title=\"$T_Show $T_SH_monitor\"><div class=\"menu_element\"><div class=\"static\"> $T_Show $T_SH_monitor </div></div></a>"
					;;
				esac
				;;
			esac
			case "$MoocInfoMode" in
			show)
				case "$ServerMenuEnabled" in
				*mooc*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard mooc hide\" title=\"$T_Hide $T_SH_mooc\"><div class=\"menu_element\"><div class=\"static\"> $T_Hide $T_SH_mooc </div></div></a>"
					;;
				esac
				;;
			*)
				case "$ServerMenuEnabled" in
				*mooc*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard mooc show\" title=\"$T_Show $T_SH_mooc\"><div class=\"menu_element\"><div class=\"static\"> $T_Show $T_SH_mooc </div></div></a>"
					;;
				esac
				;;
			esac
			case "$ServiceDetailsMode" in
			show)
				case "$ServerMenuEnabled" in
				*services*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard services hide\" title=\"$T_Hide $T_SH_services\"><div class=\"menu_element\"><div class=\"static\"> $T_Hide $T_SH_services </div></div></a>"
					;;
				esac
				;;
			*)
				case "$ServerMenuEnabled" in
				*services*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard services show\" title=\"$T_Show $T_SH_services\"><div class=\"menu_element\"><div class=\"static\"> $T_Show $T_SH_services </div></div></a>"
					;;
				esac
				;;
			esac
			case "$ServerLogMode" in
			show)
				case "$ServerMenuEnabled" in
				*log*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard log hide\" title=\"$T_Hide $T_SH_log\"><div class=\"menu_element\"><div class=\"static\"> $T_Hide $T_SH_log </div></div></a>"
					;;
				esac
				;;
			*)
				case "$ServerMenuEnabled" in
				*log*)
					SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard log show\" title=\"$T_Show $T_SH_log\"><div class=\"menu_element\"><div class=\"static\"> $T_Show $T_SH_log </div></div></a>"
					;;
				esac
				;;
			esac
			SiteMenu="$SiteMenu
</div>
<div class=\"dashboard_title\">$T_Service_list_title</div>
<div class=\"menu\">
$ServicesMenu"	
			;;
		hide)
			case "$ServerMenuEnabled" in
			*options*)
				SiteMenu="$SiteMenu
<a href=\"../index.php?action=--on_click dashboard_menu dashboard goe --dashboard options show\" title=\"$T_SH_More\"><div class=\"menu_element\"><div class=\"static\"> $T_SH_More </div></div></a>"
				;;
			esac
			SiteMenu="$SiteMenu
</div>
<div class=\"dashboard_title\">$T_Service_list_title</div>
<div class=\"menu\">
$ServicesMenu"
			;;
		esac
		;;
	guest|Guest)
		SiteMenu="<div class=\"menu\">"
		;;
	*)
		SiteMenu="
<div class=\"menu\">"
		case "$ServerMenuEnabled" in
		*help*)
			SiteMenu="$SiteMenu
<a target=\"_blank\" href=\"$PanelHelp\"><div class=\"menu_element\"><div class=\"static\"> $T_Help </div></div></a>"
			;;
		esac
		case "$ServerMenuEnabled" in
		*support*)
			SiteMenu="$SiteMenu
<a target=\"_blank\" href=\"$PanelSupport\"><div class=\"menu_element\"><div class=\"static\"> $T_Support </div></div></a>"
			;;
		esac
		;;
	esac
	echo "$SiteMenu"
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--config_mode)
	echo "$ServerMode"
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--version)
	case "$BlablaVersion" in
	-noblabla)
		echo "<!-- goe version is $ThisScriptVersion -->"
		;;
	*)
		echo "<!-- goe version is $GoeVersion -->"
		;;
	esac
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--clean)
	CHECK_BUZY $LINENO
	rm -f $ActivityFile
	rm -rf $Drawings
	rm -rf $Actions
	rm -rf $Forms
	rm -rf $Results
	rm -rf $GoeData
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
esac

#------------------------------------------------------------------------------
SHAPE_XML_FILE ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO -g  SHAPE_XML_FILE $*

#SHAPE_XML_FILE [comment] -XmlOption XmlZone [XmlFile]
xmlparamaters="$*"
case "$1" in
-*)
	;;
*)
	sxf_comment="$1"
	shift
	;;
esac
XmlOption="$1"
shift
case "$1" in
*/*|./*)
	XmlFile="$1"
	XmlZone="$2"
	;;
*)
	XmlFile="$2"
	XmlZone="$1"
	;;
esac
if [ ! -z "$XmlFile" ] ; then
	case "$XmlOption" in
	-new_page)
		echo "<!-- This file $XmlOption $XmlFile generated for $XmlZone by $0 on $Date mode $ServerMode parameters $sxf_comment -->
	<zone name=\"$XmlZone\">" > $XmlFile
		#echo "Draw $XmlOption $XmlFile for $XmlZone on $Date mode $ServerMode parameters $sxf_comment-$LINENO" >> $DrawingsLog
		
		;;
	-end_page)
		echo " <!-- end \"$XmlZone\" --> </zone>" >> $XmlFile
		;;
	-continue)
		;;
	-init)
		echo "<!-- This file $XmlOption $XmlFile generated for $XmlZone by $0 on $Date mode $ServerMode parameters $sxf_comment -->" > $XmlFile
		#echo "Draw $XmlOption $XmlFile for $XmlZone on $Date mode $ServerMode parameters $sxf_comment-$LINENO" >> $DrawingsLog
		;;
	*)
		LOG_MESSAGE $LINENO -g error $xmlparamaters
		;;
	esac
else
	case "$XmlOption" in
	-new_page)
		echo "<!-- This content $XmlOption online evaluated for $XmlZone on the fly by $0 on $Date mode $ServerMode parameters $sxf_comment -->
	<zone name=\"$XmlZone\">"
		#echo "On the fly $XmlOption evaluated for $XmlZone on $Date mode $ServerMode parameters $sxf_comment-$LINENO" >> $DrawingsLog

		;;
	-end_page)
		echo " <!-- end \"$XmlZone\" --> </zone>"
		;;
	-continue)
		;;
	-init)
		echo "<!-- This content $XmlOption online evaluated for $XmlZone on the fly by $0 on $Date mode $ServerMode parameters $sxf_comment -->"
		#echo "On the fly $XmlOption evaluated for $XmlZone on $Date mode $ServerMode parameters $sxf_comment-$LINENO" >> $DrawingsLog
		;;
	*)
		LOG_MESSAGE $LINENO -g error $xmlparamaters
		;;
	esac
fi
}
#end 
#------------------------------------------------------------------------------

case "$Option" in
#------------------------------------------------------------------------------
--init)
Drawings="$GoeDir/draw"
Actions="$GoeDir/action"
Forms="$GoeDir/form"
Results="$GoeDir/result"
GoeData="$GoeDir/data"
	for context in $Drawings $Actions $Forms $Results $GoeData ; do
		rm -rf $context
	done
	$0 --get_service_data
	$0 --collect
	$0 --template
	$0 --draw
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--login)
	GET_XOE_DATA
	AuthorizedRole="denied"
	if [ ! -z "$UserPassword" ] ; then

		if echo "$UserLogins" | grep "^$UserName $UserPassword " > /dev/null 2>&1 ; then
			AuthorizedRole=`echo "$UserLogins" | grep "^$UserName $UserPassword " | tail -n 1 | cut -d" " -f3`
		else
			# check UserName and UserPassword are accepted, if yes print UserRole, else return denied
			GET_XOE_DATA $LINENO-login $UserName
			case "$UserName:$UserPassword" in
			$XoeLoginUser:$XoeLoginPassword)
				AuthorizedRole="$XoeLoginRole"
				;;
			guest:*)
				;;
			esac
		fi

	fi
	LOG_MESSAGE $LINENO -g check_login $UserName $UserPassword $AuthorizedRole
	echo -n "$AuthorizedRole"
	;;
#------------------------------------------------------------------------------
--login_list)
	GET_XOE_DATA
	echo "<data>"
	for login_service in $ServiceList ; do
		GET_XOE_DATA $LINENO-login_list $login_service
		if [ ! -z $XoeLoginUser ] && [ ! -z $XoeLoginPassword ] &&  [ ! -z $XoeLoginRole ] ; then
			echo "    <user><login>$XoeLoginUser</login><pass>$XoeLoginPassword</pass><role>$XoeLoginRole</role></user>"
		fi
	done
	# adding configured authorized users
	old_IFS=$IFS
	IFS=$'\n'
	for ligne in $UserLogins ; do
		IFS=$old_IFS
		user_name=`echo "$ligne" | cut -d" " -f1`
		user_password=`echo "$ligne" | cut -d" " -f2`
		user_role=`echo "$ligne" | cut -d" " -f3`
		if [ ! -z $user_name ] && [ ! -z $user_password ] &&  [ ! -z $user_role ] ; then
			echo "    <user><login>$user_name</login><pass>$user_password</pass><role>$user_role</role></user>"
		fi
		IFS=$'\n'
	done
	IFS=$old_IFS
	echo "</data>"
	;;
#------------------------------------------------------------------------------
--draw*)
#------------------------------------------------------------------------------
. $0.draw
	PageTop="<![CDATA[$BackToTopImage]]>"
	PageBack1="<![CDATA[<hr/>$BackImage]]>"
	PageBack2="<![CDATA[$BackImage<hr/>]]>"

#------------------------------------------------------------------------------
#last segment of --draw* command
#------------------------------------------------------------------------------
	case "$Option" in
	#------------------------------------------------------------------------------
	--draw)
	#------------------------------------------------------------------------------
		LOG_MESSAGE $LINENO -g execution --draw to draw zone.page page.draw -----------begin
		DrawingCurrentDirectory="$Drawings.draft"
		if [ -d "$DrawingCurrentDirectory" ] ; then  rm -rf $DrawingCurrentDirectory ; fi
		mkdir -p $DrawingCurrentDirectory
		chmod 770 $DrawingCurrentDirectory
		echo "Start drawing batch $Option on `date +'%Hh%Mm%Ss:%3N'`" >> $DrawingsLog
		if [ ! -f $Drawings/default.detail.draw ] ; then
			DRAW_DETAIL draw_$LINENO -init -default default.detail $DrawingCurrentDirectory/default.detail.draw
		fi
		DisplayedPages=`tail -n $PageRefresh $GoePagesList | sort -u | xargs`
		if [ -f $SiteRefreshModeFile ] ; then
			RefreshMode=`cat $SiteRefreshModeFile`
		fi
		LOG_MESSAGE $LINENO -g execution --draw, refresh mode is $RefreshMode, recently displayed pages are $DisplayedPages
		DRAW_MAIN_PAGE
		CHECK_XML $DrawingCurrentDirectory
		chmod 770 $DrawingCurrentDirectory/*
		#LOG_MESSAGE $LINENO -g execution --draw `ls $DrawingCurrentDirectory`
		$Sudo chown $XoeAuthorizedUser:$HttpUser $DrawingCurrentDirectory
		CHECK_BUZY $LINENO set
		#mv $Drawings $Drawings.removed
		mv $DrawingCurrentDirectory/* $Drawings
		CHECK_BUZY $LINENO release
		LOG_MESSAGE $LINENO -g execution --draw fresh page contents have been updated --------------end

		echo "End drawing batch $Option on `date +'%Hh%Mm%Ss:%3N'`" >> $DrawingsLog
		#rm -rf $Drawings.removed
		#echo ".... `date +'%Hh%Mm%Ss:%3N'`" >> $GoeDir/goe.draw.log
		;;
	#------------------------------------------------------------------------------
	--draw_default)
	#------------------------------------------------------------------------------

		LOG_MESSAGE $LINENO -g execution --draw_default to draw zone.page page.draw default page content -----------begin
		DrawingCurrentDirectory="$Drawings.draft"
		if [ -d "$DrawingCurrentDirectory" ] ; then  rm -rf $DrawingCurrentDirectory ; fi
		mkdir -p $DrawingCurrentDirectory
		echo "Start Default drawing batch $Option on `date +'%Hh%Mm%Ss:%3N'`" >> $DrawingsLog
		DRAW_DEFAULT -init -default $DrawingCurrentDirectory/page.draw
		chmod -R 770 $DrawingCurrentDirectory
		LOG_MESSAGE $LINENO -g execution --draw_default `ls -lhR $DrawingCurrentDirectory`
		$Sudo chown $XoeAuthorizedUser:$HttpUser $DrawingCurrentDirectory
		CHECK_BUZY $LINENO set
		#mv $Drawings $Drawings.removed
		mv $DrawingCurrentDirectory/* $Drawings
		CHECK_BUZY $LINENO release
		LOG_MESSAGE $LINENO -g -execution -draw_default no activity default page content has been set --------------end
		#rm -rf $Drawings.removed
		echo "End Default drawing batch $Option on `date +'%Hh%Mm%Ss:%3N'`" >> $DrawingsLog
		;;
	#------------------------------------------------------------------------------
	--draw_now)
	#------------------------------------------------------------------------------
		LOG_MESSAGE $LINENO -g execution --draw_now draw on the fly a missing page with zone $ZoneName and drawing $Drawing -----------begin
		#echo -n "draw_now    `date +'%Hh%Mm%Ss:%3N'` ...." >> $GoeDir/goe.draw.log
		echo "Start drawing on demand $Option $Drawing on `date +'%Hh%Mm%Ss:%3N'`" >> $DrawingsLog
		DrawingCurrentDirectory="$Drawings"
		if [ -f $SiteRefreshModeFile ] ; then
			RefreshMode="Now"
		fi
		DRAWING_TO_SERVICE $Drawing
		LOG_MESSAGE $LINENO -g execution --draw_now Service $Service Database $Database to calculate $Drawing
		case "$Drawing" in
		log_detail.draw)
			#draw global log
			DRAW_DETAIL draw_now_$LINENO -init -general_log general_log
			;;
		*.log_detail.draw|*.instructions_detail.draw|*.configuration_detail.draw)
			#draw service log
			GET_DATA $LINENO service $Service
			DRAW_DETAIL draw_now -init -log zone.log
			DRAW_DETAIL draw_now -init -instructions zone.instructions
			DRAW_DETAIL draw_now -init -lastactions zone.lastactions
			DRAW_DETAIL draw_now -init -anomalies zone.anomalies
			DRAW_DETAIL draw_now -init -configuration zone.configuration
			LANGUAGE $LINENO $Language
			;;
		*detail.draw)
			if [ ! -z "$Database" ] ; then
				LOG_MESSAGE $LINENO -g execution --draw_now draw page Database $Database
				GET_DATA $LINENO service $Service
				GET_DATA $LINENO database $Service $Database
				DRAW_DETAIL draw_now_$LINENO -init -database_menu $Service.$Database.menu $DrawingCurrentDirectory/$Service.$Database.menu.draw
				DRAW_DETAIL draw_now_$LINENO -init -database $Service.$Database.info $DrawingCurrentDirectory/$Service.$Database.info.draw
				cat $DrawingCurrentDirectory/$Service.$Database.menu.draw > $DrawingCurrentDirectory/$Service.$Database.detail.draw
				cat $DrawingCurrentDirectory/$Service.$Database.info.draw >> $DrawingCurrentDirectory/$Service.$Database.detail.draw
				cat $DrawingCurrentDirectory/$Service.$Database.menu.draw
				cat $DrawingCurrentDirectory/$Service.$Database.info.draw
				LANGUAGE $LINENO $Language
			else
				if [ ! -z "$Service" ] ; then
					LOG_MESSAGE $LINENO -g execution --draw_now draw page Service $Service FILL_SERVICE_MENU
					GET_DATA $LINENO service  $Service
					DRAW_DETAIL draw_now_$LINENO -init -service_menu $Service.menu $DrawingCurrentDirectory/$Service.menu.draw
					DRAW_DETAIL draw_now_$LINENO -init -service $Service.info $DrawingCurrentDirectory/$Service.info.draw
					cat $DrawingCurrentDirectory/$Service.menu.draw > $DrawingCurrentDirectory/$Service.detail.draw
					cat $DrawingCurrentDirectory/$Service.info.draw >> $DrawingCurrentDirectory/$Service.detail.draw
					cat $DrawingCurrentDirectory/$Service.menu.draw
					cat $DrawingCurrentDirectory/$Service.info.draw
					LANGUAGE $LINENO $Language
				else
					if [ -f $DrawingCurrentDirectory/default.detail.draw ] ; then
						cat $DrawingCurrentDirectory/default.detail.draw
						LOG_MESSAGE $LINENO -g execution --draw_now "looking for default page $DrawingCurrentDirectory/$DrawingName, serving $DrawingCurrentDirectory/default.detail.draw instead"
					else
						LOG_MESSAGE $LINENO 404 exit "looking for missing $DrawingCurrentDirectory/$DrawingName, and no default page is available"
					fi
				fi
			fi
			;;
		page.draw|log_detail.draw|admin_guide.draw|contract.draw|open_service.draw|close_service.draw)
			#draw all services map
			LOG_MESSAGE $LINENO -g execution --draw_now zone.page page.draw
			DRAW_MAIN_PAGE_NOW
			$Sudo chown $XoeAuthorizedUser:$HttpUser $DrawingCurrentDirectory/$Service.draw
			cat $DrawingCurrentDirectory/page.draw
			;;
		*.draw)
			#draw service map
			LOG_MESSAGE $LINENO -g execution --draw_now zone.$Service $Service.draw
			DRAW_MAIN_PAGE_NOW $Service
			$Sudo chown $XoeAuthorizedUser:$HttpUser $DrawingCurrentDirectory/$Service.draw
			cat $DrawingCurrentDirectory/$Service.draw
			;;
		*)
			LOG_MESSAGE $LINENO -g execution --draw_now unexpected case $Zonename $Drawing
			;;
		esac
		LOG_MESSAGE $LINENO -g execution --draw_now  missing page has been drawn with zone $ZoneName and drawing $Drawing --------------end
		#echo ".... `date +'%Hh%Mm%Ss:%3N'`" >> $GoeDir/goe.draw.log
		echo "End drawing on demand $Option on `date +'%Hh%Mm%Ss:%3N'`" >> $DrawingsLog
		;;
	esac
	;;

#------------------------------------------------------------------------------
--collect)
#------------------------------------------------------------------------------
. $0.collect
	LOG_MESSAGE $LINENO -g "execution collect $* data for all services"
	echo -n "collect `date +'%Hh%Mm%Ss:%3N'` ...." >> $GoeDataLog
	LOG_MESSAGE $LINENO "New data to be collected -----------begin"
	/usr/local/bin/xoe --config -list -data > $XoeServicesData
	/usr/local/bin/xoe --config -list -service
	for dataset in contract admin_guide openservice closeservice system mooc general_log  page  service menu database ; do
		COLLECT_DATA $LINENO $dataset
	done	
	LOG_MESSAGE $LINENO "Last data collected -----------end"
	echo ".... `date +'%Hh%Mm%Ss:%3N'`" >> $GoeDataLog
	;;
#------------------------------------------------------------------------------
--template)
. $0.buttons
#------------------------------------------------------------------------------
#last segment of --template command


	echo -n "New templates for actions, forms and results on `date +'%Hh%Mm%Ss:%3N'`...." >> $GoeTemplatesLog
	if [ -e "$Actions.draft" ] ; then rm -rf $Actions.draft ; fi
	mkdir -p $Actions.draft
	chmod 750 $Actions.draft
	echo "Last actions on $Date" >> $GoeActionsLog
	if [ -e "$Forms.draft" ] ; then rm -rf $Forms.draft ; fi
	mkdir -p $Forms.draft
	chmod 750 $Forms.draft
	echo "Last forms on $Date" >> $GoeFormsLog
	if [ -e "$Results.draft" ] ; then rm -rf $Results.draft ; fi
	mkdir -p $Results.draft
	chmod 750 $Results.draft
	echo "Last results on $Date" >> $GoeResultsLog
	GET_DATA $LINENO page
	XoeDirConf=`cat $XoeDir/xoe.conf/xoe.services.conf | grep "^directory:server:"`

	ActionServiceList="button_editservicemenu button_renew button_start button_stop button_restart button_newcase button_company button_drop button_newmooc button_managemooc button_exam button_upload button_installarchive button_upgrade"
# button_downgrade"
	ButtonFormServiceList="button_editservicemenu button_newcase button_company button_drop button_newmooc button_managemooc button_exam button_upload button_installarchive button_upgrade"
#  button_downgrade"
	ButtonResultServiceList="$ActionServiceList"
	ActionDatabaseList="button_editdatabasemenu button_save button_snapshot button_restore button_clone button_copy button_reference button_delete button_wipe_out button_dbupdate"
	ButtonFormDatabaseList="button_editdatabasemenu button_restore button_clone button_copy button_reference button_delete button_wipe_out button_dbupdate"
	ButtonResultDatabaseList="$ActionDatabaseList"
	ActionList="$ActionServiceList $ActionDatabaseList"
	ButtonFormList="$ButtonFormServiceList $ButtonFormDatabaseList"
	ButtonResultList="$ButtonResultServiceList $ButtonResultDatabaseList"
	CHECK_BUZY $LINENO set
	for action in $ActionList ; do
		TEMPLATE_ACTION $action
	done
	for template in $ButtonFormList ; do
		TEMPLATE_BUTTON_FORM $template ${template}.form
	done
	for template in $ButtonResultList ; do
		TEMPLATE_BUTTON_RESULT $template ${template}.result
	done
	CHECK_BUZY $LINENO set
	for template in  $Actions $Forms $Results ; do
		chmod 750 $template.draft/*
		$Sudo chown -R $XoeAuthorizedUser:$HttpUser $template.draft
		mv $template $template.removed
		mv $template.draft $template
	done
	CHECK_BUZY $LINENO release
	LOG_MESSAGE $LINENO -g --template buttons forms, results and actions have been updated
	rm -rf $Actions.removed
	rm -rf $Forms.removed
	rm -rf $Results.removed
	echo "....`date +'%Hh%Mm%Ss:%3N'`" >> $GoeTemplatesLog
	;;
#------------------------------------------------------------------------------
--get_service_data)
#------------------------------------------------------------------------------
	/usr/local/bin/xoe --config -list -data > $XoeServicesData
	/usr/local/bin/xoe --config -list -service
	;;
#------------------------------------------------------------------------------
--background)
#------------------------------------------------------------------------------
	LOG_MESSAGE $LINENO -g "--backgroung Process activation"
	runningprocesses=`ps axo cmd`
	if echo "$runningprocesses" | grep 'goe' | grep -q 'loop' ; then
		LOG_MESSAGE $LINENO -g "--backgroung Process loop is running, consider --loop_stop for a graceful stop"
		echo "Process loop is running, consider --loop_stop for a graceful stop"
		EXIT $LINENO 0
	else
		if [ ! -f $GoeLoopingFlag ] ; then
			#rm -rf $GoeDir
			CHECK_ACCESS_RIGHTS
			echo "goe background task started at `date`" > $GoeLoopingFlag
		fi
		#rm -f $ActivityFile
		nohup $0 --loop 2>$GoeLog &
		LOG_MESSAGE $LINENO -g "Loop is started --loop, use $0 --loop_stop for a graceful stop"
		echo "Loop is started --loop, use $0 --loop_stop for a graceful stop"
	fi
	;;
#------------------------------------------------------------------------------
--loop)
#------------------------------------------------------------------------------

#------------------------------------------------------------------------------
MOOC_EXECUTE ()
#------------------------------------------------------------------------------
{
LOG_MESSAGE $LINENO -g mooc execute mode $ServerMode
if [ -f /usr/local/bin/mooc ] ; then
	/usr/local/bin/mooc --background
fi
}
#end 
#------------------------------------------------------------------------------
LOOP_PARAMETERS ()
#------------------------------------------------------------------------------
{
#echo "backgd  `date +'%Hh%Mm%Ss:%3N'` $NumberTimes" >> $GoeDir/goe.draw.log
if [ -z "$NumberTimes" ] ; then
	NumberTimes="Auto"
fi
rating="is not evaluated"
case "$ServerMode" in
idemdemo*)
	xTimes="0"
	;;
*)
	case "$NumberTimes" in
	x*)
		xTimes=`echo "$NumberTimes" | cut -b2-`
		;;	
	esac
	if [ ! -z "$Period" ] ; then
		Pace="$Period"
	fi
	case "-$xTimes-$Pace-$NumberTimes-" in
	*-Auto*|*-auto*)
		nbdb=`psql -l 2>/dev/null | grep -m 1 "rows" | cut -d"(" -f2 | cut -d" " -f1`
		nb_databases=`echo "$nbdb - 3" | bc`
		GET_XOE_DATA
		rating=`echo "$ServiceNumber * 10 + $nb_databases" | bc`
		echo "$rating" > $GoeRatingFile
		echo "NO" > $GoeOnDemandFile
		if [ $rating -le 30 ] ; then
			xTimes="5"
			Pace="15"
			echo "15" > $SiteRefreshPeriodFile
			echo "All" > $SiteRefreshModeFile
		else
			if [ $rating -le 36 ] ; then
				xTimes="5"
				Pace="15"
				echo "15" > $SiteRefreshPeriodFile
				echo "All" > $SiteRefreshModeFile
			else
				#echo "YES" > $GoeOnDemandFile
				if [ $rating -le 128 ] ; then
					xTimes="5"
					Pace="30"
					echo "20" > $SiteRefreshPeriodFile
					echo "$RefreshMode" > $SiteRefreshModeFile
				else
					if [ $rating -le 256 ] ; then
						xTimes="5"
						Pace="30"
						echo "20" > $SiteRefreshPeriodFile
						echo "Displayed" > $SiteRefreshModeFile
					else
						if [ $rating -le 384 ] ; then
							xTimes="5"
							Pace="30"
							echo "20" > $SiteRefreshPeriodFile
							echo "Displayed" > $SiteRefreshModeFile
						else
							if [ $rating -le 640 ] ; then
								xTimes="5"
								Pace="40"
								echo "20" > $SiteRefreshPeriodFile
								echo "Displayed" > $SiteRefreshModeFile
							else
								if [ $rating -le 1024 ] ; then
									xTimes="5"
									Pace="50"
									echo "20" > $SiteRefreshPeriodFile
									echo "Displayed" > $SiteRefreshModeFile
								else
									xTimes="5"
									Pace="60"
									echo "30" > $SiteRefreshPeriodFile
									echo "Displayed" > $SiteRefreshModeFile
								fi
							fi
						fi
					fi
				fi
			fi
		fi
		;;
	esac
	;;
esac
echo "$Pace" > $GoePaceTimeFile
#TR T_There_is There is : Il y a
#TR T_There_are There are : Il y a
#TR T_database_over database over : base de donnees sur
#TR T_databases_over databases over : bases de donnees sur
#TR T_service service : service
#TR T_services services : services
#TR T_Delay Delay to next evaluation : Prochain calcul apres
#TR T_Disk_size_eval Disk is evaluated once a day : Le disque est evalue 1 fois par jour
case "$nb_databases"-"$ServiceNumber" in
0-0|0-1|1-0|1-1)
	echo "$T_Disk_size_eval. $T_There_is $nb_databases $T_database_over $ServiceNumber $T_service" > $SiteRefreshCommentFile
	;;
0-*|1-*)
	echo "$T_Disk_size_eval. $T_There_is $nb_databases $T_database_over $ServiceNumber $T_services" > $SiteRefreshCommentFile
	;;
*-0|*-1)
	echo "$T_Disk_size_eval. $T_There_is $nb_databases $T_databases_over $ServiceNumber $T_service" > $SiteRefreshCommentFile
	;;
*)
	echo "$T_Disk_size_eval. $T_There_are $nb_databases $T_databases_over $ServiceNumber $T_services" > $SiteRefreshCommentFile
	;;
esac
LOG_MESSAGE $LINENO -g "LOOP_PARAMETERS rating: $rating, $xTimes x refresh, $Pace s naptime, `cat $SiteRefreshPeriodFile` s display period, refresh mode is `cat $SiteRefreshModeFile`"
}
#end
#------------------------------------------------------------------------------
LOOP_STATUS ()
#------------------------------------------------------------------------------
{
loop_status="$*"
if [ -z "$loop_status" ] ; then
	cat $GoeLoopStatusFile
else
	case `cat $GoeLoopStatusFile` in
	$loop_status)
		LOG_MESSAGE $LINENO -g looping LOOP_STATUS UNCHANGED $loop_status pace $Pace loop $iloop/$xTimes $SinceLoop
		;;
	*)
		echo "$loop_status" > $GoeLoopStatusFile
		LOG_MESSAGE $LINENO -g looping NEW LOOP_STATUS $loop_status pace $Pace loop $iloop/$xTimes $SinceLoop
		;;
	esac
fi
}
#------------------------------------------------------------------------------
LOOP ()
#------------------------------------------------------------------------------
{
#in crontab /usr/loca/bin/goe --bakground x10 6
	if [ ! -e "$ActivityFile" ] ; then
		echo -n "1234567890abcdef" > $ActivityFile
	fi
	some_time=`echo "$Pace - 5" | bc`
	MOOC_EXECUTE
	for (( iloop=1; iloop<=$xTimes; iloop++ )) ; do
		LastTime=`cat $ActivityFile | wc -c`
		SinceLoop="since `echo "$LastTime * $Pace" | bc`s"
		if [ $LastTime -le 12 ] ; then			
			case `LOOP_STATUS` in
			Napping)
				LOOP_STATUS Awakening
				#$0 --collect
				echo -n "*" >> $ActivityFile
				;;
			esac
			case "$iloop" in
			1)
				LOOP_STATUS On duty
				OnDemand=`cat $GoeOnDemandFile`
				case "$OnDemand" in
				YES)
					;;
				*)
					$0 --draw
					LOG_MESSAGE $LINENO -g collect data and redraw $iloop/$xTimes
					;;
				esac
				echo -n ";" >> $ActivityFile
				;;
			*)
				if [ $LastTime -le 6 ] ; then
					LOOP_STATUS Hard worker
					case "$OnDemand" in
					YES)
						;;
					*)
						$0 --draw
						LOG_MESSAGE $LINENO -g collect data and redraw $iloop/$xTimes
						;;
					esac
					echo -n ":" >> $ActivityFile
				else
					LOOP_STATUS Lazy
					echo -n "," >> $ActivityFile
				fi
				;;
			esac
		else
			LOOP_STATUS Napping
			echo -n "." >> $ActivityFile
			echo "Napping" >> $GoePagesList
		fi
		sleep $Pace
	done
}
#------------------------------------------------------------------------------
#--loop
	LOG_MESSAGE $LINENO -g "LOOP_STATUS Starting execution loop forever, use $0 --loop_stop for a graceful stop"
	echo "$$" > $GoePidFile
	chmod 600 $GoePidFile
	date > $GoeLoopStartFile
	$0 --clean
	$0 --get_service_data
	LOOP_PARAMETERS
	$0 --template
	$0 --collect
	while [ ! -f  $LoopStopFlag ] ; do
		if [ -f "$GoeLogMode" ] ; then . $GoeLogMode ; fi
		LOOP
		sleep 5
	done
	$Sudo rm -f $LoopStopFlag
	rm -f $GoePidFile
	LOG_MESSAGE $LINENO -g "LOOP_STATUS Execution loop is stopped, use $0 --background to restart this loop"
	;;
#------------------------------------------------------------------------------
--loop_status)
#------------------------------------------------------------------------------
	runningprocesses=`ps axo cmd`
	#echo "$runningprocesses"
	if echo "$runningprocesses" | grep 'goe' | grep -q ' --loop$' ; then
		echo "Loop status:		loop is looping"
		echo "Loop started on 	`cat $GoeLoopStartFile`"
		echo "Draw On Demand		`cat $GoeOnDemandFile`"
		echo "Refresh Comment		`cat $SiteRefreshCommentFile`"
		echo "Rating			`cat $GoeRatingFile`"
		echo "At work	 		`cat $GoeLoopStatusFile`"
		echo "Refresh Period		`cat $SiteRefreshPeriodFile`s"
		echo "Refresh Mode		`cat $SiteRefreshModeFile`"
		PaceTime=`cat $GoePaceTimeFile`
		echo "Pace Time		$PaceTime s"
		SinceLastActivity=`cat $ActivityFile | wc -c`
		UnusedFor=`echo "$SinceLastActivity * $PaceTime" | bc`
		echo "Last Activity		$UnusedFor s"
		echo "Activity Record		`cat $ActivityFile`"
	else
		echo "Loop status: no loop is looping"
	fi
	if [ -f $LoopStopFlag ] ; then
		echo "A request for stopping loop has been filed"
	fi
	;;
#------------------------------------------------------------------------------
--loop_stop)
#------------------------------------------------------------------------------
	WORKINGPROCESS=`/bin/ps axo pid,cmd | grep "$0"`
	if echo "$WORKINGPROCESS" | grep -q "loop$" 2>/dev/null ; then 
		echo "Process loop is invited to stop"
		$Sudo echo "please stop looping" >  $LoopStopFlag
		$Sudo chmod 777 $LoopStopFlag
	else
		echo "Process loop is already stopped"
		$Sudo rm -f  $LoopStopFlag
	fi
	;;
#------------------------------------------------------------------------------
--history_forget)
#------------------------------------------------------------------------------
	Resize="$1"
	if [ -z "$Resize" ] ; then
		Resize="$PageKeep"
	fi
	if [ ! -e $GoePagesList ] || [ -w $GoePagesList ] ; then
		echo "$DrawingName" >> $GoePagesList
		recentpages=`tail -n $Resize $GoePagesList`
		echo "$recentpages" > $GoePagesList
	fi
	;;
#------------------------------------------------------------------------------
--new_login)
#------------------------------------------------------------------------------
	case `whoami` in
	root)
		case "$ServerMode" in
		*)
			if [ -z "$UserName" ] ; then
				echo -n "New login : "
				read UserName
			fi
			if echo "$UserLogins" | grep -qm 1 "^$UserName " ; then
				LOG_MESSAGE $LINENO -e $UserName is already declared in configuration
			else
				if [ -z "$UserPassword" ] ; then
					echo -n "New password : "
					read UserPassword
				fi
				if [ -z "$UserRole" ] ; then
					echo -n "New role : "
					read UserRole
				fi
				echo "UserLogins=\"$UserLogins
$UserName $UserPassword $UserRole\"" > $GoeLoginConf
				echo "Login $UserName is added to $GoeLoginConf"
			fi
			;;
		esac
		;;
	*)
		echo "You must be root or use sudo to setup a new login"
		;;
	esac
	;;

#------------------------------------------------------------------------------
--config)
#------------------------------------------------------------------------------
	cd /usr/local
	if [ ! -e etc/goe ] ; then
		mkdir -p etc/goe
	fi
	echo "This is current configuration of goe in $GoeConf : "
	cat $0 2>/dev/null | grep -m 1 -B 200 "^##EndConfig" | grep -A 200 "^##StartConfig"
	if [ ! -f "$GoeLocalConf" ] ; then
		echo "# This is current local configuration of goe in $GoeLocalConf : " > $GoeLocalConf
		echo "# Last Update : `stat -c %z $GoeLocalConf | cut -d"." -f1`" >> $GoeLocalConf
	fi
	echo "#------------------------------------------------------------------------------"
	cat $GoeLocalConf
	chmod 755 $GoeLocalConf
	if [ -f $GoeModeConf ] ; then
		echo "#------------------------------------------------------------------------------"
		echo "# This is current mode configuration of goe in $GoeModeConf"
		cat $GoeModeConf
	fi
	if [ -f $GoeConfDir/goe.local.conf.save ] ; then
		echo "#------------------------------------------------------------------------------"
		echo "# Local configuration of goe is also saved in $GoeConfDir/goe.local.conf.save"
	fi
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--config_save)
#------------------------------------------------------------------------------
	if [ ! -f $GoeLocalConf ] ; then
		echo "#Local configuration of goe"	> $GoeLocalConf
	fi
	cp -a $GoeLocalConf $GoeConfDir/goe.local.conf.save
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--dashboard)
#------------------------------------------------------------------------------	
#toggle parameters options|contract|admin_guide|monitor|mooc|services|log show|hide
#list help support options contract monitor mooc services log
#	echo "$LINENO `date` `whoami` $DashboardOption parameters $0 --dashboard $OptionParameters" >> /tmp/goe.dashboard.service.log 2>&1
				TOGGLE ()
				{
				tog_file="$1"
				shift
				tog_line="$*"
				before_content=`cat $tog_file | grep -v "^$tog_line"`
				echo "$before_content" > $tog_file
				echo "$tog_line" >> $tog_file
				}
	case `whoami` in
	root)
		case "$DashboardValue" in
		show|hide)
			;;
		*)
			DashboardValue="show"
			;;
		esac
		if [ -z "$DashboardList" ] ; then
			DashboardList="help support options admin_guide contract monitor mooc services log"
		fi
		case "$DashboardOption" in
		list)
			TOGGLE $GoeLocalConf "ServerMenuEnabled=\"$DashboardList\""
			TOGGLE $GoeLocalConf "ServerMenuMode=\"hide\""
			;;
		options)
			TOGGLE $GoeLocalConf "ServerMenuMode=\"$DashboardValue\""
			;;
		admin_guide)
			TOGGLE $GoeLocalConf "AdminGuideMode=\"$DashboardValue\""
			;;
		contract)
			TOGGLE $GoeLocalConf "ServerContractMode=\"$DashboardValue\""
			;;
		openservice)
			TOGGLE $GoeLocalConf "OpenServiceMode=\"$DashboardValue\""
			;;
		closeservice)
			TOGGLE $GoeLocalConf "CloseServiceMode=\"$DashboardValue\""
			;;
		monitor)
			TOGGLE $GoeLocalConf "SystemInfoMode=\"$DashboardValue\""
			;;
		mooc)
			TOGGLE $GoeLocalConf "MoocInfoMode=\"$DashboardValue\""
			;;
		services)
			TOGGLE $GoeLocalConf "ServiceDetailsMode=\"$DashboardValue\""
			;;
		log)
			TOGGLE $GoeLocalConf "ServerLogMode=\"$DashboardValue\""
			;;
		newservice)
			nohup /usr/local/bin/xoe --contract -service_full_set $DashboardNewService > /dev/null 2>&1 &
			echo "$LINENO `date` `whoami` /usr/local/bin/xoe --contract -service_full_set $DashboardNewService" >> /tmp/goe.dashboard.service.log
			;;
		cancelservice)
			nohup /usr/local/bin/xoe --contract -cancel -save $DashboardCloseService >> /dev/null 2>&1 &
			echo "$LINENO `date` `whoami` sudo /usr/local/bin/xoe --contract -cancel -save $DashboardCloseService" >> /tmp/goe.dashboard.service.log
			;;
		esac
		;;
	*)
		echo "$LINENO `date` `whoami` You must be root" >> /tmp/goe.dashboard.service.log 2>&1
		;;
	esac
	;;
#------------------------------------------------------------------------------
--log)
#------------------------------------------------------------------------------
	$0 --set_log on
	if [ -z "$SearchString" ] ; then
		cat -n $GoeLogFile
	else
		cat -n $GoeLogFile | grep -i "$SearchString"
	fi
	;;
#------------------------------------------------------------------------------
--live)
#------------------------------------------------------------------------------
	$0 --set_log on
	if [ -z "$SearchString" ] ; then
		tail -f $GoeLogFile
	else
		tail -f $GoeLogFile | grep -i "$SearchString"
	fi
	;;
#------------------------------------------------------------------------------
--message)

	LOG_MESSAGE $LINENO -g $OptionParameters

	;;
#------------------------------------------------------------------------------
--mode)
#------------------------------------------------------------------------------
#echo "New mode $NewMode"
	case "$NewMode" in
	demo|business|education)
		;;
	*)
		echo "Current mode is $ServerMode"
		echo "New mode $NewMode should be in demo|business|education"
		EXIT $LINENO 1
		;;
	esac
	case `whoami` in
	root)
		case "$NewMode" in
		$ServerMode)
			;;
		demo|education)
			echo "
ServerMode=\"$NewMode\""  > $GoeModeConf
			/usr/local/bin/mooc --mode on
			;;
		*|business)
			#echo "mode is written to $GoeModeConf"
			echo "
ServerMode=\"$NewMode\""  > $GoeModeConf
			/usr/local/bin/mooc --mode off
			;;
		esac
		echo "this new setting is kept in $GoeModeConf"
		;;
	esac
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--set_authorized_user)
#------------------------------------------------------------------------------
	if [ -z "$SetAuthorizedUser" ] ; then
		echo -n  "ERP authorized user :  "
		read SetAuthorizedUser
	fi
	case `whoami` in
	root)
		case "$SetAuthorizedUser" in
		$XoeAuthorizedUser)
			;;
		*)
			if [ ! -f $GoeLocalConf ] ; then
				echo "#Local configuration of goe"	> $GoeLocalConf
			fi
			echo "XoeAuthorizedUser=\"$SetAuthorizedUser\""  >> $GoeLocalConf
			echo "this new setting is kept in $GoeLocalConf"
			;;
		esac
		;;
	esac
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--set_log)
#------------------------------------------------------------------------------
	case "$NewMode" in
	on)
		case "$GoeLog" in
		$GoeLogFile)
			;;
		*)
			echo "GoeLog=\"$GoeLogFile\""  > $GoeLogMode
			echo "Log mode is set to on" >> $GoeLogFile
			;;
		esac
		;;
	off)
		case "$GoeLog" in
		/dev/null)
			;;
		*)
			echo "GoeLog=\"/dev/null\""  > $GoeLogMode
			echo "Log mode is set to off" >> $GoeLogFile
			;;
		esac
		;;
	*)
		echo "Log file is $GoeLog"
		echo "Log setting is kept in $GoeLogMode"
		;;
	esac


	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--shell)
#------------------------------------------------------------------------------
	LOG_MESSAGE $LINENO -g execute as `whoami` shell command $ShellCommand
	$ShellCommand
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--shell_move)
#------------------------------------------------------------------------------
	LOG_MESSAGE $LINENO -g move uploaded files as `whoami` from/to $ShellCommand
	origin=`echo "$ShellCommand" | cut -d" " -f1`
	destination=`echo "$ShellCommand" | cut -d" " -f2`
	if [ ! -z "$origin" ] && [ ! -z "$destination" ] ; then
		rm -f $origin/*' '*
		mv $origin/* $destination
	else
		LOG_MESSAGE $LINENO -g move uploaded files as `whoami` from/to are mandatory
	fi
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--install_panel)
#------------------------------------------------------------------------------
	case `whoami` in
	root)

#-------------------------------------------------------------------------
PHP_CAPABILITY ()
#-------------------------------------------------------------------------
{
	if cat /etc/issue | grep -q "10.04\|11.04\|12.04\|14.04\|16.04\|Debian GNU/Linux 7" ; then
		echo "5"
	else
		echo "7"
	fi
}
#end 
#-------------------------------------------------------------------------
INSTALL_PHP_CAPABILITY ()
#-------------------------------------------------------------------------
{
	iphpc_version=`PHP_CAPABILITY`
	apt-get install fontconfig xfonts-75dpi xfonts-base xfonts-encodings xfonts-utils
	case "$iphpc_version" in
	5)
		if ! apt-get install php5 ; then
			echo "Failure during php5 installation."
		fi
		;;
	7)
		if apt-get install php ; then
			
			PHP_UPLOAD_MAX
		else
			echo "Failure during PHP7 installation."
		fi
		;;
	esac
	if ! apt-get install php-xml* ; then
		echo "Failure during PHP-XML installation."
	fi
	LOG_MESSAGE $LINENO -g PHP installed version is $iphpc_version
}
#end 
#-------------------------------------------------------------------------
		if ! apt-get install apache2 ; then
			echo "Failure during Apache2 installation."
		fi
		INSTALL_PHP_CAPABILITY
		goe_location="/`cat /etc/apache2/sites-enabled/*default* | grep DocumentRoot | cut -d/ -f2-`"
		if [ ! -e "$goe_location" ] ; then
			echo "cannot find Apache2 DocumentRoot for $Option option, not done"
			EXIT $LINENO 1
		fi
		if [ -f $goe_location/index.html ] ; then
			mv $goe_location/index.html $goe_location/.index.html.dist
		fi
		# create apache virtualhost
		$0 --update_panel
		su $XoeAuthorizedUser -c '/usr/local/bin/goe --init'

#bug lacommande crontab ne marche pas
		if ! cat /var/spool/cron/crontabs/$XoeAuthorizedUser | grep -q "/usr/local/bin/goe" ; then
			echo "
* * * * *   /usr/local/bin/goe  --background  > /dev/null 2>&1" >> /var/spool/cron/crontabs/$XoeAuthorizedUser
		fi
		# Corriger les droits d'acces
		chmod 600 /var/spool/cron/crontabs/$XoeAuthorizedUser
		chown $XoeAuthorizedUser /var/spool/cron/crontabs/$XoeAuthorizedUser
		chgrp crontab /var/spool/cron/crontabs/$XoeAuthorizedUser
		if [ -f $goe_location/robots.txt ] ; then
			mv $goe_location/robots.txt $goe_location/.robots.txt.dist
		fi
		RobotFileName="$goe_location/robots.txt"
		echo "User-agent: *
Disallow: /" > $RobotFileName
		# add $HttpUser to sudoers
		# ??
		if ! cat /etc/sudoers | grep -q "$HttpUser ALL = NOPASSWD: /usr/local/bin/goe" ; then
			echo "$HttpUser ALL = NOPASSWD: /usr/local/bin/goe" >> /etc/sudoers
		fi
		if ! cat /etc/sudoers | grep -q "$HttpUser ALL = NOPASSWD: /usr/local/bin/xoe" ; then
			echo "$HttpUser ALL = NOPASSWD: /usr/local/bin/xoe" >> /etc/sudoers
		fi
		/etc/init.d/apache2 restart
		$0 --update_mooc
		;;
	*)
		echo "you must be root or sudo to succeed with $Option option"
		;;
	esac
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--update)
#-------------------------------------------------------------------------
UPDATER ()
#-------------------------------------------------------------------------
{
goe_segment="$1"
if [ -z "$goe_segment" ] ; then
	segment=""
else
	segment=".$goe_segment"
fi
rm -f $0$segment.new_version

if wget -q http://$download_source/goe$segment -O $0$segment.new_version ; then
	diff $0$segment $0$segment.new_version
	mv $0$segment rescue.goe$segment
	mv $0$segment.new_version $0$segment
	chmod 755 $0$segment
	LOG_MESSAGE $LINENO Downloaded goe$segment
else
	LOG_MESSAGE $LINENO Failed to download goe$segment
	rm -f $0$segment.new_version
fi
}
#------------------------------------------------------------------------------
	case `whoami` in
	root)
		LOG_MESSAGE $LINENO -g goe $Option Nouvelle version $*
		cd /usr/local/bin
		script_source="$0"
		panel_source=""
		css_source=""
		if [ ! -z "$CodeAltSource" ] ; then
			case "$CodeAltSource" in
			*,*,*)
				download_source=`echo "$CodeAltSource" | cut -d"," -f1`
				panel_source=`echo "$CodeAltSource" | cut -d"," -f2`
				css_source=`echo "$CodeAltSource" | cut -d"," -f3`
				;;
			*,*)
				download_source=`echo "$CodeAltSource" | cut -d"," -f1`
				panel_source=`echo "$CodeAltSource" | cut -d"," -f2`
				;;
			*)
				download_source="$CodeAltSource"
				;;
			esac
		else
			download_source="$GoeDownloadSource"
		fi
		OLDVERSION=`$0 --version -noblabla`
		
		UPDATER
		for goe_tool in buttons collect draw ; do
			UPDATER $goe_tool
		done

		rm -f $GoeTranslationFile.*
		NEWVERSION=`$0 --version -noblabla`
		case "$NEWVERSION" in
		$OLDVERSION)
			echo "$0 is uptodate `$0 --version`"
			;;
		*)
			echo "$0 downloaded new version from $download_source $NEWVERSION"
			;;
		esac
		$0 --update_mooc
		$0 --update_panel $panel_source $css_source
		$0 --loop_stop
		;;
	*)
		echo "$0 you must be root or sudo to succeed with $Option option"
		;;
	esac
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--update_mooc)
#------------------------------------------------------------------------------
	case `whoami` in
	root)
		LOG_MESSAGE $LINENO -g goe $Option Nouvelle version $*
		cd /usr/local/bin
		download_source="$MoocDownloadSource"
		script_source="mooc"
		if [ ! -f $script_source ] ; then
			if wget -q $download_source -O $script_source.new_version ; then
				diff $script_source $script_source.new_version
				mv $script_source.new_version $script_source
				chmod 755 $script_source
				#first activation checks permissions and configuration
				/usr/local/bin/mooc --version
			else
				echo "could not download $script_source software from $download_source"
			fi
		else
			chmod 755 $script_source
			/usr/local/bin/mooc --update
		fi
		;;
	*)
		echo "you must be root or sudo to succeed with $Option option"
		;;
	esac
	EXIT $LINENO 0
	;;
#------------------------------------------------------------------------------
--update_panel)
#------------------------------------------------------------------------------
	case `whoami` in
	root)
		LOG_MESSAGE $LINENO -g goe $Option Nouvelle version $CodeAltSource
		goe_location="/`cat /etc/apache2/sites-enabled/*default* | grep DocumentRoot | cut -d/ -f2-`"
		if [ ! -e "$goe_location" ] ; then
			echo "cannot find Apache2 DocumentRoot for $Option option, not done"
			EXIT $LINENO 1
		fi
		cd $goe_location
		panel_source="$PanelDownloadSource"
		css_source="$CssDownloadSource"
		if [ ! -z "$CodeAltSource" ] ; then
			case "$CodeAltSource" in
			*,*)
				panel_source=`echo "$CodeAltSource" | cut -d"," -f1`
				css_source=`echo "$CodeAltSource" | cut -d"," -f2`
				;;
			*)
				panel_source="$CodeAltSource"
				;;
			esac
		fi
		if wget -q $panel_source -O $SiteScriptName.new_version ; then
			if [ -f "$SiteScriptName" ] ; then
				diff $SiteScriptName $SiteScriptName.new_version
				mv $SiteScriptName rescue.`basename $SiteScriptName`
			fi
			mv $SiteScriptName.new_version $SiteScriptName
			chown $HttpUser $SiteScriptName
			echo "goe panel is up-to-date"
		else
			echo "Could not update panel software from $PanelDownloadSource"
		fi
		if wget -q $css_source -O $SiteCss.new_version ; then
			if [ -f "$SiteCss" ] ; then
				diff $SiteCss $SiteCss.new_version
				mv $SiteCss rescue.$SiteCss
			fi
			mv $SiteCss.new_version $SiteCss
			chown $HttpUser $SiteCss
			echo "goe panel css is up-to-date"
		else
			echo "Could not update css file from $css_source"
		fi
		rm -rf $SiteImages
		if ! wget -q -r -np -nH -nd -R index.html $ImageSource -P $SiteImages ; then
			echo "Could not update images from $ImageSource"
		fi
		echo "<?php
// php code generated by $0 version $ThisScriptVersion
function bytesToSize1024(\$bytes, \$precision = 2) {
    \$unit = array('B','KB','MB');
    return @round(\$bytes / pow(1024, (\$i = floor(log(\$bytes, 1024)))), \$precision).' '.\$unit[\$i];
}
if (isset(\$_POST['service']))
{
	\$serviceName = \$_POST['service'];
}
\$errorCode = \$_FILES['archive_upload']['error'];
\$fileName = \$_FILES['archive_upload']['name'];
\$fileType = \$_FILES['archive_upload']['type'];
\$fileExtension = pathinfo(\$fileName, PATHINFO_EXTENSION);
\$fileBytes = \$_FILES['archive_upload']['size'];
\$fileSize = bytesToSize1024(\$_FILES['archive_upload']['size'], 1);
\$fileTemp = \$_FILES['archive_upload']['tmp_name'];
\$targetFile = \"$GoeUploads/\$serviceName/\$fileName\";
\$dirService = \"$GoeUploads/\$serviceName\";
\$acceptedExtensions = ['tar.gz','zip'];
//echo \"<p>Your file: \".\$fileName.\" has been successfully received.</p>\";
echo \"<p>Type: \".\$fileType.\"</p>\";
echo \"<p>Size: \".\$fileSize.\"</p>\";
//echo \"<p>file: \".\$fileTemp.\"</p>\";
echo \"<p>copy: \".\$targetFile.\"</p>\";
if(\$errorCode === 1)
{
	echo \"<p>Fichier trop gros, refuse. File is too large, rejected.</p>\";
}
elseif(\$error_Code === 2)
{
	echo \"<p>File error code 2</p>\";
	exit;
}
elseif(\$error_Code === 3)
{
	echo \"<p>File error code 3</p>\";
	exit;
}
elseif(\$error_Code === 4)
{
	echo \"<p>Le fichier est vide -File is empty</p>\";
	exit;
}
elseif(\$fileBytes > $MaxArchiveUploadSize)
{
	echo \"<p>Le fichier est trop gros.The file is too big. Max : $MaxArchiveUploadSize.</p>\";
	exit;
}
elseif(!in_array(\$fileExtension,\$acceptedExtensions))
{
	echo \"<p>Les archives acceptees sont au formats .tar.gz ou .zip, sans espace dans le nom. Accepted archives are .tar.gz or .zip file, no space in name.</p>\";
	exit;
}
if (!is_dir(\$dirService))
	mkdir(\$dirService, 0777);
\$is_uploaded = move_uploaded_file(\$fileTemp, \$targetFile);
if(\$is_uploaded)
{
	echo \"<p>Le fichier \".\$fileName.\" peut etre ajoute a la bibliotheque specifique du service. File \".\$fileName.\" uploaded successfully to specific library of service</p>\";
}
else
{
	echo \"<p>File not uploaded.</p>\";
}
?>
"	> upload.php.new_version
		if [ -f upload.php ] ; then
			diff upload.php upload.php.new_version
			rm upload.php
		fi
		mv upload.php.new_version upload.php
		echo "goe upload.php is up-to-date"
		PHP_UPLOAD_MAX
		if ! cat /etc/sudoers | grep -q "$HttpUser ALL = NOPASSWD: /usr/local/bin/goe" ; then
			echo "$HttpUser ALL = NOPASSWD: /usr/local/bin/goe" >> /etc/sudoers
		fi
		if ! cat /etc/sudoers | grep -q "$HttpUser ALL = NOPASSWD: /usr/local/bin/xoe" ; then
			echo "$HttpUser ALL = NOPASSWD: /usr/local/bin/xoe" >> /etc/sudoers
		fi
		if ! cat /etc/sudoers | grep -q "$HttpUser ALL = NOPASSWD: /usr/local/bin/mooc" ; then
			echo "$HttpUser ALL = NOPASSWD: /usr/local/bin/mooc" >> /etc/sudoers
		fi
		;;
	*)
		echo "you must be root or sudo to succeed with $Option option"
		;;
	esac
	EXIT $LINENO 0
	;;

#------------------------------------------------------------------------------
--css)
#------------------------------------------------------------------------------
	cd $GoeDir
	wget -q $CssDownloadSource -O $GoeDir/copy_of_goe.css
	echo "/* generated by $0 on $Date */"
	cat $GoeDir/copy_of_goe.css
	echo "/* generated by $0 on $Date */"
	;;
#------------------------------------------------------------------------------
--css_check)
#------------------------------------------------------------------------------
	CssContent=`$0 --css`
	PositionList=`cat $0 | grep -v "PositionList=" | grep "<zone_position>" | cut -d">" -f2 | cut -d"<" -f1 | sort -u | xargs`
	echo "List of positions : $PositionList"
	for position in $PositionList ; do
		if ! echo "$CssContent" | grep -q "\.$position" ; then
			echo "Missing css class .$position"
		fi
	done
	StatusList="fault ok unknown warning"
	echo "List of status values : $StatusList"
	for status in $StatusList ; do
		if ! echo "$CssContent" | grep -q "\.$status" ; then
			echo "Missing css class .$status"
		fi
	done
	TypeList=`cat $0 | grep -v "TypeList=" | grep "<zone_type>" | cut -d">" -f2 | cut -d"<" -f1 | sort -u | xargs`
	echo "List of zone types : $TypeList"
	for type in $TypeList ; do
		if ! echo "$CssContent" | grep -q "\.$type" ; then
			echo "Missing css class .$type"
		fi
		for status in $StatusList ; do
			if ! echo "$CssContent" | grep "\.$type" | grep -q "\.$status" ; then
				echo "Defaulted css class .$type .$status"
			fi
		done
	done
	;;
#------------------------------------------------------------------------------
--help)
#------------------------------------------------------------------------------
	echo "goe : application de gestion des services openerp
syntaxe :
goe [login [language]] --command [parameters]
-- are optionnal when login and language are indicated

Command :
--help

--background			#create a loop forever
--collect
--config
--config_denied_message
--config_head_css
--config_head_title
--config_head_refresh
--config_login_form
--config_mode
--config_page_header
--config_page_footer
--config_page_menu
--config_save
--config_welcome_message
--css_check
--css
--dashboard	options|contract|monitor|mooc|services|log [show]|hide
--dashboard	list help support options contract monitor mooc services log
--draw
--draw_now	zone_name drawing_name
--get_service_data
--history_forget	[nb_pages]
--init
--install_panel
--licence
--live		[search_string]
--log		[search_string]
--login		username password # check user is authorized and return user role
--login_list
--loop				#used by --background
--loop_status
--loop_stop			#set an indicator to stop gracefully a --loop at next iteration
--message	message text
--mode		demo|business|education
--move_uploaded	upload_dir custom_dir
--new_login	user_name user_password service_name|admin
--on_click	zone_name new_drawing_name action [action_parameters]
--on_duty
--page		zone_name drawing_name
--refresh	zone_name drawing_name
--set_authorized_user xoe_administration_username
--set_log	on|off


--shell		shell_command_and_parameters
--shell_move	origin_dir destination_dir
--template
--update	[http://alternative_goe_code_source_url [http://alternative_panel_code_source_url]]
--update_panel
--version [-noblabla]

language= fr|en


Configuration adaptation is located in $GoeLocalConf and saved to $GoeConfDir/goe.local.conf.save

--install_panel
--update
--update_mooc
--update_panel


output file format :
<zone name=\"zone_name\" />
	<markup>data</markup>
</zone>
markup is one of
zone name	introduces a nested zone, name is mandatory
these markups relate to the zone they are declared in
zone_doc_over	specifies information showed when mouse is over an active element
zone_form	html form code
zone_html	html content to be added in the page
zone_label	short text of a button
zone_menu	html code of an element added to a gobal menu zone
zone_on_click	action executed in case of click on the zone area
zone_on_validate	action executed when a form is validated

these markups are used to invoke css styles for the content of the zone and are applied in this order :
zone_position	example zcenter, zright, zleft...
zone_type	example service_name, service_running, database...
zone_status	typically ok, fault, warning and unknown

these are used to set up global setting wherever the declaration is :
zone_refresh	superceedes any previous page refreshment instruction
zone_title	superceedes any previous title set for the current window
zone_window	specifies a name of the pop up window
"
$0 --version
	;;
#------------------------------------------------------------------------------
--licence)
#------------------------------------------------------------------------------
	echo "This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Credits
2012-today: goe is an original work from SISalp, http://sisalp.fr"
	;;
#------------------------------------------------------------------------------
--)
#------------------------------------------------------------------------------
	$0 --help | less
	;;

#------------------------------------------------------------------------------
*)
#------------------------------------------------------------------------------
	echo "503 Option $Option is not supported by goe command"
	;;
esac
EXIT $LINENO 0


