#! /bin/bash
#------------------------------------------------------------------------------
#see licence at the end
#soe is a commercial application which delivers odoo and Tryton services
#soe runs on front-end behind web page and spools requests
#soe also runs on the back-end and executes commands to fullfil requests.
SoeVersion="1.0 - 27 may 2024 rev 4 Last Update : `stat -c %z $0 | cut -d"." -f1`"
Date=`date +"%d/%m/%y-%H:%M:%S"`
CurrentUser=`whoami`
AllParameters="$*"

#------------------------------------------------------------------------------
#StartConfig
#------------------------------------------------------------------------------
#Adapt following values to your context
#
#SoeMode : see --help"
#SoeMode="remote"
SoeMode="test"
SoeSiteMode="maintenance"

#Other parameters you may look for :
#
#soe background tasks parameters
#-------------------------------
SoeDir="/usr/local/etc/soe"
SoeConfig="$SoeDir/soe.conf"
SoeSpool="$SoeDir/soe_spool"
SoeData="$SoeDir/soe_data"
SoeCodes="$SoeData/codes.data"
SoeServices="$SoeData/services.data"
SoeAdminCodes="$SoeData/admin.data"
SoeLogFile="$SoeDir/soe.log"
SoeReport="$SoeDir/soe.report"
SoeModeFile="$SoeDir/soe.mode"
SoeStatus="$SoeDir/soe.status"
SoeLastDelivery="$SoeDir/soe.last_delivery"
SoeSiteModeFile="$SoeDir/soe_site.mode"
SoeDefaultLanguage="fr"
#------------------------------------------------------------------------------
#EndConfig
#------------------------------------------------------------------------------
if [ -f $SoeModeFile ] ; then
	SoeMode=`cat $SoeModeFile`
fi
if [ -f $SoeSiteModeFile ] ; then
	SoeSiteMode=`cat $SoeSiteModeFile | cut -f1`
fi
Pace=`cat $SoeConfig | grep "^Pace:" | cut -f2`
#------------------------------------------------------------------------------
#Fonctions
#------------------------------------------------------------------------------
LOG_MESSAGE ()
#------------------------------------------------------------------------------
{
case "$1" in
-short)
	shift
	if [ ! -f /tmp/soe.log.return ] ; then
		echo ".=new iteration, :=loop is active, C=shop is closed, W=hoe is running and delivery is delayed" >> $SoeLogFile
		echo "return" > /tmp/soe.log.return
		chmod 777 /tmp/soe.log.return
	fi
	echo -n "$*" >> $SoeLogFile
	;;
*)
	if [ -f /tmp/soe.log.return ] ; then
		rm /tmp/soe.log.return
		echo "" >> $SoeLogFile
	fi
	echo "$HOSTNAME|soe|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$*" >> $SoeLogFile
	;;
esac
}
#------------------------------------------------------------------------------
SITE_CONFIG ()
#------------------------------------------------------------------------------
{
SiteConfig="$1"
if [ -d "$SoeDir/$SiteConfig" ] ; then
	SoeCatalogue="$SoeDir/$SiteConfig/soe.catalogue"
	SoePublicAddress="$SoeDir/$SiteConfig/soe.public_address"
else
	exit 1
fi
}

#-------------------------------------------------------------------------
NEW_PASSWORD ()
#-------------------------------------------------------------------------
{
if [ -f /usr/local/bin/PW ] ; then
	NEW_PWD=`/usr/local/bin/PW $*`
else
	if [ -z "$1" ] ; then
		pw_nb_digits=12
	else
		pw_nb_digits="$*"
	fi
	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 )
	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
fi
echo "${NEW_PWD}"
}
#------------------------------------------------------------------------------
NEW_USER_CODE ()
#------------------------------------------------------------------------------
{
	personnalkey=`NEW_PASSWORD 2 3`
	echo "code_$personnalkey"
	echo "$1	code_$personnalkey	$Language	$Date" >> $SoeCodes
}
#------------------------------------------------------------------------------
GET_CODE ()
#------------------------------------------------------------------------------
{
	if cat $SoeCodes | grep -iq "^$1" ; then
		cat $SoeCodes | grep -i "^$1" | tail -n 1 | cut -f2
	else
		NEW_USER_CODE $1
	fi
}
#------------------------------------------------------------------------------
GET_LANGUAGE ()
#------------------------------------------------------------------------------
{
	GetLanguage=`cat $SoeCodes | grep -i "^$1" | tail -n 1 | cut -f3`
	case "$GetLanguage" in
	fr|en)
		echo "$GetLanguage"
		;;
	*)
		echo "$SoeDefaultLanguage"
		;;
	esac
}
#------------------------------------------------------------------------------
COLLECT_SPOOL ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO "COLLECT_SPOOL $*"
#Read Spool List
SpoolList=`cat $SoeConfig | grep "^spool_server:" | cut -d: -f2 | xargs`
#echo "SpoolList=$SpoolList"
cd $SoeSpool
for spool in $SpoolList ; do
	#echo "spool=$spool"
	SpoolServer=`cat $SoeConfig | grep "^spool_server:$spool:" | cut -f2`
	SpoolHost=`cat $SoeConfig | grep "^spool_server:$spool:" | cut -f3`
	SpoolPort=`cat $SoeConfig | grep "^spool_server:$spool:" | cut -f4`
	SpoolPath=`cat $SoeConfig | grep "^spool_server:$spool:" | cut -f5`
	#echo "commande: ssh -p $SpoolPort $SpoolHost 'ls $SpoolPath'"
	if ssh -p $SpoolPort $SpoolHost ls $SpoolPath > /tmp/soe.spool.list 2>/tmp/soe.spool.log ; then
		ActionList=`cat /tmp/soe.spool.list`
		#echo "ActionList=$ActionList"
		if [ ! -z "$ActionList" ] ; then
			LOG_MESSAGE $LINENO "COLLECT_SPOOL Synchronization is done, actions are copied from $SpoolServer"
		fi
		for action in $ActionList ; do
			#echo "commande: scp -P $SpoolPort $SpoolHost:$SpoolPath/$action ."
			if scp -P $SpoolPort $SpoolHost:$SpoolPath/$action . >> /tmp/soe.spool.log 2>&1 ; then
				#echo "commande: ssh -p $SpoolPort $SpoolHost rm $SpoolPath/$action"
				ssh -p $SpoolPort $SpoolHost rm $SpoolPath/$action >> /tmp/soe.spool.log 2>&1
			else
				LOG_MESSAGE $LINENO "COLLECT_SPOOL Synchronization failed on $spool $SpoolServer SpoolPath/$action"
				SEND_MAIL -error en Synchronization failed on $spool $SpoolServer SpoolPath/$action
			fi
		done
		rm -f /tmp/soe.spool.list
	else
		LOG_MESSAGE $LINENO "COLLECT_SPOOL Synchronization failed on $spool $SpoolServer: ssh -p $SpoolPort $SpoolHost ls $SpoolPath"
	fi
done
}
#------------------------------------------------------------------------------
RETURN_STATUS ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO "RETURN_STATUS $*"
status_level="$1"
case "$SoeMode" in
remote)
	status_level="$1"
	case "$status_level" in
	closed)
		Color="#cc6633"
		Border="#aa4411"
		ShopMessages=`cat $SoeSiteModeFile | cut -f2-`
		ShopMessageFr=`echo "$ShopMessages" | cut -d: -f1`
		ShopMessageEn=`echo "$ShopMessages" | cut -d: -f2`
		Status="<span style=\"padding:5px 20px; margin: 5px; background-color: $Color; border:solid 1px $Border; color: #eeeeee; \">$ShopMessageFr&nbsp;-&nbsp;<i>$ShopMessageEn</i> <small>`date +"%H:%M"`</small></span><br/><br/>"
		;;
	ok)
		Color="#336633"
		Border="#003300"
		FrDelay="10mn"
		EnDelay="10mn"
		Status="<span style=\"padding:5px 20px; margin: 5px; background-color: $Color; border:solid 1px $Border; color: #eeeeee; \">Dernier livré: `cat $SoeLastDelivery` Délai: $FrDelay&nbsp;-&nbsp;<i>Last delivery: `cat $SoeLastDelivery` Lead time: $EnDelay</i> <small>`date +"%H:%M"`</small></span><br/><br/>"
		;;
	lag)
		Color="#cc6633"
		Border="#aa4411"
		FrDelay="1h"
		EnDelay="1h"
		Status="<span style=\"padding:5px 20px; margin: 5px; background-color: $Color; border:solid 1px $Border; color: #eeeeee; \">Dernier livré: `cat $SoeLastDelivery` Délai: $FrDelay&nbsp;-&nbsp;<i>Last delivery: `cat $SoeLastDelivery` Lead time: $EnDelay</i> <small>`date +"%H:%M"`</small></span><br/><br/>"
		;;
	delayed)
		Color="#7e0021"
		Border="#4e0011"
		FrDelay="Indéterminé"
		EnDelay="Unknown"
		Status="<span style=\"padding:5px 20px; margin: 5px; background-color: $Color; border:solid 1px $Border; color: #eeeeee; \">Dernier livré: `cat $SoeLastDelivery` Délai: $FrDelay&nbsp;-&nbsp;<i>Last delivery: `cat $SoeLastDelivery` Lead time: $EnDelay</i> <small>`date +"%H:%M"`</small></span><br/><br/>"
		;;
	esac
	$0 --status $Status
	#Read Spool List
	SpoolList=`cat $SoeConfig | grep "^spool_server:" | cut -d: -f2 | xargs`
	#echo "SpoolList=$SpoolList"
	cd $SoeSpool
	for spool in $SpoolList ; do
		#echo "spool=$spool"
		SpoolServer=`cat $SoeConfig | grep "^spool_server:$spool:" | cut -f2`
		SpoolHost=`cat $SoeConfig | grep "^spool_server:$spool:" | cut -f3`
		SpoolPort=`cat $SoeConfig | grep "^spool_server:$spool:" | cut -f4`
		SpoolPath=`cat $SoeConfig | grep "^spool_server:$spool:" | cut -f5`
		if ! scp -P $SpoolPort $SoeStatus $SpoolHost:$SoeStatus ; then
			LOG_MESSAGE $LINENO "RETURN_STATUS failed on $spool $SpoolServer $SpoolHost:$SoeStatus"
			SEND_MAIL -error en RETURN_STATUS failed on $spool $SpoolServer $SpoolHost:$SoeStatus
		fi
	done
	;;
esac
}
#------------------------------------------------------------------------------
LOOP_FOREVER ()
#------------------------------------------------------------------------------
{
	LOG_MESSAGE $LINENO "Starting execution loop forever, use $0 --stop to break this loop"
	while [ ! -f /tmp/soe.loop_control.status ] ; do
		LOG_MESSAGE -short "."
		$0 --execute
		sleep $Pace
	done
	LOG_MESSAGE $LINENO "Execution loop is stopped, use /usr/local/bin/soe --start to let --background create this loop next time"
}
#------------------------------------------------------------------------------
SHOP_OPEN_ONLY ()
#------------------------------------------------------------------------------
{
if [ -f "$SoeSiteModeFile" ] ; then
	ShopStatus=`cat $SoeSiteModeFile | cut -f1`
	case "$ShopStatus" in
	closed)
		LOG_MESSAGE -short "C"
		RETURN_STATUS closed
		exit 0
		;;
	esac
fi
WorkingProcesses=`ps axo pid,cmd`
if echo "$WorkingProcesses" | grep -q "/usr/local/bin/hoe" ; then
#while echo "$WorkingProcesses" | grep -v "/usr/local/bin/hoe --live" | grep -q "/usr/local/bin/hoe" ; do
#	LOG_MESSAGE $LINENO "SHOP_OPEN_ONLY hoe process is running"
	LOG_MESSAGE -short "W"
	RETURN_STATUS lag
	exit 0
fi
RETURN_STATUS ok
}
#------------------------------------------------------------------------------
NOT_LOOPING_ONLY ()
#------------------------------------------------------------------------------
{
	runningprocesses=`/bin/ps axo pid,cmd`
	if echo "$runningprocesses" | grep "$0" | grep -q "loop_forever" ; then
		LOG_MESSAGE -short ":"
		exit 0
	fi
}
#------------------------------------------------------------------------------
STOP_LOOP ()
#------------------------------------------------------------------------------
{
	runningprocesses=`/bin/ps axo pid,cmd`
	if echo "$runningprocesses" | grep "$0" | grep -q "loop_forever" ; then
		LOG_MESSAGE $LINENO "Process loop is invited to stop"
	else
		LOG_MESSAGE $LINENO "Process loop is already stopped"
	fi
	echo "please stop looping" > /tmp/soe.loop_control.status
	RETURN_STATUS delayed
}
#------------------------------------------------------------------------------
UNSTOP_LOOP ()
#------------------------------------------------------------------------------
{
	rm -f /tmp/soe.loop_control.status
	LOG_MESSAGE $LINENO "Process loop can restart"
	RETURN_STATUS lag
}
#------------------------------------------------------------------------------
CORRECT_CODE_ONLY ()
#------------------------------------------------------------------------------
{
	#LOG_MESSAGE $LINENO  "CORRECT_CODE_ONLY $*"
	given_mail="$1"
	given_code="$2"
	if [ -z "$given_code" ] ; then
		RETURN_MESSAGE "Vous devez indiquer votre code personnel"
		exit 0
	fi
	registered_code=`cat $SoeCodes | grep -i "^$given_mail" | tail -n 1 | cut -f2`
	allowed_codes=`cat $SoeAdminCodes | grep "^allowed_code:" | cut -f2 | xargs | sed s/' '/':'/g`
	if [ -z "$allowed_codes" ] ; then
		allowed_codes=`NEW_PASSWORD 64 64`
	fi
	if [ -z "$registered_code" ] ; then
		RETURN_MESSAGE "Vous avez commis une erreur en indiquant votre mail ou votre code personnel. L'action demandée ne va pas être effectuée.<br /><i>You made a mistake on your mail or your personnal code. Your request won't be processed.</i>"
		LOG_MESSAGE $LINENO "Access denied $Mail $Code E-mail not found" 
		exit 0
	fi
	case ":$allowed_codes:" in
	*:$given_code:*)
		given_code="$registered_code"
		;;
	esac
	case "$registered_code" in
	revoked)
		RETURN_MESSAGE "Vous utilisez une adresse mail qui n'est plus autorisée. Contactez le support pour plus d'explications.<br /><i>This mail address has been banned. Please contact support for more.</i>"
		exit 1
		;;
	esac
	case "$given_code" in
	$registered_code)
		;;
	*)
		RETURN_MESSAGE "Vous avez commis une erreur en indiquant votre mail ou votre code personnel. L'action demandée ne va pas être effectuée.<br /><i>You made a mistake on your mail or your personnal code. Your request won't be processed.</i>"
		LOG_MESSAGE $LINENO "Access denied $given_mail $given_code Code is incorrect"
		exit 1
		;;
	esac
}
#------------------------------------------------------------------------------
REVOKE_MAIL ()
#------------------------------------------------------------------------------
{
	echo "$1	revoked	-	$Date" >> $SoeCodes	
}
#------------------------------------------------------------------------------
UNREVOKE_MAIL ()
#------------------------------------------------------------------------------
{
	# should be uninterruptible TODO
	unrevoked=`cat $SoeCodes | grep -v "^$1	revoked"`
	echo "$unrevoked" > $SoeCodes	
}
#------------------------------------------------------------------------------
ACTION ()
#------------------------------------------------------------------------------
{
ActionTemplate="#! /bin/bash
# created by $O on `date`
/usr/local/bin/soe --action $*
rm \$0
exit 0"
echo "$ActionTemplate" > $SoeSpool/action.${Code}$1.sh
chmod 777 $SoeSpool/action.${Code}$1.sh
LOG_MESSAGE $LINENO "action $* is waiting in spool"
}
#------------------------------------------------------------------------------
LOCAL_ACTION ()
#------------------------------------------------------------------------------
{
ActionTemplate="#! /bin/bash
/usr/local/bin/soe --action $*
rm \$0
exit 0"
echo "$ActionTemplate" > $SoeSpool.local/action.${Code}$1.sh
chmod 777 $SoeSpool.local/action.${Code}$1.sh
LOG_MESSAGE $LINENO "local action $1 $2 $3 is waiting in local spool"
}
#------------------------------------------------------------------------------
RETURN_MESSAGE ()
#------------------------------------------------------------------------------
{
echo "<br/>$*<br/>"
}
#------------------------------------------------------------------------------
SEND ()
#------------------------------------------------------------------------------
{
echo "$MessageText" > /tmp/soe.mail_content.$$.txt
/usr/local/bin/MAIL content:/tmp/soe.mail_content.$$.txt to:$ToMail subject:$MessageSubject
rm /tmp/soe.mail_content.$$.txt

#if [ -x /usr/local/bin/spool ] ; then
#	echo "$MessageText" > /tmp/soe.mail_content.$$.txt
#	#spool --push mail [content:pushed.txt] [to:addr@dom] [cc:toto@dom] [bcc:tata@dom] [from:addr@dom] [subject:text and text]
#	if [ ! -z "$BccMail" ] ; then
#		spool --push mail content:/tmp/soe.mail_content.$$.txt to:$ToMail from:$SenderMail subject:$MessageSubject
#	else
#		spool --push mail content:/tmp/soe.mail_content.$$.txt to:$ToMail bcc:$BccMail from:$SenderMail subject:$MessageSubject
#	fi
#	rm /tmp/soe.mail_content.$$.txt
#else
#	if [ -x /usr/bin/mail ] ; then
#		if [ ! -z "$BccMail" ] ; then
#			echo "$MessageText" | mail -a "From: $SenderMail" -b $BccMail -s "$MessageSubject" $ToMail
#		else
#			echo "$MessageText" | mail -a "From: $SenderMail" -s "$MessageSubject" $ToMail
#		fi
#	else
#		LOG_MESSAGE $LINENO "no mailing capability to send messages to user content:/tmp/soe.mail_content.$$.txt to:$ToMail bcc:$BccMail from:$SenderMail subject:$MessageSubject"
#	fi
#fi
}
#------------------------------------------------------------------------------
SEND_MAIL ()
#------------------------------------------------------------------------------
{
message_type="$1"
shift
message_language="$1"
shift
case "$message_type" in
-error)
	errortext="$*"
	SenderMail=`cat $SoeConfig | grep ^mail:sender: | cut -f2-`
	ToMail=`cat $SoeConfig | grep ^mail:admin: | cut -f2-`
	case "$SoeMode" in
	local|remote|suspend)
		ToMail="$Mail"
		BccMail=`cat $SoeConfig | grep ^mail:admin: | cut -f2-`
		MailFlag=""
		;;
	test|redirect)
		ToMail=`cat $SoeConfig | grep ^mail:test: | cut -f2-`
		MailFlag="- Redirected from $Mail"
		;;
	esac
	MessageSubject="[ERROR] soe $HOSTNAME $CurrentUser $errortext"
	MessageText=`tail -n 25 $SoeLogFile`
	SEND
	;;
-anomaly)
	errortext="$*"
	SenderMail=`cat $SoeConfig | grep ^mail:sender: | cut -f2-`
	case "$SoeMode" in
	local|remote|suspend)
		ToMail="$Mail"
		BccMail=`cat $SoeConfig | grep ^mail:admin: | cut -f2-`
		MailFlag=""
		;;
	test|redirect)
		ToMail=`cat $SoeConfig | grep ^mail:test: | cut -f2-`
		MailFlag="- Redirected from $Mail"
		;;
	esac
	case "$message_language" in
	fr)
		MessageSubject="[ERP en Self-Service par SISalp] Votre requete ne peut aboutir $MailFlag"
		MessageText="Bonjour,

Vous avez soumis une demande sur le serveur ERP en Self-Service de SISalp.

Cependant, le serveur a rejete votre demande pour la raison suivante :
$errortext

En cas de difficulté, merci de contacter serviceclient@sisalp.fr

Nous vous souhaitons pleine reussite dans vos activités.

"
		;;
	en)
		MessageSubject="[Help Yourself ERP by SISalp] Your request could not succeed $MailFlag"
		MessageText="Hello,

You made a request on SISalp's Help Yourself ERP server.

Unfortunatly, our server rejected your request for the following reason :
$errortext

In case of difficulty, please contact service.client@sisalp.fr

We wish you full success in your activities.

"
		;;
	esac
	SEND
	;;
-template)
	templatename="$1"
	SenderMail=`cat $SoeConfig | grep ^mail:sender: | cut -f2-`
	case "$SoeMode" in
	local|remote|suspend)
		ToMail="$Mail"
		BccMail=`cat $SoeConfig | grep ^mail:admin: | cut -f2-`
		MailFlag=""
		;;
	test|redirect)
		ToMail=`cat $SoeConfig | grep ^mail:test: | cut -f2-`
		MailFlag="- Redirected from $Mail"
		;;
	esac
	mooc_url="mooc url $MoocServer"
	login_url="$ServiceUrl/web/login?db=$ServiceName"
	case "$templatename" in
	send_code)
		case "$message_language" in
		fr)
			MessageSubject="[ERP en Self-Service par SISalp] Votre code personnel $MailFlag"
			MessageText="Bonjour,

Vous avez soumis une demande de code personnel sur le serveur ERP en Self-Service de SISalp. Ce code personnel vous a ete attribue.

Votre adresse mail utilisee pour votre identification : $Mail
Votre code personnel : $Code

Ce code va vous permettre de creer votre service ERP en ligne.

En cas de difficulté, merci de contacter service.client@sisalp.fr

Nous vous souhaitons pleine reussite dans vos activites.

"
			;;
		en)
			MessageSubject="[Help Yourself ERP by SISalp] Your personnal code $MailFlag"
			MessageText="Hello,

You made a request on SISalp's Help Yourself ERP server for a personnal code. This personnal code has been declared

Your mail address : $Mail
Your personnal code : $Code

This code will allow you to create your on-line ERP service.

In case of difficulty, please contact service.client@sisalp.fr

We wish you full success in your activities.

"
			;;
		esac
		;;
	revoke)
		case "$message_language" in
		fr)
			MessageSubject="[ERP en Self-Service par SISalp] Revocation de votre adresse mail $MailFlag"
			MessageText="Bonjour,

Vous avez soumis une demande de bannissement d'une adresse mail sur le serveur ERP en Self-Service de SISalp.

L'adresse mail suivante ne sera plus jamais utilisee : $Mail

Si cette adresse mail a ete utilisee sans votre consentement, nous vous prions de nous excuser pour la gene occasionnee.
Si vous recevez encore des messages de notre part, merci de contacter service.client@sisalp.fr

Cordialement

"
			;;
		en)
			MessageSubject="[Help Yourself ERP by SISalp] Your mail address is now revoked $MailFlag"
			MessageText="Hello,

You made a request on SISalp's Help Yourself ERP server for banning your e-mail address used without your consentment. This address will never be used.

Your mail address : $Mail

In case of difficulty, please contact service.client@sisalp.fr

We wish you full success in your activities.

"
			;;
		esac
		;;
	unrevoke)
		case "$message_language" in
		fr)
			MessageSubject="[ERP en Self-Service par SISalp] Revalidation de votre adresse mail $MailFlag"
			MessageText="Bonjour,

Vous avez soumis une demande de revalidation d'une adresse mail dont vous aviez demande le bannissement sur le serveur ERP en Self-Service de SISalp.

Il semble que cette demande de bannissement etait due a une erreur ou a ete effectuee a votre insu. Elle a ete revalidee.

L'adresse mail suivante peut de nouveau etre utilisee : $Mail

Cordialement

"
			;;
		en)
			MessageSubject="[Help Yourself ERP by SISalp] Your mail address is now revalidated $MailFlag"
			MessageText="Hello,

You made a request on SISalp's Help Yourself ERP server for revalidating your e-mail address banned by error. This address now revalidated.

Your mail address : $Mail

In case of difficulty, please contact service.client@sisalp.fr

We wish you full success in your activities.

"
			;;
		esac
		;;
	service_ids)
		case "$message_language" in
		fr)
			MessageSubject="[ERP en Self-Service par SISalp] Creation de votre ERP en ligne $MailFlag"
			MessageText="Bonjour,

Vous avez soumis une demande de mise a disposition d'un service ERP en ligne sur le serveur ERP en Self-Service de SISalp.

Votre service ERP est en cours d'installation. Vous allez bientot recevoir vos instructions de connexion et d'utilisation par mail.

Merci de surveiller votre boîte aux lettres et eventuellement votre boite des SPAMs.

Nous vous souhaitons pleine reussite dans vos activites.

"
			;;
		en)
			MessageSubject="[Help Yourself ERP by SISalp] Installation of your service ERP on-line" $MailFlag
			MessageText="Hello,

You made a request on SISalp's Help Yourself ERP server for an on-line ERP service. This service is now being installed. You will soon receive connection and use instructions by mail.

Please, check your inbox and eventually your spam box.

In case of difficulty, please contact service.client@sisalp.fr

We wish you full success in your activities.

"
			;;
		esac
		;;
	all_ids)
		case "$message_language" in
		fr)
			MessageSubject="[ERP en Self-Service par SISalp] Instruction de connexion a votre service ERP en ligne $MailFlag"
			MessageText="Bonjour,

Vous avez soumis une demande d'envoi des instructions de connexion et d'utilisation de vos services actifs sur le serveur ERP en Self-Service de SISalp.

Vous allez bientot recevoir vos instructions de connexion et d'utilisation par mail de chaque service.

Merci de surveiller votre boîte aux lettres et eventuellement votre boite des SPAMs

Nous vous souhaitons pleine reussite dans vos activites.

"
			;;
		en)
			MessageSubject="[Help Yourself ERP by SISalp] Connection instructions to your service ERP on-line $MailFlag"
			MessageText="Hello,

You made a request on SISalp's Help Yourself ERP server to recieve your connection instructions to your on-line ERP services.

You will soon receive connection and use instructions by mail for all active services.

Please, check your inbox and eventually your spam box.

In case of difficulty, please contact service.client@sisalp.fr

We wish you full success in your activities.

"
			;;
		esac
		;;
	esac
	#echo "$MessageText" | mail -a "From: $SenderMail" -s "$MessageSubject" $ToMail
	SEND
	;;
esac
LOG_MESSAGE $LINENO "send mail $message_type $message_language $templatename code $Code db $ServiceName to $Mail"
}
#------------------------------------------------------------------------------
CHECK_PERMISSIONS ()
#------------------------------------------------------------------------------
{
for directory in $SoeDir $SoeSpool $SoeSpool.local $SoeData ; do
	if [ ! -d $directory ] ; then
		mkdir -p $directory
		chmod 777 $directory
	fi
done
for datafile in $SoeConfig $SoeCodes $SoeAdminCodes $SoeLogFile $SoeStatus ; do
	if [ ! -e $datafile ] ; then
		echo "#$HOSTNAME|soe|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$* initialization of $datafile" >> $datafile
		chmod 777 $datafile
		LOG_MESSAGE $LINENO "File $datafile is initialized"
	fi
	case "$CurrentUser" in
	root)
		chmod 777 $datafile
		;;
	esac
done
datafile="$SoeLastDelivery"
if [ ! -e $datafile ] ; then
	date +"%d/%m/%y %H:%M" > $SoeLastDelivery
	chmod 777 $datafile
	LOG_MESSAGE $LINENO "File $datafile is initialized"
fi
case "$CurrentUser" in
root)
	chmod 777 $datafile
	;;
esac
}
#------------------------------------------------------------------------------
#
#echo "$LINENO MAIN $*"
Option="$1"
shift
ActionParameters="$*"
CHECK_PERMISSIONS
#LOG_MESSAGE $LINENO "$Option $*"
case "$Option" in
--code)
	Site="$1"
	shift
	SITE_CONFIG $Site
	Mail="$1"
	Language="$2"
	Code=`GET_CODE $Mail`
	Language=`GET_LANGUAGE $Mail`
	CORRECT_CODE_ONLY $Mail $Code
	LOCAL_ACTION -send_code $Mail $Code $Language
	RETURN_MESSAGE "Vous allez recevoir votre code personnel par mail à l'adresse $Mail<br/><i>Your personnal code is going to be sent by mail to $Mail</i>"
	;;
#------------------------------------------------------------------------------
--revoke)
	Site="$1"
	shift
	SITE_CONFIG $Site
	Mail="$1"
	Code="$2"
	CORRECT_CODE_ONLY $Mail $Code
	Language=`GET_LANGUAGE $Mail`
	LOCAL_ACTION -revoke $Mail $Code $Language
	RETURN_MESSAGE "Vous allez recevoir une derniere confirmation de votre action par mail à l'adresse $Mail<br/><i>A last confirmation message is going to be sent by mail to $Mail</i>"
	;;
#------------------------------------------------------------------------------
--unrevoke)
	Mail="$1"
	Code="$2"
	LOCAL_ACTION -unrevoke $Mail $Code
	RETURN_MESSAGE "Vous allez recevoir une confirmation de votre action par mail à l'adresse $Mail<br/><i>A confirmation message is going to be sent by mail to $Mail</i>"
	;;
#------------------------------------------------------------------------------
--service_ids)
	Site="$1"
	shift
	SITE_CONFIG $Site
	Mail="$1"
	Code="$2"
	Version="$3"
	Family="$4"
	CORRECT_CODE_ONLY $Mail $Code
	Language=`GET_LANGUAGE $Mail`
	# version and family are not verified
	if [ -z "$Family" ] ; then
		LOG_MESSAGE $LINENO "Version and family are mandatory with --service_ids command"
		exit 1
	fi
	ACTION -service_ids $Mail $Code $Version $Family $Language
	RETURN_MESSAGE "Vous allez recevoir vos identifiants de connexion à votre ERP par mail à l'adresse $Mail quand votre service sera disponible<br/><i>Connection instructions to your ERP will be sent to $Mail when your service is installed</i>"
	;;
#------------------------------------------------------------------------------
--all_ids)
	Site="$1"
	shift
	SITE_CONFIG $Site
	Mail="$1"
	Code="$2"
	CORRECT_CODE_ONLY $Mail $Code
	Language=`GET_LANGUAGE $Mail`
	ACTION -all_ids $Mail $Code $Language
	RETURN_MESSAGE "Vous allez recevoir vos identifiants de connexion à votre ERP par mail à l'adresse $Mail<br/><i>Connection instructions to your ERP will be sent to $Mail</i>"
	;;
#------------------------------------------------------------------------------
--execute)
	case "$SoeMode" in
	local|remote|test|redirect)
		case "$SoeMode" in
		remote)
			COLLECT_SPOOL
			ToDoRemote=`ls $SoeSpool`
			ToDoLocal=""
			;;
		local)
			ToDoRemote=""
			ToDoLocal=`ls $SoeSpool.local`
			;;
		*)
			ToDoRemote=`ls $SoeSpool`
			ToDoLocal=`ls $SoeSpool.local`
			;;
		esac
		for action in $ToDoLocal ; do
			$SoeSpool.local/$action
		done
		SHOP_OPEN_ONLY
		for action in $ToDoRemote ; do
			SHOP_OPEN_ONLY
			$SoeSpool/$action
			date +"%d/%m/%y %H:%M" > $SoeLastDelivery
		done
		;;
	*|suspend)
		LOG_MESSAGE $LINENO "Mode is suspend, spooled actions are not executed"
		;;
	esac
	;;
#------------------------------------------------------------------------------
--background)
	NOT_LOOPING_ONLY
	nohup $0 --loop_forever >> $SoeLogFile 2>&1 &
	;;
#------------------------------------------------------------------------------
--loop_forever)
	LOOP_FOREVER
	;;
#------------------------------------------------------------------------------
--spool)
	ls -lh $SoeSpool
	ls -lh $SoeSpool.local
	;;
#------------------------------------------------------------------------------
--start)
	UNSTOP_LOOP
	;;
#------------------------------------------------------------------------------
--stop)
	STOP_LOOP
	;;
#------------------------------------------------------------------------------
--action)
	Command="$1"
	Mail="$2"
	Code="$3"
	Language="$4"
	case "$Command" in
	-send_code)
		SEND_MAIL -template $Language send_code
		;;
	-revoke)
		SEND_MAIL -template $Language revoke
		REVOKE_MAIL $Mail $Language

		;;
	-unrevoke)
		SEND_MAIL -template $Language unrevoke
		UNREVOKE_MAIL $Mail $Language
		;;
	-service_ids)
		Version="$4"
		Family="$5"
		Language="$6"
		SEND_MAIL -template $Language service_ids
		LOG_MESSAGE  $LINENO "/usr/local/bin/hoe --declare -subscription $Mail $Language $Family $Version"
		/usr/local/bin/hoe --declare -subscription $Mail $Language $Family $Version
		;;
	-all_ids)
		# TO BE DONE
		SEND_MAIL -template $Language all_ids
		;;
	esac
	;;
#------------------------------------------------------------------------------
--report)
	case "$1" in
	-raz)
		rm $SoeReport
		;;
	-live)
		while [ ! -f $SoeReport ] ; do
			sleep 1
		done
		tail -f $SoeReport
		;;
	*)
		less $SoeReport
		;;
	esac
	;;

#------------------------------------------------------------------------------
--erpversions)
	Site="$1"
	shift
	SITE_CONFIG $Site
	cat $SoeCatalogue | grep ^erp_version: | cut -f2-
	exit 0
	;;
#------------------------------------------------------------------------------
--erpsettings)
	Site="$1"
	shift
	SITE_CONFIG $Site
	cat $SoeCatalogue | grep ^erp_setting: | cut -f2-
	exit 0
	;;

#------------------------------------------------------------------------------
--version)
	echo ""
	echo "<!--soe version is $SoeVersion -->"
	if [ -d /var/www/html/ ] ; then
		cd /var/www/html/
		grep -rn "SiteVersion:" *
	fi
	;;
#------------------------------------------------------------------------------
--config)
	case `whoami` in
	root)
		cat $0 | grep -m 1 -B 100 "#EndConfig" | grep -A 100 "#StartConfig"
		cat $SoeConfig
		;;
	esac
	;;
#------------------------------------------------------------------------------
--keypass)
	priviledgekey=`NEW_PASSWORD 13 2`
	echo "allowed_code:	adm_$priviledgekey" >> $SoeAdminCodes
	echo "Your new admin access is adm_$priviledgekey"
	;;
#------------------------------------------------------------------------------
--log)
	cat -n $SoeLogFile
	;;

#------------------------------------------------------------------------------
--log_rotate)
	cat $SoeLogFile > $SoeLogFile.history
	rm $SoeLogFile
	LOG_MESSAGE $LINENO "Log is rotated to $SoeLogFile.history"
	;;
#------------------------------------------------------------------------------
--log_history)
	cat -n $SoeLogFile.history
	;;
#------------------------------------------------------------------------------
--live)
	tail -f $SoeLogFile
	;;
#------------------------------------------------------------------------------
--mode)
	case "$1" in
	test|local|remote|suspend|redirect)
		echo "$1" > $SoeModeFile
		;;
	*)
		echo -n "$SoeMode"
		;;
	esac
	;;
#------------------------------------------------------------------------------
--site_mode)
	sm_mode="$1"
	shift
	case "$sm_mode" in
	closed|maintenance|on|open|test)
		echo "$sm_mode	$*" >  $SoeSiteModeFile
		;;
	*)
		echo -n "$SoeSiteMode"
		;;
	esac
	;;
#------------------------------------------------------------------------------
--status)
	if [ ! -z "$1" ] ; then
		echo "$*" > $SoeStatus
	else
		if [ ! -f "$SoeStatus" ] ; then
			echo "<span style=\"padding:5px 20px; margin: 5px; background-color: #7e0021; border:solid 1px #4e0011; color: #eeeeee; \">Dernier livré/<i>Last delivery</i> `cat $SoeLastDelivery` Delai/<i>Lead time</i>: Inconnu/<i>Unknown</i>:</span><br/><br/>"
		else
			cat $SoeStatus
		fi
	fi
	;;
#------------------------------------------------------------------------------
--public_address)
	Site="$1"
	shift
	SITE_CONFIG $Site
	if [ ! -z "$1" ] ; then
		echo "$*" > $SoePublicAddress
	else
		if [ -f "$SoePublicAddress" ] ; then
			cat $SoePublicAddress
		else
			echo "<br/><br/>"
		fi
	fi
	;;
#------------------------------------------------------------------------------
--about)
	echo "<br/><br/><a href=\"https://sisalp.fr\" target=\"_blank\">A propos de SISalp</a><br/><i><a href=\"https://sisalp.fr\" target=\"_blank\">About SISalp</a></i><br/><br/><br/>"
	;;
#-------------------------------------------------------------------------
--update)
	DOWNLOAD_SCRIPT_COMMAND=`cat $SoeConfig | grep ^soe_script_update: | cut -f2-`
	echo "$LINENO soe script --update : $DOWNLOAD_SCRIPT_COMMAND"
	$0 --version -noblabla
	if [ ! -z "$DOWNLOAD_SCRIPT_COMMAND" ] ; then
		cd /usr/local/bin
		rm -rf rescue.soe
		mv soe rescue.soe
		if $DOWNLOAD_SCRIPT_COMMAND ; then
			diff $VERBOSE_OUTPUT rescue.soe soe
			chmod 755 soe
		else
			mv /usr/local/bin/rescue.soe /usr/local/bin/soe
			echo "$LINENO Failed to download $DOWNLOAD_SCRIPT_COMMAND"
			exit 1
		fi
	else
		LOG_MESSAGE -vv "$LINENO download code source is not configured"
	fi
	DOWNLOAD_WEB_COMMAND=`cat $SoeConfig | grep ^soe_web_update: | cut -f2-`
	if [ ! -z "$DOWNLOAD_WEB_COMMAND" ] ; then
		echo "$LINENO soe web --update : $DOWNLOAD_WEB_COMMAND"
		cd /var/www/html/
		rm -rf rescue.soe.www
		mv soe.www rescue.soe.www
		rm -f soe.www.tar.gz
		if $DOWNLOAD_WEB_COMMAND ; then
			tar -xzf soe.www.tar.gz
			rm soe.www.tar.gz
			diff -r rescue.soe.www soe.www
			#ls
		else
			rm -rf /var/www/html/soe.www
			mv /var/www/html/rescue.soe.www /var/www/html/soe.www
			echo "$LINENO Failed to download $DOWNLOAD_WEB_COMMAND"
			exit 1
		fi
	fi
	/usr/local/bin/soe --version
	;;	
#------------------------------------------------------------------------------
--help)
	echo "soe : self-service ERP
syntax :
soe --command [parameters]

command :
--help

commands activated by internet user or administrator:
====================================================

--code		site mail_address code fr|en					#get personnal id code
--service_ids	site mail_address code 6|61|7|8|9|10|11|t entreprise|education	#get service connexion ids
--all_ids	site mail_address code					#get all ids linked to this address
--revoke	site mail_address code					#blacklist an email address
--status								#status presented on site
--public_address	site						#public adderess message
--about									#About generic mention
--erpversions	site							#list configured options of erp versions
--erpsettings	site							#list configured settings


previous commands generates scripts in $SoeSpool which invoke the following command :

--action -command 	mail_address	parameters	#execute the action requested by internet user
-command is in 	-send_code|-service_ids|-all_services_ids|-revoke
--action -code		mail_address code fr|en					#get personnal id code
--action -service_ids	mail_address code 6|61|7|8|9|10|11|t entreprise|education fr|en	#get service connexion ids
--action -all_ids	mail_address code fr|en					#get all ids linked to this address
--action -revoke	mail_address code fr|en					#blacklist an email address

All scripts of the spool are executed periodically in loop activated or re-activated by crontab

--background		#check the loop is active else restart it by --loop_forever
--execute		#execute all scripts in the spool
--loop_forever		#loop forever on --execute command

commands for the administrator only:
===================================

--config		#prints hardcoded parameters and context files
--unrevoke		mail_address		#revalidate an email address

--licence		#print licence
--live			#print last lines and follow soe log file
--log			#print soe log file
--log_history		#print older log
--log_rotate		#move log messages to older log
--mode [mode]		#set soe execution mode (see below)
--report [-raz|-live]	#report of background actions
--site_mode [mode] [MessageFr:MessageEn]	#set soe site execution mode (see below)
--spool			#list waiting scripts in spool
--start			#let the background loop restart
--stop			#stop the next background loop
--version		#print soe version
--update		#download a new version

command --revoke can be used by the user or the administrator with a keypass code

Allowed codes in $SoeAdminCodes are used to by-pass user authentication

Soe execution modes are used for online maintenance:
local		service is local,
remote		service is remote,
test		commands on services are not executed and mail is sent to alternative test mail address
suspend		background actions are delayed
redirect	all mail traffic is redirected to administrator's mail box

Site execution modes are used for online maintenance:
open				service delivery is on
closed MessageFr:MessageEn	service delivery is off, Messages Fr and En are displayed
maintenance			web interface is closed,
on				web site is operational
test				default status is diplayed on site

if mode is not indicated, soe returns current mode
Remote requires /etc/hosts to solve host names and key previously exchanged.

Parameters are located in $SoeConfig
"
cat $SoeConfig | grep "#"
$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
2015-today: soe is an original work from SISalp, https://sisalp.fr"
	;;
#------------------------------------------------------------------------------
*)
	echo "503 Option $Option is not supported by soe command"
	$0 --help
	;;
#------------------------------------------------------------------------------
esac
exit 0
