#! /bin/bash
#------------------------------------------------------------------------------
#see licence at the end
#
MoocVersion="2.0 - deprecated Last Update : `stat -c %z $0 | cut -d"." -f1`"
Date=`date +%y_%m_%e_%H_%M_%S`
CurrentUser=`whoami`
AllParameters="$*"
XoeAuthorizedUser=`cat /usr/local/etc/xoe/xoe.list_of_users.conf | cut -d" " -f1`
#------------------------------------------------------------------------------
#StartConfig
#------------------------------------------------------------------------------
#Adapt following values to your context
#
#MoocMode : see --help"
MoocMode="on"
#Mooc execution modes are used for online maintenance:
#on		operationnal,
#test		commands on databases 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
#off		no mooc functionality


#Other parameters you may look for :
#
#mooc background tasks parameters
#-------------------------------
MoocDir="/usr/local/etc/mooc"
MoocTranslationEn="$MoocDir/mooc.translation.en"
MoocTranslationFr="$MoocDir/mooc.translation.fr"
GoeCurrentLanguage="/usr/local/etc/goe/goe.language.conf"
MoocParametersConf="$MoocDir/mooc.conf"
MoocPermanentConf="$MoocDir/mooc.local.conf"
MoocSpool="$MoocDir/mooc_spool"
MoocData="$MoocDir/mooc_data"
MoocConfigFile="$MoocData/mooc.data"
MoocCodes="$MoocData/codes.data"
MoocDatabases="$MoocData/databases.data"
MoocLogFile="$MoocDir/mooc.log"
MoocConfigVersionFile="$MoocData/mooc.config.version"
MoocReport="/tmp/mooc.report.$$.tmp"
MoocModeFile="$MoocDir/mooc.mode"
DefaultNbDatabaseMax="50"
DefaultNbDatabaseMin="0"
DefaultPace="30"
DefaultMail="service.client@sisalp.fr"
TestInfo="/tmp/last_used_mooc.test.data"

#Site parameters
#--------------------------------------
HttpUser="www-data"

MoocDownloadSource="http://download.sisalp.net/scripts/panel/mooc"

#GlobalParameter:	value

Pace="$DefaultPace"
AdminMail="-"
SenderMail="-"
TestMail="-"

#------------------------------------------------------------------------------
#EndConfig
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
LOG_MESSAGE ()
#------------------------------------------------------------------------------
{
case "$NoisyLog" in
No)
	;;
*)
	case "$1" in
	-short)
		shift
		echo -n "$*" >> $MoocLogFile
		echo "return" > /tmp/mooc.log.return
		chmod 777 /tmp/mooc.log.return
		;;
	*)
		if [ -f /tmp/mooc.log.return ] ; then
			rm /tmp/mooc.log.return
			echo "" >> $MoocLogFile
		fi
		echo "$HOSTNAME|mooc|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$*" >> $MoocLogFile
		;;
	esac
	;;
esac
}
#-------------------------------------------------------------------------
FORMAT_DATABASE_NAME ()
#-------------------------------------------------------------------------
{
fdn_name=`echo "$*" | iconv -f utf-8 -t US-ASCII//TRANSLIT | sed s/" "/_/g | sed s/\'/_/g  | tr '[:upper:]' '[:lower:]'`
echo "$fdn_name"
}
#-------------------------------------------------------------------------
READ_MOOC_CONFIG ()
#-------------------------------------------------------------------------
{
MoocConfig=`cat $MoocConfigFile | grep --invert-match "^#" | sed 's/\t\t\t\t/\t/g'| sed 's/\t\t\t/\t/g'| sed 's/\t\t/\t/g'`
}
#------------------------------------------------------------------------------
CHECK_CONFIGURATION ()
#------------------------------------------------------------------------------
{
case "$CurrentUser" in
root)
	if [ ! -e $MoocDir ] ; then
		mkdir $MoocDir
	fi
	if [ ! -f "$MoocLogFile" ] ; then
		LOG_MESSAGE $LINENO "File $MoocLogFile is initialized"
	fi
	if [ ! -d "$MoocData" ] ; then mkdir $MoocData ; fi
	if [ ! -f $MoocConfigFile ] ; then
		echo "#$MoocVersion
#$HOSTNAME|mooc|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$* initialization of $MoocConfigFile
#Mooc definitions
#Mooc:xoe_service_name:mooc_name:mooc_code:	Open/Closed	reference_database	min/max-databases	admin_address
" > $MoocConfigFile
		LOG_MESSAGE $LINENO "File $MoocConfigFile is initialized"
	fi
	if [ ! -f "$MoocDatabases" ] ; then
		echo "#$MoocVersion
#$HOSTNAME|mooc|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$* initialization of $MoocDatabases
#Database definitions
#Database:xoe_service_name:mooc_name:	:Database_name:	:login/password:	:Student_mail:
" > $MoocDatabases
		LOG_MESSAGE $LINENO "File $MoocDatabases is initialized"
	fi
	if [ ! -f "$MoocCodes" ] ; then
		echo "#$MoocVersion
#$HOSTNAME|mooc|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$* initialization of $MoocCodes
#Code registrations
#StudentMail:	Personal_code	User_name
" > $MoocCodes
		LOG_MESSAGE $LINENO "File $MoocCodes is initialized"
	fi
	if [ ! -d "$MoocSpool" ] ; then mkdir $MoocSpool ; fi
	chown -R $XoeAuthorizedUser:$HttpUser $MoocDir
	chmod -R 770 $MoocDir
	;;
esac
}
#------------------------------------------------------------------------------
CHECK_CONFIGURATION
if [ -f "$MoocParametersConf" ] ; then
	. $MoocParametersConf
else
	cat $0 | grep -m 1 -B 1000 "^#EndConfig" | grep -A 1000 "^#StartConfig" > $MoocParametersConf
fi
if [ -f "$MoocPermanentConf" ] ; then
	. $MoocPermanentConf
fi
if [ -f $MoocModeFile ] ; then
	MoocMode=`cat $MoocModeFile`
fi
if [ ! -f $MoocConfigFile ] ; then
	echo "#$HOSTNAME|mooc|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$* initialization of $MoocConfigFile
#Mooc definitions
#Mooc:xoe_service_name:mooc_name:mooc_code:	Open/Closed	reference_database	min/max-databases	admin_address
" > $MoocConfigFile
	chmod 777 $MoocConfigFile
	LOG_MESSAGE $LINENO "File $MoocConfigFile is initialized"
fi
READ_MOOC_CONFIG
NbDatabasePerService=`echo "$MoocConfig" | grep "^NbDatabasePerService:" | cut -f2`
Pace=`echo "$MoocConfig" | grep "^Pace:" | cut -f2`
#LocalReferenceData=`echo "$MoocConfig" | grep "^LocalReferenceData:" | cut -f2`
if [ -f $GoeCurrentLanguage ] ; then
	Language=`cat $GoeCurrentLanguage`
else
	Language="en"
fi
#------------------------------------------------------------------------------
TR ()
#------------------------------------------------------------------------------
{
	shift
	if [ ! -z $1 ] ; then
		translator="$1"
		shift
		english_text=`echo "$*" | cut -d: -f1 | sed s/' $'//`
		texte_francais=`echo "$*" | cut -d: -f2 | sed s/'^ '//`
		echo "$translator=\"$english_text\"" >> $MoocTranslationEn
		echo "$translator=\"$texte_francais\"" >> $MoocTranslationFr
	fi
}
#------------------------------------------------------------------------------
if [ ! -f $MoocTranslationFr ] || [ ! -f $MoocTranslationEn ] ; then
	old_IFS=$IFS
	IFS=$'\n'
	for TR_line in `cat $0 | grep "#TR " | grep -v "#Not me"` ; do  #Not me
		IFS=$old_IFS
		TR $TR_line
		IFS=$'\n'
	done
	IFS=$old_IFS
	chmod 777 $MoocTranslationEn
	sudo chown $XoeAuthorizedUser:$HttpUser $MoocTranslationEn
	chmod 777 $MoocTranslationFr
	sudo chown $XoeAuthorizedUser:$HttpUser $MoocTranslationFr
fi	
case "$Language" in
fr|Francais)
	. $MoocTranslationFr
	;;
en|English|*)
	. $MoocTranslationEn
	;;
esac

#------------------------------------------------------------------------------
#------------------------------------------------------------------------------

#Fonctions
#-------------------------------------------------------------------------
NEW_PASSWORD ()
#-------------------------------------------------------------------------
{
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
echo "${NEW_PWD}"
}
#------------------------------------------------------------------------------
NEW_CODE ()
#------------------------------------------------------------------------------
{
	prefix="$1"
	shift
	uniqueinfile="$1"
	shift
	if [ -z "$1" ] ; then
		keylength="2 3"
	else
		keylength="$*"
	fi
	key=`NEW_PASSWORD $keylength`
	#check code is unique
	if [ ! -z "$uniqueinfile" ] && [ -f $uniqueinfile ] ; then
		while cat $uniqueinfile | grep -qi "$prefix$key" ; do
			LOG_MESSAGE $LINENO "NEW_CODE: bad luck, the code $prefix$key is already in use, shoot again"
			key=`NEW_PASSWORD $keylength`
		done
	fi
	echo "$prefix$key"
}
#------------------------------------------------------------------------------
GET_CODE ()
#------------------------------------------------------------------------------
{
	if cat $MoocCodes | grep -q "^$1:" ; then
		cat $MoocCodes | grep -i "^$1:" | tail -n 1 | cut -f2
	else
		get_code=`NEW_CODE code_`
		echo "$1:	$get_code	$StudentName" >> $MoocCodes
		echo "$get_code"
	fi
}
#------------------------------------------------------------------------------
GET_URL ()
#------------------------------------------------------------------------------
{
ServiceUrl=`/usr/local/bin/xoe --config -noblabla $1 | grep "^url:" | head -n 1 | sed 's/\t\t\t\t/\t/g'| sed 's/\t\t\t/\t/g'| sed 's/\t\t/\t/g' | cut -f2 | cut -d" " -f1`
}

#------------------------------------------------------------------------------
GET_DATABASE_STATS ()
#------------------------------------------------------------------------------
{
MoocDatabaseList=`cat $MoocDatabases | grep "^Database:$MoocService:$MoocName:" | cut -f2- | cut -d: -f2 | xargs`
MoocDatabaseNumber=`echo "$MoocDatabaseList" | wc -w`
AssignedDatabaseList=`cat $MoocDatabases | grep "^Database:$MoocService:$MoocName:" | grep -v ":UNASSIGNED:" | cut -f2- | cut -d: -f2 | xargs`
AssignedDatabaseNumber=`echo "$AssignedDatabaseList" | wc -w`
UnassignedDatabaseList=`cat $MoocDatabases | grep "^Database:$MoocService:$MoocName:" | grep ":UNASSIGNED:" | cut -f2- | cut -d: -f2 | xargs`
UnassignedDatabaseNumber=`echo "$UnassignedDatabaseList" | wc -w`
}
#------------------------------------------------------------------------------
GET_DATABASE_EXISTING_LIST ()
#------------------------------------------------------------------------------
{
XoeDatabaseList=" `/usr/local/bin/xoe --database -list $MoocService | cut -d"|" -f1 | xargs` "
}
#------------------------------------------------------------------------------
NOT_EXECUTING_ONLY ()
#------------------------------------------------------------------------------
{
	runningprocesses=`/bin/ps axo pid,cmd`
	if echo "$runningprocesses" | grep "$0" | grep -q "mooc --execute" ; then
		LOG_MESSAGE -short ":"
		exit 0
	fi
}
#------------------------------------------------------------------------------
PARSING_MOOC_LINE ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO "PARSING_MOOC_LINE $LINENO $*"
READ_MOOC_CONFIG
mooc_key=":"
for parameter in $* ; do
	mooc_key="$mooc_key$parameter:"
done
MoocLine=`echo "$MoocConfig" | grep "^Mooc:" | grep -i "$mooc_key" | tail -n 1`
#LOG_MESSAGE $LINENO "PARSING_MOOC_LINE MoocLine $MoocLine"
if [ -z "$MoocLine" ] ; then

	MoocStatus="Unknown"
	LOG_MESSAGE $LINENO "PARSING_MOOC_LINE mooc_key $mooc_key Not Found"
else

	MoocService=`echo "$MoocLine" | cut -d: -f2`
	MoocName=`echo "$MoocLine" | cut -d: -f3`
	MoocCode=`echo "$MoocLine" | cut -d: -f4`
	MoocStatus=`echo "$MoocLine" | cut -f2`
	MoocReference=`echo "$MoocLine" | cut -f3`
	MoocMin=`echo "$MoocLine" | cut -f4 | cut -d/ -f1`
	MoocMax=`echo "$MoocLine" | cut -f4 | cut -d/ -f2`
	MoocAdminMail=`echo "$MoocLine" | cut -f5`
	case "$MoocMode" in
	test)
		echo "$MoocName $MoocCode" > $TestInfo
		;;
	esac
fi
MoocUrl=`/usr/local/bin/xoe --config -noblabla | grep -m 1 "^panel_url:" | cut -f2-`
# supprimer les tabulations inutiles ou interoger xoe **************************
#LOG_MESSAGE $LINENO "PARSING_MOOC_LINE MoocService $MoocService MoocName $MoocName MoocCode $MoocCode MoocStatus $MoocStatus MoocReference $MoocReference MoocMin $MoocMin MoocMax $MoocMax MoocAdminMail $MoocAdminMail"
}
#------------------------------------------------------------------------------
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 $MoocCodes | grep -i "^$given_mail:" | tail -n 1 | cut -f2`
	if [ -z "$registered_code" ] ; then
		RETURN_MESSAGE "Vous avez commis une erreur en indiquant votre mail ou votre code personnel. L'action demandee ne va pas etre effectuee."
		LOG_MESSAGE $LINENO "Access denied $StudentMail $Code E-mail not found"
		exit 0
	fi
	case "$registered_code" in
	revoked)
		RETURN_MESSAGE "Vous utilisez une adresse mail qui n'est plus autorisee. Contactez le support pour plus d'explications"
		exit 0
		;;
	esac
	case "$given_code" in
	$registered_code)
		StudentName=`cat $MoocCodes | grep -i "^$given_mail:" | tail -n 1 | cut -f3-`
		;;
	*)
		RETURN_MESSAGE "Vous avez commis une erreur en indiquant votre mail ou votre code personnel. L'action demandee ne va pas etre effectuee."
		LOG_MESSAGE $LINENO "Access denied $StudentMail $Code Code is incorrect"
		exit 0
		;;
	esac
}
#------------------------------------------------------------------------------
CORRECT_MOOC_ONLY ()
#------------------------------------------------------------------------------
{
	given_mooc_name="$1"
	given_mooc_code="$2"
	if [ -z "$given_mooc_code" ] ; then
		RETURN_MESSAGE "Vous devez indiquer le code d'identification du cours"
		exit 0
	fi
	PARSING_MOOC_LINE $given_mooc_name $given_mooc_code
	case "$MoocStatus" in
	Unknown)
		RETURN_MESSAGE "Vous avez commis une erreur en indiquant le nom du cours ou son code. L'action demandee ne va pas etre effectuee."
		exit 0
		;;
	Closed)
		RETURN_MESSAGE "Le cours que vous souhaitez rejoindre n'est pas ouvert aux nouvelles inscriptions. L'action demandee ne va pas etre effectuee."
		exit 0
		;;
	Open|*)
		case "$MoocMode" in
		test|off|redirect)
			RETURN_MESSAGE "La gestion des cours est en maintenance. Vous devez repeter cette operation plus tard."
			;;
		esac
		;;
	esac
}
#------------------------------------------------------------------------------
ACTION ()
#------------------------------------------------------------------------------
{
ActionTemplate="#! /bin/bash
/usr/local/bin/mooc --action $* >> $MoocLogFile 2>&1
rm \$0
exit 0"
echo "$ActionTemplate" > $MoocSpool/action.${Code}$1.sh
chmod 755 $MoocSpool/action.${Code}$1.sh
LOG_MESSAGE $LINENO "action $* is now waiting in spool"
cp $MoocSpool/action.${Code}$1.sh /tmp/action.${Code}$1.sh	#debug
}
#------------------------------------------------------------------------------
RETURN_MESSAGE ()
#------------------------------------------------------------------------------
{
echo "<br/>$*<br/>"
}
#------------------------------------------------------------------------------
PARSING_CODE_LINE ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO "PARSING_CODE_LINE $1"
MailExists="No"
if [ ! -z "$1" ] ; then
	CodeLine=`cat $MoocCodes | grep -i "^$1:" | tail -n 1`
	if [ ! -z "$CodeLine" ] ; then
		MailExists="Yes"
		StudentCode=`echo "$CodeLine" | cut -f2`
		StudentName=`echo "$CodeLine" | cut -f3-`
	fi
fi
#LOG_MESSAGE $LINENO "PARSING_CODE_LINE Mail $1 MailExists $MailExists StudentCode $StudentCode StudentName $StudentName CodeLine $CodeLine"
}

#------------------------------------------------------------------------------
PARSING_DATABASE_LINE ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO "PARSING_DATABASE_LINE $1 Database:$MoocService:$MoocName:"
parsingkey="$1"
DatabaseLine=""
if [ ! -z "$parsingkey" ] ; then
	DatabaseLine=`cat $MoocDatabases | grep "^Database:$MoocService:$MoocName:" | grep -i ":$parsingkey:" | tail -n 1`
else
	LOG_MESSAGE $LINENO "PARSING_DATABASE_LINE parsingkey is empty"
fi
if [ -z "$DatabaseLine" ] ; then
	DatabaseLine=`cat $MoocDatabases | grep "^Database:$MoocService:$MoocName:" | grep -i ":UNASSIGNED:" | head -n 1`
fi
#LOG_MESSAGE $LINENO "PARSING_DATABASE_LINE DatabaseLine $DatabaseLine"
PARSING_DATABASE ()
{
shift
DatabaseName=`echo "$1" | cut -d: -f2`
shift
case "$1" in
*/*)
	DatabaseLoginId=`echo "$1" | cut -d: -f2 | cut -d/ -f1`
	DatabaseLoginPassword=`echo "$1" | cut -d: -f2 | cut -d/ -f2`
	shift
	;;
*)
	DatabaseLoginId="admin"
	DatabaseLoginPassword="admin"
	;;
esac
case "$*" in
:UNASSIGNED:*)
	;;
*)
	StudentMail=`echo "$1" | cut -d: -f2`
	PARSING_CODE_LINE $StudentMail
	;;
esac
}
if [ -z "$DatabaseLine" ] ; then
	DatabaseAssigned="Unknown"
else
	case "$DatabaseLine" in
	*UNASSIGNED*)
		DatabaseAssigned="Unassigned"
		;;
	*)
		DatabaseAssigned="$StudentMail"
		;;
	esac
	PARSING_DATABASE $DatabaseLine
fi
#LOG_MESSAGE $LINENO "PARSING_DATABASE_LINE DatabaseAssigned $DatabaseAssigned DatabaseName $DatabaseName"
}

#------------------------------------------------------------------------------
GET_DATABASE ()
#------------------------------------------------------------------------------
{
#LOG_MESSAGE $LINENO "GET DATABASE $*"
gdb_option="$1"
shift
case "$gdb_option" in
-predeclare)
	#declare unassigned databases
	GET_DATABASE_STATS
	if [ $MoocDatabaseNumber -lt $MoocMin ] ; then
		for ((indexdb=$MoocDatabaseNumber;indexdb<$MoocMin;indexdb=indexdb+1)) ; do
			RawDatabaseName="m_${MoocName}_`NEW_CODE b $MoocDatabases`"
			DatabaseName=`FORMAT_DATABASE_NAME $RawDatabaseName`
			DatabasePassword=`NEW_PASSWORD 7`

			DatabaseLoginId="admin"
			DatabaseLoginPassword="admin_$DatabasePassword"
			echo "Database:$MoocService:$MoocName:	:$DatabaseName:	:$DatabaseLoginId/$DatabaseLoginPassword:	:UNASSIGNED:"	>> $MoocDatabases
			LOG_MESSAGE $LINENO "Declare a new database Database:$MoocService:$MoocName:	:$DatabaseName:	:$DatabaseLoginId/$DatabaseLoginPassword:	:UNASSIGNED:"
		done
	else
		LOG_MESSAGE $LINENO "Enough required databases are already declared $MoocDatabaseNumber/$MoocMin/$MoocMax"
	fi
	;;
-precreate)
	#database creation if needed
	#LOG_MESSAGE $LINENO "precreate $MoocDatabaseList"
	GET_DATABASE_STATS
	GET_DATABASE_EXISTING_LIST
	for database in $MoocDatabaseList ; do
		case "$XoeDatabaseList" in
		*$database*)
			#LOG_MESSAGE $LINENO "database $database already exists"
			;;
		*)
			#create database
			LOG_MESSAGE $LINENO "precreate database /usr/local/bin/xoe --database -restore -force $MoocService $database $MoocReference"
			/usr/local/bin/xoe --database -restore -force $MoocService $database $MoocReference
			;;
		esac
	done
	;;
-assign)
	#database assignment or declaration
	case "$DatabaseAssigned" in
	Unassigned)
		LOG_MESSAGE $LINENO "GET DATABASE assign database $DatabaseName to $StudentMail"
		DatabaseLine=`cat $MoocDatabases | grep "^Database:$MoocService:$MoocName:" | grep ":$DatabaseName:" | tail -n 1 | sed s/:UNASSIGNED:/:$StudentMail:/`
		cp $MoocDatabases $MoocDatabases.tmp
		sed s/"^Database:$MoocService:$MoocName:.*:$DatabaseName:"/"#Database:$MoocService:$MoocName:\t:$DatabaseName:"/ $MoocDatabases.tmp > $MoocDatabases
		echo "$DatabaseLine"	>> $MoocDatabases
		rm $MoocDatabases.tmp
		DatabaseAssigned="$StudentMail"
		;;
	Unknown)
		#declare database
		LOG_MESSAGE $LINENO "GET DATABASE A new database needs to be declared"
		GET_DATABASE_STATS
		if [ $MoocDatabaseNumber -ge $MoocMax ] ; then
			#max number of databases is reached TBD
			LOG_MESSAGE $LINENO "GET DATABASE max number of databases $MoocMax is reached"
		else
			RawDatabaseName="m_${MoocName}_`NEW_CODE b $MoocDatabases`"
			DatabaseName=`FORMAT_DATABASE_NAME $RawDatabaseName`
			# supprimer les tabulations inutiles ou interoger xoe **************************

			DatabasePassword=`NEW_PASSWORD 7`

			DatabaseLoginId="admin"
			DatabaseLoginPassword="admin_$DatabasePassword"
			echo "Database:$MoocService:$MoocName:	:$DatabaseName:	:$DatabaseLoginId/$DatabaseLoginPassword:	:$StudentMail:"	>> $MoocDatabases
			LOG_MESSAGE $LINENO "Declare a new database Database:$MoocService:$MoocName:	:$DatabaseName:	:$DatabaseLoginId/$DatabaseLoginPassword:	:$StudentMail:"
			DatabaseAssigned="$StudentMail"
		fi
		;;
	*)
		LOG_MESSAGE $LINENO "GET DATABASE Database already assigned to $DatabaseAssigned"
		;;
	esac
	;;
-create)
	#database creation if needed
	case "$DatabaseAssigned" in
	Unassigned|Unknown)
		LOG_MESSAGE $LINENO "GET DATABASE Database is not assigned"
		;;
	*)
		GET_DATABASE_EXISTING_LIST
		case "$XoeDatabaseList" in
		*$DatabaseName*)
			LOG_MESSAGE $LINENO "GET DATABASE Database already exists"
			DatabaseExists="Yes"
			;;
		*)
			#create database
			LOG_MESSAGE $LINENO "create database /usr/local/bin/xoe --database -restore -force $MoocService $DatabaseName $MoocReference"
			/usr/local/bin/xoe --database -restore -force $MoocService $DatabaseName $MoocReference
			DatabaseExists="No"
			;;
		esac
		;;
	esac
	;;
esac
}
#------------------------------------------------------------------------------
MOOC ()
#------------------------------------------------------------------------------
{
#echo "MOOC $LINENO $*"
	#TR T_Mooc_exists Already exists, Pick another name : Ce cours existe deja, choisissez un autre nom
mooc_action="$1"
shift
case "$mooc_action" in
-report)
	echo "---------------------------------------------------------------------" > $MoocReport
	echo "Rapport sur le cours $MoocName du service $MoocService"	>> $MoocReport
	echo "---------------------------------------------------------------------" >> $MoocReport
	echo "" >> $MoocReport
	echo "Mail de l'administrateur du cours : $MoocAdminMail" >> $MoocReport
	echo "" >> $MoocReport
	echo "Reference utilisee $MoocReference" >> $MoocReport
	echo "" >> $MoocReport
	echo "URL d'utilisation du service : $MoocUrl" >> $MoocReport
	echo "" >> $MoocReport
	echo "Code du mooc demande a l'inscription : $MoocCode" >> $MoocReport
	echo "" >> $MoocReport
	echo "Etat des inscriptions : $MoocStatus" >> $MoocReport
	echo "" >> $MoocReport
	echo "Nombre maximal de bases autorisees : $MoocMax" >> $MoocReport
	echo "" >> $MoocReport
	GET_DATABASE_STATS
	echo "Nombre de bases initiales : $MoocDatabaseNumber" >> $MoocReport
	echo "" >> $MoocReport
	echo "Nombre de bases disponibles : $UnassignedDatabaseNumber" >> $MoocReport
	echo "" >> $MoocReport
	echo "Nombre de bases utilisees : $AssignedDatabaseNumber" >> $MoocReport
	echo "" >> $MoocReport
	echo "Information sur les bases declarees : " >> $MoocReport
	echo "" >> $MoocReport
	GET_URL $MoocService
	echo "Base de donnees affectees : url Login	password	Mail	Code	Utilisateur" >> $MoocReport
	echo "format CSV" >> $MoocReport
	GET_DATABASE_EXISTING_LIST
	for reportdatabase in $AssignedDatabaseList ; do
		PARSING_DATABASE_LINE $reportdatabase
		DatabaseLoginUrl="http://$ServiceUrl/web/login?db=$DatabaseName"
		case "$XoeDatabaseList" in
		*$DatabaseName*)
			echo "$DatabaseName,$DatabaseLoginUrl,$DatabaseLoginId,$DatabaseLoginPassword,$StudentMail,$StudentCode,$StudentName" >> $MoocReport
			;;
		*)
			echo "$DatabaseName,Cette base a ete affectee puis detruite et doit etre recreee,,$StudentMail,$StudentCode,$StudentName" >> $MoocReport
			;;
		esac
	done
	echo "Base de donnees precrees non affectees" >> $MoocReport
	echo "format CSV" >> $MoocReport
	for reportdatabase in $UnassignedDatabaseList ; do
		PARSING_DATABASE_LINE $reportdatabase
		DatabaseLoginUrl="http://$ServiceUrl/web/login?db=$DatabaseName"
		echo "$DatabaseName,$DatabaseLoginUrl,$DatabaseLoginId,$DatabaseLoginPassword" >> $MoocReport
	done
	echo "" >> $MoocReport
	echo "---------------------------------------------------------------------" >> $MoocReport
	echo "Instructions utiles aux eleves"  >> $MoocReport
	echo "---------------------------------------------------------------------" >> $MoocReport
	echo "" >> $MoocReport
	echo "Votre inscription au cours $MoocName s'effectue sur la page  $MoocUrl" >> $MoocReport
	echo "" >> $MoocReport
	echo "Dans un premier temps vous devez obtenir un code personnel" >> $MoocReport
	echo "qui sera associe a votre adresse mail par le serveur" >> $MoocReport
	echo "" >> $MoocReport
	echo "Pour cela, dans le formulaire 'Etape 1'," >> $MoocReport
	echo "indiquez votre nom en n'utilisant que des lettres ou des chiffres," >> $MoocReport
	echo "puis votre adresse mail" >> $MoocReport
	echo "" >> $MoocReport
	echo "Un mail vous indiquant votre code personnel sous la forme" >> $MoocReport
	echo "code_xxxxxx vous est envoye par le serveur" >> $MoocReport
	echo "" >> $MoocReport
	echo "Muni de votre code personnel, vous pouvez maintenant vous inscrire" >> $MoocReport
	echo "au cours en utilisant le formulaire 'Etape 2'" >> $MoocReport
	echo "sur la page  $MoocUrl" >> $MoocReport
	echo "" >> $MoocReport
	echo "Choisissez le cours $MoocName" >> $MoocReport
	echo "" >> $MoocReport
	echo "Indiquez le code du cours $MoocCode" >> $MoocReport
	echo "" >> $MoocReport
	echo "Remplissez ensuite votre adresse mail et votre code personnel" >> $MoocReport
	echo "que vous avez recu precedemment" >> $MoocReport
	echo "" >> $MoocReport
	echo "Le serveur vous transmet alors par mail les instructions pour utiliser" >> $MoocReport
	echo "votre nouveau service d'entrainement" >> $MoocReport
	echo "" >> $MoocReport
	echo "---------------------------------------------------------------------" >> $MoocReport
	;;
-resend_ids)
	GET_DATABASE_STATS
	GET_DATABASE_EXISTING_LIST
	for resenddatabase in $AssignedDatabaseList ; do
		case "$XoeDatabaseList" in
		*$resenddatabase*)
			PARSING_DATABASE_LINE  $resenddatabase
			#LOG_MESSAGE "$LINENO --spool_database_ids		mail_address personal_code mooc_name mooc_code	#get database connexion ids"
			#LOG_MESSAGE "$LINENO $0 send ids of this database $DatabaseName	$DatabaseLoginUrl	$StudentCode	$StudentMail	$StudentName"
			LOG_MESSAGE "$LINENO $0 --spool_database_ids $StudentMail $StudentCode $MoocName $MoocCode ;"
			$0 --spool_database_ids $StudentMail $StudentCode $MoocName $MoocCode
			sleep 5
			;;
		*)
			LOG_MESSAGE "$LINENO $resenddatabase	Cette base a ete assignee puis detruite et doit etre recreee"
			;;
		esac
	done
	;;
-new)
	#xoe_service_name mooc_name reference_database min-databases max-databases admin_mail
	m_service_name="$1"
	shift
	m_mooc_name="$1"
	shift
	m_reference_database="$1"
	shift
	m_min_databases="$1"
	shift
	m_max_databases="$1"
	shift
	m_mail_address="$1"
	PARSING_MOOC_LINE $m_service_name $m_mooc_name
	case "$MoocStatus" in
	Unknown)
		#mooc didn't exist and is declared
		echo "Mooc:$m_service_name:$m_mooc_name:`NEW_CODE M $MoocConfigFile`:	Closed	$m_reference_database	$m_min_databases/$m_max_databases	$m_mail_address" >> $MoocConfigFile
		;;
	*)
		LOG_MESSAGE "$LINENO $mooc_action $* Mooc:$m_service_name:$m_mooc_name Already exists"
		;;
	esac
	PARSING_MOOC_LINE $m_service_name $m_mooc_name
	GET_DATABASE -predeclare
	GET_DATABASE -precreate
	;;
-open)
	PARSING_MOOC_LINE $1 $2
	case "$MoocStatus" in
	Closed)
		#echo "cat $MoocConfigFile | sed s/'^Mooc:$MoocService:$MoocName:$MoocCode:.*\tClosed\t'/'Mooc:$MoocService:$MoocName:$MoocCode:\tOpen\t'/"
		MoocConfigFileContent=`cat $MoocConfigFile | sed s/"^Mooc:$MoocService:$MoocName:$MoocCode:.*\tClosed\t"/"Mooc:$MoocService:$MoocName:$MoocCode:\tOpen\t"/`
		echo "$MoocConfigFileContent" > $MoocConfigFile
		;;
	esac
	;;
-close)
	PARSING_MOOC_LINE $1 $2
	case "$MoocStatus" in
	Open)
		MoocConfigFileContent=`cat $MoocConfigFile | sed s/"^Mooc:$MoocService:$MoocName:$MoocCode:.*\tOpen\t"/"Mooc:$MoocService:$MoocName:$MoocCode:\tClosed\t"/`
		echo "$MoocConfigFileContent" > $MoocConfigFile
		;;
	esac
	;;
-cancel)
	PARSING_MOOC_LINE $1 $2
	case "$MoocStatus" in
	Open|Closed|Ambiguous)
		#LOG_MESSAGE "$LINENO $mooc_action $* cat $MoocConfigFile | sed s/^Mooc:$MoocService:$MoocName:/#Mooc:$MoocService:$MoocName:/"
		MoocConfigFileContent=`cat $MoocConfigFile | sed s/"^Mooc:$MoocService:$MoocName:"/"#Mooc:$MoocService:$MoocName:"/`
		echo "$MoocConfigFileContent" > $MoocConfigFile
		MoocDatabasesContent=`cat $MoocDatabases | sed s/"^Database:$MoocService:$MoocName:"/"#Database:$MoocService:$MoocName:"/`
		echo "$MoocDatabasesContent" > $MoocDatabases
		;;
	Unknown)
		LOG_MESSAGE "$LINENO $mooc_action $* Mooc to delete is not found"
		;;
	esac
	;;
-list)
	if [ -z "$1" ] ; then
		echo "$MoocConfig" | grep "^Mooc:" | cut -d: -f2-3 | sort
	else
		echo "$MoocConfig" | grep "^Mooc:" | grep ":$1:" | cut -d: -f3 | sort | xargs
	fi
	;;
-html)
	case "$MoocMode" in
	off)
		echo "<![CDATA[ <!-- Management of courses is off --> ]]>"
		;;
	*)
		NoisyLog="No"
		
		#echo "m======= $LINENO `date +%Hh%Mm%Ss:%3N`" >> /tmp/collect.log
		if [ -z "$1" ] ; then
			MoocList=`echo "$MoocConfig" | grep "^Mooc:" | cut -d: -f2-4 | sort | xargs`
		else
			MoocList=`echo "$MoocConfig" | grep "^Mooc:" | grep ":$1:" | cut -d: -f2-4 | sort | xargs`
		fi
		#TR T_Mooc_status Courses status : Cours crees
		#TR T_No_mooc	No courses has been created yet : Aucun cours n a encore ete cree
		#TR T_html_Registrations Registrations : Inscriptions
		#TR T_html_Course Course : Cours
		#TR T_html_Reference  Reference : Reference
		#TR T_html_Mail_Contact Contact mail : Mail du titulaire
		#TR T_Mooc_open Open : Ouvert
		#TR T_Mooc_closed Closed : Clos

		if [ -z "$MoocList" ] ; then
			#MoocZoneContent="<![CDATA[ <!-- $T_No_mooc --> ]]>"
			MoocZoneContent="<![CDATA[   <table style=\\\"width: 800px;\\\" cellspacing=\\\"6\\\" cellpadding=\\\"0\\\">
<thead><tr><th colspan=\\\"1\\\" style=\\\"color:#999999;\\\">$T_No_mooc</th></tr></thead>
</table>]]>"
		else
			MoocZoneContent="<![CDATA[<table style=\\\"width: 800px;\\\" cellspacing=\\\"6\\\" cellpadding=\\\"0\\\">
<thead>
<tr><th colspan=\\\"7\\\" style=\\\"color:#999999;\\\">$T_Mooc_status</th></tr>
<tr style=\\\"color:#999999;font-size:0.9em;\\\"><th>Service</th><th>$T_html_Course</th><th>$T_html_Registrations</th><th>Bases</th><th>Code</th><th>$T_html_Reference</th><th>$T_html_Mail_Contact</th></tr>
</thead>
<tbody>"
			for moocline in $MoocList ; do
		
				#echo "m	$moocline	 $LINENO `date +%Hh%Mm%Ss:%3N`" >> /tmp/collect.log
				PARSING_MOOC_LINE $moocline
				moocreffile=`basename $MoocReference .sql.gz`
				case "$MoocStatus" in
				Open)
					MoocStyle="color:#336633;font-size:0.8em;"
					MoocSit="$T_Mooc_open"
					;;
				Closed)
					MoocStyle="color:#999999;font-size:0.8em;"
					MoocSit="$T_Mooc_closed"
					;;
				esac
				#echo "m	$moocline	 $LINENO `date +%Hh%Mm%Ss:%3N`" >> /tmp/collect.log		
				GET_DATABASE_STATS
				#echo "m	$moocline	 $LINENO `date +%Hh%Mm%Ss:%3N`" >> /tmp/collect.log
				MoocZoneContent="$MoocZoneContent
<tr style=\\\"$MoocStyle\\\"><td>$MoocService</td><td>$MoocName</td><td>$MoocSit</td><td>$AssignedDatabaseNumber/$MoocMin/$MoocMax</td><td>$MoocCode </td><td>$moocreffile</td><td>$MoocAdminMail</td></tr>"
			done
			MoocZoneContent="$MoocZoneContent
</tbody>
</table>]]>"
		fi
		echo "$MoocZoneContent"		
		#echo "m--------	 $LINENO `date +%Hh%Mm%Ss:%3N`" >> /tmp/collect.log
		;;
	esac
	;;
-replace_logins)
	GET_DATABASE_STATS
	GET_DATABASE_EXISTING_LIST
	echo "#`date` Start -replace_logins on $MoocDatabaseList" >> /tmp/mooc.executed.script
	for ExamDatabase in $MoocDatabaseList ; do
		case "$XoeDatabaseList" in
		*$ExamDatabase*)
			PARSING_DATABASE_LINE  $ExamDatabase
			LOG_MESSAGE "$LINENO /usr/local/bin/xoe --database -login_password service_name database_name login [password]"
			LOG_MESSAGE "$LINENO /usr/local/bin/xoe --database -login_password  $ExamService $ExamDatabase $ExamLogin $ExamPassword ;"
			echo "/usr/local/bin/xoe --database -login_password  $ExamService $ExamDatabase $ExamLogin $ExamPassword" >> /tmp/mooc.executed.script
			/usr/local/bin/xoe --database -login_password  $ExamService $ExamDatabase $ExamLogin $ExamPassword
			sleep 2
			;;
		*)
			LOG_MESSAGE "$LINENO $ExamDatabase	Cette base a ete assignee puis detruite et doit etre recreee"
			;;
		esac
	done
	echo "#`date` End -replace_logins" >> /tmp/mooc.executed.script
	/usr/local/bin/xoe --service -sessions -clear  $ExamService
	;;
-restore_logins)
	GET_DATABASE_STATS
	GET_DATABASE_EXISTING_LIST
	echo "#`date` Start -restore_logins on $MoocDatabaseList" >> /tmp/mooc.executed.script
	for ExamDatabase in $MoocDatabaseList ; do
		case "$XoeDatabaseList" in
		*$ExamDatabase*)
			PARSING_DATABASE_LINE  $ExamDatabase
			LOG_MESSAGE "$LINENO /usr/local/bin/xoe --database -login_password service_name database_name login [password]"
			LOG_MESSAGE "$LINENO /usr/local/bin/xoe --database -login_password  $ExamService $ExamDatabase $DatabaseLoginId $DatabaseLoginPassword"
			echo "/usr/local/bin/xoe --database -login_password  $ExamService $ExamDatabase $DatabaseLoginId $DatabaseLoginPassword" >> /tmp/mooc.executed.script
			/usr/local/bin/xoe --database -login_password  $ExamService $ExamDatabase $DatabaseLoginId $DatabaseLoginPassword
			sleep 2
			;;
		*)
			LOG_MESSAGE "$LINENO $ExamDatabase	Cette base a ete assignee puis detruite et doit etre recreee"
			;;
		esac
	done
	echo "#`date` End -restore_logins" >> /tmp/mooc.executed.script
	/usr/local/bin/xoe --service -sessions -clear  $ExamService
	;;
-edit)
	nano $MoocConfigFile
	;;
*)
	#error
	echo "MOOC $LINENO option $mooc_action is not valid"
	;;
esac
}
#------------------------------------------------------------------------------
TEST_MODE ()
#------------------------------------------------------------------------------
{	case "$MoocMode" in
	test)
		if [ -f $TestInfo ] ; then
			$0 --spool_database_ids $StudentMail $Code `cat $TestInfo`
		fi
		;;
	esac 
}
#------------------------------------------------------------------------------
SEND_MAIL ()
#------------------------------------------------------------------------------
{
message_type="$1"
shift
DEFAULT_MAIL ()
{
case "$MoocMode" in
on|suspend)
	MailFlag=""
	ResultMail="$1"
	case "$ResultMail" in
	*@*)
		;;
	*)
		ResultMail="$DefaultMail"
		;;
	esac
	;;
test|redirect)
	MailFlag="- Redirected from $StudentMail"
	StudentMail="$DefaultMail"
	ResultMail="$DefaultMail"
	;;
esac
echo "$ResultMail"
}
case "$MoocMode" in
off)	;;
*)
	SenderMail=`DEFAULT_MAIL $SenderMail`
	AdminMail=`DEFAULT_MAIL $AdminMail`
	TestMail=`DEFAULT_MAIL $TestMail`
	case "$message_type" in
	-send_code)
		MessageSubject="[Mooc_ERP] Votre code personnel d'inscription aux cours"
		MessageText="Bonjour $StudentName,

	Vous avez soumis une demande de code personnel sur le serveur du cours ERP. Ce code personnel vous a ete attribue.

	Votre adresse mail utilisee pour votre identification : $StudentMail
	Votre code personnel : $Code
	Votre nom : $StudentName

	Ce code va vous permettre de creer votre espace personnel pour effectuer les exercices d'application du Mooc ERP en vous rendant sur la page :
	$MoocUrl

	Nous vous souhaitons pleine reussite dans votre apprentissage.

	"
		echo "$MessageText" > /tmp/mooc.message.$$.txt
		if [ -f /usr/local/bin/spool ] ; then
			/usr/local/bin/spool --push mail content:/tmp/mooc.message.$$.txt to:$StudentMail from:$SenderMail subject:$MessageSubject $MailFlag
			LOG_MESSAGE $LINENO "Send mail /usr/local/bin/spool --push mail content:/tmp/mooc.message.$$.txt to:$StudentMail from:$SenderMail subject:$MessageSubject $MailFlag"
		else
			MESSAGE -w "$LINENO| spool script is not installed, system mail utility is used instead"
			cat /tmp/mooc.message.$$.txt | mail -a "From: $SenderMail" -s "$MessageSubject $MailFlag" $StudentMail
		fi
		rm /tmp/mooc.message.$$.txt

		;;

	-database_ids)

		PARSING_DATABASE_LINE $DatabaseName
		GET_URL $MoocService
		DatabaseUrl="$ServiceUrl/web/login?db=$DatabaseName"
		MessageSubject="[Mooc_ERP] Vos identifiants d'acces a votre espace personnel de travail"
		MessageText="Bonjour $StudentName,

	Vous avez soumis une demande de mise a dispostion d'un espace personnel sur le serveur du Mooc ERP. Cet espace personnel a ete cree.

	Votre page de connexion personnelle : http://$DatabaseUrl
	Le nom de votre espace personnel (nom de la base de donnees) : $DatabaseName

	Si le lien ci-dessus n'est pas actif, copiez le dans votre navigateur.
	Si vous partagez votre poste avec d'autres utilisateurs, vous pouvez passer d'un espace personnel a l'autre sur la page
	http://$ServiceUrl/web/database/selector
	en y indiquant le nom de votre base de donnees.
	Les identifiants de connexion a votre espace personnel vous sont indiques par votre professeur $MoocAdminMail
	Celui-ci peut vous donner instruction d'utiliser les identifiants attribues par le systeme. Dans ce cas, utilisez:
	Login:		$DatabaseLoginId
	Mot de passe:	$DatabaseLoginPassword

	Nous vous souhaitons pleine reussite dans votre apprentissage.

	"
		#SenderMail="$MoocAdminMail"
		SenderMail=`DEFAULT_MAIL $SenderMail`

		echo "$MessageText" > /tmp/mooc.message.$$.txt
		if [ -f /usr/local/bin/spool ] ; then
			/usr/local/bin/spool --push mail content:/tmp/mooc.message.$$.txt to:$StudentMail from:$SenderMail subject:$MessageSubject $MailFlag
			LOG_MESSAGE $LINENO "Send mail /usr/local/bin/spool --push mail content:/tmp/mooc.message.$$.txt to:$StudentMail from:$SenderMail subject:$MessageSubject $MailFlag"
			/usr/local/bin/spool --push mail content:/tmp/mooc.message.$$.txt to:$MoocAdminMail from:$SenderMail subject:Inscription $MessageSubject $MailFlag
			LOG_MESSAGE $LINENO "Send mail /usr/local/bin/spool --push mail content:/tmp/mooc.message.$$.txt to:$MoocAdminMail from:$SenderMail subject:Inscription $MessageSubject $MailFlag"
		else
			MESSAGE -w "$LINENO| spool script is not installed, system mail utility is used instead"
			cat /tmp/mooc.message.$$.txt | mail -a "From: $SenderMail" -s "$MessageSubject $MailFlag" $StudentMail
			cat /tmp/mooc.message.$$.txt | mail -a "From: $SenderMail" -s "Inscription $MessageSubject $MailFlag" $MoocAdminMail
		fi
		rm /tmp/mooc.message.$$.txt
		;;
	-report)
		MessageSubject="[Mooc_ERP] Rapport sur le cours $MoocName du service $MoocService"
		#SenderMail="$MoocAdminMail"
		SenderMail=`DEFAULT_MAIL $SenderMail`
		cat $MoocReport > /tmp/mooc.message.$$.txt
		if [ -f /usr/local/bin/spool ] ; then
			/usr/local/bin/spool --push mail content:/tmp/mooc.message.$$.txt to:$MoocAdminMail from:$SenderMail subject:$MessageSubject
			LOG_MESSAGE $LINENO "Send mail /usr/local/bin/spool --push mail content:/tmp/mooc.message.$$.txt to:$MoocAdminMail from:$SenderMail subject:$MessageSubject"
		else
			MESSAGE -w "$LINENO| spool script is not installed, system mail utility is used instead"
			cat /tmp/mooc.message.$$.txt | mail -a "From: $SenderMail" -s "$MessageSubject $MailFlag" $MoocAdminMail
		fi
		rm /tmp/mooc.message.$$.txt
		;;
	esac
	;;
esac
}

#------------------------------------------------------------------------------
#
Option="$1"
shift
ActionParameters="$*"
#CHECK_CONFIGURATION
#LOG_MESSAGE $LINENO "$Option $*"
#LOG_MESSAGE -short "a"
case "$Option" in

#------------------------------------------------------------------------------
--code)
	less $MoocCodes
	;;

#------------------------------------------------------------------------------
--database)
	less $MoocDatabases
	;;
#------------------------------------------------------------------------------
--spool_code)
	#TR T_Code_mail Your personnal code is sent to : Vous allez recevoir votre code personnel par mail a l'adresse
	#TR T_Code_error You must indicate your mail address to receive your personnal code : Vous devez indiquer une adresse mail pour y recevoir votre code personnel
	StudentMail="$1"
	shift
	StudentName="$*"
	if [ ! -z "$StudentMail" ] ; then
		Code=`GET_CODE $StudentMail`
		CORRECT_CODE_ONLY $StudentMail $Code
		ACTION -send_code $StudentMail $Code 
		RETURN_MESSAGE "$T_Code_mail $StudentMail"
	else
		RETURN_MESSAGE "$T_Code_error"
	fi
	;;
#------------------------------------------------------------------------------
--spool_database_ids)
	#TR T_Ids_mail Connection ids to you training database are sent to your mail address : Vous allez recevoir vos identifiants de connexion a votre base de donnees d'entrainement par mail a l'adresse
	StudentMail="$1"
	Code="$2"
	MoocName="$3"
	MoocCode="$4"
	CORRECT_CODE_ONLY $StudentMail $Code
	CORRECT_MOOC_ONLY $MoocName $MoocCode
	ACTION -database_ids $StudentMail $Code $MoocName $MoocCode
	#unassigned databases : create if database doesn't exist
	RETURN_MESSAGE "$T_Ids_mail $StudentMail"
	;;
#------------------------------------------------------------------------------
--spool_resend_ids)
	#TR T_Ids_remail Connection ids are re-sent to all subscribers : Les identifiants de connexion sont renvoyes a tous les inscrits
	Service="$1"
	MoocName="$2"
	Code="$$"
	PARSING_MOOC_LINE $Service $MoocName
	ACTION -resend_ids $MoocService $MoocName
	RETURN_MESSAGE "$T_Ids_remail"
	;;
#------------------------------------------------------------------------------
--spool_report)
	Service="$1"
	MoocName="$2"
	Code="$$"
	PARSING_MOOC_LINE $Service $MoocName
	ACTION -report $MoocService $MoocName
	;;

--spool_replace_logins)
	#TR T_Patch_logins New connection ids are set for all databases of course : Les nouveaux identifiants de connexion sont modifies pour toutes les bases du cours
	LOG_MESSAGE $LINENO "--spool_replace_logins $*"
#sudo /usr/local/bin/mooc --spool_replace_logins tryton-50-sslp-173 d5 admin admin_5937_H0B5
	ExamService="$1"
	ExamMoocName="$2"
	ExamLogin="$3"
	ExamPassword="$4"
	Code="$$"
	PARSING_MOOC_LINE $ExamService $ExamMoocName
	ACTION -replace_logins $ExamService $ExamMoocName $ExamLogin $ExamPassword
	RETURN_MESSAGE "$T_Patch_logins $ExamMoocName/$ExamService"

	;;
--spool_restore_logins)
	#TR T_Restore_logins New connection ids are reset to original for all databases of course : Les nouveaux identifiants de connexion sont reinitialises pour toutes les bases du cours
	LOG_MESSAGE $LINENO "--spool_restore_logins $*"
#sudo /usr/local/bin/mooc --spool_replace_logins tryton-50-sslp-173 d5 admin admin_5937_H0B5
	ExamService="$1"
	ExamMoocName="$2"
	Code="$$"
	PARSING_MOOC_LINE $ExamService $ExamMoocName
	ACTION -restore_logins $ExamService $ExamMoocName
	RETURN_MESSAGE "$T_Restore_logins $ExamMoocName/$ExamService"
	;;
#------------------------------------------------------------------------------
--return_message)
	#TR T_return_message Your request has been submitted to the server. : Votre demande a ete soumise au serveur.
	echo "$T_return_message $*"
	;;

#------------------------------------------------------------------------------
--execute)
	case "$MoocMode" in
	on|test|redirect)
		#LOG_MESSAGE $LINENO "--execute `ls $MoocSpool`"
		for action in `ls $MoocSpool` ; do
			if [ -e "$MoocSpool/$action" ] ; then
				LOG_MESSAGE $LINENO "Mode is $MoocMode, spooled action $MoocSpool/$action is executed"
				$MoocSpool/$action
			fi
		done
		;;
	*|suspend|off)
		LOG_MESSAGE $LINENO "Mode is suspend, spooled actions are not executed"
		;;
	esac
	;;
#------------------------------------------------------------------------------
--background)
	if [ ! -z "`ls $MoocSpool`" ] ; then
		NOT_EXECUTING_ONLY
		nohup $0 --execute >> $MoocLogFile 2>&1 &
	fi
	;;
#------------------------------------------------------------------------------
--spool)
	ls -lh $MoocSpool
	;;
#------------------------------------------------------------------------------
--action)
	Command="$1"
	shift
	StudentMail="$1"
	ReportService="$1"
	ExamService="$1"
	shift
	Code="$1"
	MoocService="$1"
	ReportMoocName="$1"
	ExamMoocName="$1"
	shift
	StudentName="$*"
	MoocName="$1"
	ExamLogin="$1"
	shift
	MoocCode="$1"
	ExamPassword="$1"
	case "$Command" in
	-send_code)
		TEST_MODE
		MoocUrl=`/usr/local/bin/xoe --config -noblabla | grep -m 1 "^server_url:\|^erp_url:" | cut -f2`
		SEND_MAIL -send_code
		;;
	-database_ids)
		PARSING_MOOC_LINE $MoocName $MoocCode
		GET_DATABASE -predeclare
		GET_DATABASE -precreate
		PARSING_DATABASE_LINE $StudentMail
		GET_DATABASE -assign
		PARSING_DATABASE_LINE $StudentMail
		GET_DATABASE -create
		SEND_MAIL -database_ids
		;;
	-resend_ids)
		PARSING_MOOC_LINE $ReportService $ReportMoocName
		MOOC -resend_ids
		;;
	-report)
		PARSING_MOOC_LINE $ReportService $ReportMoocName
		MOOC -report
		SEND_MAIL -report
		;;
	-replace_logins)
		PARSING_MOOC_LINE $ExamService $ExamMoocName
		MOOC -replace_logins
		;;
	-restore_logins)
		PARSING_MOOC_LINE $ExamService $ExamMoocName
		MOOC -restore_logins
		;;
	esac
	;;
#------------------------------------------------------------------------------
--create)
	xoe_service_name="$1"
	mooc_name="$2"
	reference_database="$3"
	min_databases="$4"
	max_databases="$5"
	admin_mail="$6"
	if [ -z "$6" ] || [ ! -f $reference_database ] ; then
		#error
		echo "--create xoe_service_name mooc_name reference_database min-databases max-databases admin_mail : Missing parameter"
	else
		MOOC -new $*
	fi
	;;
#------------------------------------------------------------------------------
--open)
	xoe_service_name="$1"
	mooc_name="$2"
	if [ -z "$1" ] || [ -z "$2" ] ; then
		#error 
		echo "--open xoe_service_name mooc_name : Missing parameter"
	else
		MOOC -open $*
	fi
	;;
#------------------------------------------------------------------------------
--close)
	xoe_service_name="$1"
	mooc_name="$2"
	if [ -z "$1" ] || [ -z "$2" ] ; then
		#error 
		echo "--close xoe_service_name mooc_name : Missing parameter"
	else
		MOOC -close $*
	fi
	;;
#------------------------------------------------------------------------------
--cancel)
	xoe_service_name="$1"
	mooc_name="$2"
	if [ -z "$1" ] || [ -z "$2" ] ; then
		#error 
		echo "--cancel xoe_service_name mooc_name : Missing parameter"
	else
		MOOC -cancel $*
	fi
	;;
#------------------------------------------------------------------------------
--show_database)
	xoe_service_name="$1"
	mooc_name="$2"
	/usr/local/bin/xoe --service -cfg-database_list-set $xoe_service_name yes
	/usr/local/bin/xoe --restart $xoe_service_name
	;;
#------------------------------------------------------------------------------
--hide_database)
	xoe_service_name="$1"
	mooc_name="$2"
	/usr/local/bin/xoe --service -cfg-database_list-set $xoe_service_name no
	/usr/local/bin/xoe --restart $xoe_service_name
	;;

#------------------------------------------------------------------------------
--list)
	MOOC -list $1
	;;
#------------------------------------------------------------------------------
--html)
	MOOC -html $1
	;;
#------------------------------------------------------------------------------
--edit_mooc)
	MOOC -edit
	;;
#------------------------------------------------------------------------------
--edit_parameters)
	nano $MoocParametersConf
	;;
#------------------------------------------------------------------------------
--edit_database)
	nano $MoocDatabases
	;;
#------------------------------------------------------------------------------
--edit_code)
	nano $MoocCodes
	;;
#------------------------------------------------------------------------------
--version)
	echo "<!-- mooc version is $MoocVersion -->"
	;;
#------------------------------------------------------------------------------
--config_mooc)
	cat $MoocConfigFile
	;;
#------------------------------------------------------------------------------
--config_parameters)
	cat $0 | grep -m 1 -B 100 "#EndConfig" | grep -A 100 "#StartConfig"
	cat $MoocParametersConf
	;;
#------------------------------------------------------------------------------
--config_reset)
	rm $MoocParametersConf
	;;
#------------------------------------------------------------------------------
--log)
	cat -n $MoocLogFile
	;;
#------------------------------------------------------------------------------
--live)
	tail -f $MoocLogFile
	;;


#------------------------------------------------------------------------------
--mode)
	case "$1" in
	test|on|suspend|redirect|off)
		echo "$1" > $MoocModeFile
		;;
	*)
		echo "$MoocMode"
	esac
	;;
#------------------------------------------------------------------------------
--registration_form)
	#TR T_Management Management of your personnal training environment : Gestion de votre environnement pedagogique personnel
	#TR T_Step STEP : ETAPE
	#TR T_register CREATE YOUR ACCOUNT : CREEZ VOTRE COMPTE
	#TR T_Course Course name : Nom du cours
	#TR T_Personal_name Your name : Votre nom
	#TR T_Personal_mail Your mail address : Votre adresse mail
	#TR T_Get_mooc_code Send my personnal code by mail : Recevoir mon code personnel par mail
	#TR T_Mooc_db REGISTER TO COURSE : INSCRIPTION AU COURS
	#TR T_Mooc_code Course registration code : Code d'inscription au cours
	#TR T_Personal_code Your personal code : Votre code personnel
	#TR T_Get_mooc_ids Send my ids to connect to my private space : Recevoir les identifiants pour faire les exercices
	#TR T_Reset_mooc Reset everything: Tout recommencer depuis le debut
	#TR T_OR OR : OU
	#TR T_Mooc_note NOTE  : ATTENTION 
	#TR T_Mooc_comment If you don't receive a mail from the server, please chack your spam box. : Si vous ne recevez pas de mail, verifiez votre dossier SPAM.

	#afficher ce formulaire si mode= academie et il existe au moins un mooc

	case "$MoocMode" in
	test|redirect)
		test_comment="<strong> TEST EN COURS </strong>"
		;;
	esac
	case "$MoocMode" in
	on|suspend|test|redirect)
		GoeMode=`/usr/local/bin/goe --config_mode`
		case "$GoeMode" in
		education)
			OpenMoocs=`cat $MoocConfigFile | grep -v "#" | grep "	Open	" | cut -d: -f3 | sort -u | xargs`
			if [ ! -z "$OpenMoocs" ] ; then
				OpenMoocOptions=""
				for moocoption in $OpenMoocs ; do
					OpenMoocOptions="$OpenMoocOptions<option value=\"$moocoption\">$moocoption</option>"
				done
				MoocForm="<a href=\".\">Mooc ERP&nbsp;-&nbsp;$T_Management $test_comment</a><br/><br/>
			<div class=\"form\">
			<div class=\"mooc\">$T_Step 1 : $T_register</div>
		<div class=\"form\"><p><form method=POST action=\".\">
			<table>
			<tr><td>$T_Personal_name : </td><td><input type=text name=\"user_name\" style=\"cursor:pointer; width:400px; padding:5px 20px; margin: 5px; background-color: #eeeeee; border:solid 1px #999999;\" autofocus required ></td></tr>
			<tr><td>$T_Personal_mail : </td><td><input type=email name=\"email_address\" id=\"email_address\" style=\"cursor:pointer; width:400px; padding:5px 20px; margin: 5px; background-color: #eeeeee; border:solid 1px #999999;\" autofocus required ></td></tr>
		<tr><td></td><td><input type=\"submit\" name =\"personnal_id\" value=\"$T_Get_mooc_code\" style=\"cursor:pointer; padding:5px 20px; background-color: #336799; color: #eeeeee; font-weight:bold; border:dotted 1px #336799; border-radius:5px;\" /></td></tr></table><br/>
		</form></p></div>
			<div class=\"mooc\">$T_Step 2 : $T_Mooc_db</div>
		<div class=\"form\"><p><form method=POST action=\".\">
			<table>
			<tr><td>$T_Course : </td><td><select name=\"mooc_name\" style=\"cursor:pointer; width:250px; padding:5px 20px; margin: 5px; background-color: #eeeeee; border:solid 1px #999999;\" required >$OpenMoocOptions</select></td></tr>
			<tr><td>$T_Mooc_code : </td><td><input type=text name=\"mooc_code\" style=\"cursor:pointer; width:250px; padding:5px 20px; margin: 5px; background-color: #eeeeee; border:solid 1px #999999;\" required ></td></tr>
			<tr><td>$T_Personal_mail : </td><td><input type=email name=\"email_address\" id=\"email_address\" style=\"cursor:pointer; width:400px; padding:5px 20px; margin: 5px; background-color: #eeeeee; border:solid 1px #999999;\" autofocus required ><td></tr>
			<tr><td>$T_Personal_code : </td><td><input type=text name=\"personnal_code\" style=\"cursor:pointer; width:250px; padding:5px 20px; margin: 5px; background-color: #eeeeee; border:solid 1px #999999;\" required ></td></tr>
			<tr><td></td><td><input type=\"submit\" name =\"database_ids\" value=\"$T_Get_mooc_ids\" style=\"cursor:pointer; padding:5px 20px; background-color: #336799; color: #eeeeee; font-weight:bold; border:dotted 1px #336799; border-radius:5px;\" /></td></tr></table><br/>
			$T_Mooc_note : $T_Mooc_comment<br/><br/>
			</form></p></div>"
			else
				MoocForm="<br/>Pas de cours ouvert a l'inscription<br/>"
			fi
			;;
		*)
			MoocForm="
	<!-- Pas de gestion des cours en mode $GoeMode -->"
			;;
		esac
		;;
	*|off)
				MoocForm="
	<!-- la fonction de gestion des cours est arretee -->"
		;;
	esac
	echo -n "$MoocForm"
	exit 0
	;;

#------------------------------------------------------------------------------
--update)
	case `whoami` in
	root)
		cd /usr/local/bin
		script_source=`basename $0`
		panel_source=""
		css_source=""
		if [ ! -z "$1" ] ; then
			download_source="$MoocDownloadSource.$1"
		else
			download_source="$MoocDownloadSource"
		fi
		OLDVERSION=`$0 --version`
		if wget  $download_source -O $script_source.new_version ; then
			diff $script_source $script_source.new_version
			mv $script_source rescue.$script_source
			mv $script_source.new_version $script_source
			chmod 755 $script_source
			rm -f $MoocTranslationEn
			rm -f $MoocTranslationFr
			# upgrade code from V1 to v2
			if [ ! -f  $MoocConfigVersionFile ] ; then
				echo "$MoocVersion" > $MoocConfigVersionFile
			fi
			ConfigVersion=`cat $MoocConfigVersionFile | cut -b1`
			case "$ConfigVersion" in
			1)
				cd /usr/local/bin
				rm -f migmooc1-2.sh
				wget http://download.sisalp.net/panel/migmooc1-2.sh
				chmod 755 migmooc1-2.sh
				/usr/local/bin/migmooc1-2.sh
				# migmooc1-2.sh removes itself
				;;
			*)
				echo "$MoocVersion" > $MoocConfigVersionFile
				;;
			esac
		else
			echo "could not update $script_source software from $download_source"
		fi
		#first activation checks permissions and configuration
		NEWVERSION=`$0 --version`
		case "$NEWVERSION" in
		$OLDVERSION)
			echo "$0 is uptodate $NEWVERSION"
			;;
		*)
			echo "$0 downloaded new version from $download_source"
			echo "$NEWVERSION"
			;;
		esac
		;;
	*)
		echo "you must be root or sudo to succeed with $Option option"
		;;
	esac
	exit 0
	;;
#------------------------------------------------------------------------------
--help)
	echo "mooc : gestion des bases de donnees d'entrainement des utilisateurs du mooc
syntaxe :
mooc --command [parameters]

command :
--help

commands activated by internet trainee through internet panel:
=============================================================

--registration_form								# print registration form
--spool_code			mail_address personnal_name			#get personnal id code
--spool_database_ids		mail_address personal_code mooc_name mooc_code	#get database connexion ids
--return_message								#return mesage to web interface
previous commands generate scripts in $MoocSpool which invoke the following commands :		
--action -send_code		mail_address personnal_name			#execute action in spool : send code
--action -database_ids		mail_address personal_code mooc_name mooc_code	#execute action in spool : send ids
--action -report		xoe_service_name mooc_name			#execute action in spool : send report

commands activated by teacher through internet panel:
====================================================

--create		xoe_service_name mooc_name reference_database min-databases max-databases admin_mail
--spool_report		xoe_service_name mooc_name
--spool_resend_ids	xoe_service_name mooc_name
--open			xoe_service_name mooc_name
--close			xoe_service_name mooc_name
--cancel		xoe_service_name mooc_name
--show_database		xoe_service_name mooc_name
--hide_database		xoe_service_name mooc_name
--list			[xoe_service_name|mooc_name|mooc_code]
--html			[xoe_service_name|mooc_name|mooc_code]


All scripts of the spool are executed periodically by crontab via goe

--background		#execute spooled actions in background
--execute		#execute all scripts in the spool
--spool			#list waiting scripts in spool


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

--config_parameters	#prints hardcoded parameters and context files
--edit_parameters	#prints hardcoded parameters and context file
--config_mooc		#prints mooc configuration
--config_reset		#resets mooc configuration
--edit_mooc		#edit mooc configuration
--database		#print databases information
--edit_database		#edit databases information
--code			#print codes information
--edit_code	#edit codes information
--licence		#print licence
--live			#print last lines and follow mooc log file
--log			#print mooc log file
--mode [mode]		#set mooc execution mode (see below)
--report [-raz|-live]	#report of background actions
--update		#update mooc code
--version		#print mooc version


Mooc execution modes are used for online maintenance:
on		operationnal,
test		mail is sent to alternative test mail address, registration is simplified
suspend		background actions are delayed
redirect	all mail traffic is redirected to administrator's mail box
off		no mooc functionality

if mode is not indicated, mooc returns current mode

Mooc data are located in $MoocData
Format of database file :
Database:service_name:mooc_name:	database_name	login/password	:Student_mail:

Parameters are located in $MoocParametersConf, reset at update time
Local changes can be added permanently to $MoocPermanentConf

"
	cat $MoocConfigFile | grep -v "^#"
	$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: mooc is an original work from SISalp, http://sisalp.fr"
	;;
#------------------------------------------------------------------------------
*)
	echo "503 Option $Option is not supported by mooc command"
	$0 --help
	;;
#------------------------------------------------------------------------------
esac
exit 0
