#! /bin/bash
#------------------------------------------------------------------------------
#see licence at the end

SpoolVersion="1.0 - 25 mar 2026 rev 2 Last Update : `stat -c %z $0 | cut -d"." -f1`"
#============================CHANGE LOG=================================--)
##v	Change-log for spool
##v
#	nouvelles idees
#	
#
##v	version 1.0 25 mar 2026
##v	========================
##v	Combined with new MAIL script
##v	Defaults are revisited
##v	
##v
##v
##v
##v	version 0.1 13 nov 2018
##v	========================
##v	initial prototype
##v	xoe is the pusher
##v	cloe is the puller
##v
##v
##v
Date=`date +"%d/%m/%y-%H:%M:%S"`
CurrentUser=`whoami`
Machine=`hostname`
AllParameters="$*"
SpoolMode="unknown"
Pace="61"
VSDIR="/var/lib/vz/private"
UpdateScriptSource="http://download.sisalp.net/scripts/spool"
#------------------------------------------------------------------------------
#StartConfig
#------------------------------------------------------------------------------
#Adapt following values to your context
#
#spool parameters
#-------------------------------
SpoolDir="/usr/local/etc/spool"
SpoolPull="$SpoolDir/spool.pull"
SpoolDone="$SpoolDir/spool.done"
SpoolNotDone="$SpoolDir/spool.not.done"
SpoolAllowedUserFile="$SpoolDir/spool.alloweduser"
SpoolLoopPaceFile="$SpoolDir/spool.pace"
SpoolTest="service.client@sisalp.fr"
SpoolBccMonitoringFile="$SpoolDir/spool.bcc.monitoring"
SpoolAuthenticationKey="$SpoolDir/spool.authentication.key"
SpoolKnownKeys="$SpoolDir/spool.known.keys"
#-------------------------------
SpoolConfig="$SpoolDir/spool.$CurrentUser.conf"
SpoolPush="$SpoolDir/spool.$CurrentUser.push"
SpoolLogFile="/dev/null"
SpoolLogMode="/tmp/spool.log.mode"
SpoolModeFile="$SpoolDir/spool.$CurrentUser.mode"
SpoolLoopStatus="$SpoolDir/spool.$CurrentUser.status"
SpoolLoopSignature="$SpoolDir/spool.$CurrentUser.signature"
KnownActions="mail txt proxy file-export file-import service-export service-import"
LogShorts="Log short codes meaning
: Check Loop is looping
/ New loop execution
L Spool is local in a vserver
l Spool is local pusher mode
. Collect content
+ Pull spool actions
M Send mail
P Proxy action
i File import
x File export
I Service import
X Service export"
#------------------------------------------------------------------------------
#EndConfig
#------------------------------------------------------------------------------


#------------------------------------------------------------------------------
#Fonctions
#------------------------------------------------------------------------------
MESSAGE ()
#------------------------------------------------------------------------------
{
case "$1" in
-on)
	if [ ! -f $SpoolLogMode ] ; then
		echo "SpoolLogFile=\"/tmp/spool.log\""		> $SpoolLogMode
		SpoolLogFile="/tmp/spool.log"
		echo "$HOSTNAME|spool|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|Log mode is set to on" >> $SpoolLogFile
	fi
	;;
-short)
	shift
	echo -n "$*" >> $SpoolLogFile
	echo "return" > $SpoolLogFile.return
	chmod 700 $SpoolLogFile.return
	;;
-l)
	shift
	if [ -f $SpoolLogFile.return ] ; then
		rm $SpoolLogFile.return
		echo "" >> $SpoolLogFile
	fi
	echo "$HOSTNAME|spool|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$*" >> $SpoolLogFile
	;;
*)
	if [ -f $SpoolLogFile.return ] ; then
		rm $SpoolLogFile.return
		echo "" >> $SpoolLogFile
	fi
	echo "$HOSTNAME|spool|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$*" >> $SpoolLogFile
	echo "$HOSTNAME|spool|`date +%A_%x-%H:%M:%S:%3N`|INFO |$CurrentUser|$$|$*"
	;;
esac
}
#-------------------------------------------------------------------------
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}"
}
#------------------------------------------------------------------------------
CHECK_ACTION ()
#------------------------------------------------------------------------------
{
actiontype="${1%/}"
if [ -z "$actiontype" ] ; then
	actiontype="None"
fi
case " $KnownActions " in
*' '$actiontype' '*)
	;;
*)
	echo "Type of action in $KnownActions is mandatory, it is $actiontype"
	exit 1
	;;
esac
}
#------------------------------------------------------------------------------
CHECK_SETUP ()
#------------------------------------------------------------------------------
{
AllowedUser="root"
if cat /etc/group | grep -q "sisalpuser" ; then
	AllowedUser="sisalpuser"
fi
if [ -f $SpoolAllowedUserFile ] ; then
	AllowedUser=`cat $SpoolAllowedUserFile`
fi
for directory in $SpoolDir ; do
	if [ ! -d $directory ] ; then
		mkdir -p $directory
		chmod 777 $directory
	fi
done
for directory in $SpoolPull $SpoolDone $SpoolNotDone ; do
	if [ ! -d $directory ] ; then
		mkdir --parent $directory
		chmod 777 $directory
	fi
done
if [ ! -f $SpoolAuthenticationKey ] ; then
	NEW_PASSWORD 12 9 > $SpoolAuthenticationKey
	chmod 644 $SpoolAuthenticationKey
fi
if [ -f $SpoolLoopPaceFile ] ; then
	Pace=`cat $SpoolLoopPaceFile`
else
	echo "$Pace" > $SpoolLoopPaceFile
fi
if [ -f $SpoolBccMonitoringFile ] ; then
	BccMonitoring=`cat $SpoolBccMonitoringFile | grep -v "#" | xargs`
else
	echo "#Bcc copy address for all sent mails" > $SpoolBccMonitoringFile
fi
case "$CurrentUser" in
root)
	#echo "AllowedUser is $AllowedUser"
	chown -R root:$AllowedUser $SpoolDir
	chmod -R 770 $SpoolDir
	;;
esac
for directory in $SpoolPush ; do
	if [ ! -d $directory ] ; then
		mkdir -p $directory
		chmod 700 $directory
	fi
done
if [ -f $SpoolModeFile ] ; then
	SpoolMode=`cat $SpoolModeFile`
fi
#echo "$LINENO mode is $SpoolMode, file is $SpoolModeFile `cat $SpoolModeFile`"
if [ -f $SpoolConfig ] ; then
	. $SpoolConfig
else
	cat $0 | grep -m 1 -B 100 "#EndConfig" | grep -A 100 "#StartConfig" > $SpoolConfig
	chmod 700 $SpoolConfig
fi
AuthenticationKey=`cat $SpoolAuthenticationKey`
if [ -f $SpoolLogMode ] ; then
	. $SpoolLogMode
fi
}
#------------------------------------------------------------------------------
CHECK_SETUP

#-------------------------------------------------------------------------
CHECK_LOOP_OPTION ()
#-------------------------------------------------------------------------
{
co_option="$1"
OptionList=" `cat $0 | grep "^--" | grep ")$" | cut -d")" -f1 | cut -d"-" -f3- | xargs` `cat $0 | grep "^--" | grep ")$" | cut -d")" -f1 | xargs` "
case "$OptionList" in
*' '$co_option' '*)
	LoopOption="$co_option"
	;;
*)
	MESSAGE $LINENO "Parameter $co_option is not a valid spool command for $Option, fallback value pull will be used instead"
	LoopOption="pull"
	;;
esac
}
#------------------------------------------------------------------------------
LOOP_SIGNATURE ()
#------------------------------------------------------------------------------
{
	if [ ! -f "$SpoolLoopSignature" ] ; then
		NEW_PASSWORD 12 > $SpoolLoopSignature
	fi
	LoopSignature=`cat $SpoolLoopSignature`
}
#------------------------------------------------------------------------------
LOOP_FOREVER ()
#------------------------------------------------------------------------------
{
	MESSAGE $LINENO "Starting execution loop forever, signature is $LoopSignature, use $0 --stop to break this loop"
	while [ ! -f  $SpoolLoopStatus ] ; do
		MESSAGE -short "/"
		#MESSAGE $LINENO "action is $0 $LoopOption $ActionParameters"
		$0 $LoopOption $ActionParameters
		sleep $Pace
	done
	MESSAGE $LINENO "Execution loop is stopped, use /usr/local/bin/spool --start to let --background create this loop next time"
}
#------------------------------------------------------------------------------
NOT_LOOPING_ONLY ()
#------------------------------------------------------------------------------
{
	LOOP_SIGNATURE
	runningprocesses=`/bin/ps axo pid,cmd`
	if echo "$runningprocesses" | grep -q "$LoopSignature" ; then
		MESSAGE -short ":"
		exit 0
	fi
}
#------------------------------------------------------------------------------
STOP_LOOP ()
#------------------------------------------------------------------------------
{
	LOOP_SIGNATURE
	runningprocesses=`/bin/ps axo pid,cmd`
	if echo "$runningprocesses" | grep -q "$LoopSignature" ; then
		MESSAGE $LINENO "Process loop is invited to stop"
	else
		MESSAGE $LINENO "Process loop is already stopped"
	fi
	echo "please stop looping" >  $SpoolLoopStatus
	MESSAGE $LINENO "spool loop is invited to stop at next iteration"
}
#------------------------------------------------------------------------------
UNSTOP_LOOP ()
#------------------------------------------------------------------------------
{
	rm -f  $SpoolLoopStatus
	MESSAGE $LINENO "spool loop can be restarted"
}
#------------------------------------------------------------------------------
ADMIN_MESSAGE ()
#------------------------------------------------------------------------------
{
am_option="$1"
case "$am_option" in
-authenticate)
	for bccto in $BccMonitoring ; do
		MESSAGE $LINENO "ActionAuthenticationKey $ActionAuthenticationKey is added to $SpoolKnownKeys, Adding spool authentication key on $Machine $bccto"
	done
	;;
esac
}
#------------------------------------------------------------------------------
CHECK_AUTHENTIC ()
#------------------------------------------------------------------------------
{
#today : no control, but may change over time.
if [ ! -f $SpoolKnownKeys ] ; then
	echo "#This file created on `date` by $0 $Option $ActionParameters" > $SpoolKnownKeys
fi
if ! cat $SpoolKnownKeys | grep "^$ActionAuthenticationKey$" >/dev/null 2>&1 ; then
	echo "$ActionAuthenticationKey" >> $SpoolKnownKeys
	MESSAGE $LINENO "ActionAuthenticationKey $ActionAuthenticationKey is added to $SpoolKnownKeys"
	ADMIN_MESSAGE -authenticate
#else 
	#MESSAGE $LINENO "ActionAuthenticationKey $ActionAuthenticationKey is already known"
fi
}
#------------------------------------------------------------------------------
GET_ACTION_OPTIONS ()
#------------------------------------------------------------------------------
{
#MESSAGE $LINENO "GET_ACTION_OPTIONS ActionType $ActionType"
echo "#! /bin/bash" > /tmp/spool.get_options.$$.sh
echo "# parsing action parameters $TicketParameters $SpoolParameters"  >> /tmp/spool.get_options.$$.sh
echo "echo -n \""  >> /tmp/spool.get_options.$$.sh
#MESSAGE $LINENO "parameter in  ticket $TicketParameters arguments $SpoolParameters"
for parameter in $TicketParameters $SpoolParameters ; do
	#MESSAGE $LINENO "parameter --$parameter"
	case "$parameter" in
	*:*)
		#MESSAGE $LINENO "parameter --$parameter--"
		echo "\""  >> /tmp/spool.get_options.$$.sh
		parameterkey=`echo "$parameter" | cut -d: -f1`
		parametervalue=`echo "$parameter" | cut -d: -f2`
		echo -n "spool_$parameterkey=\"$parametervalue" >> /tmp/spool.get_options.$$.sh
		;;
	*)
		echo -n " $parameter" >> /tmp/spool.get_options.$$.sh
		;;
	esac
done
echo "\"" >> /tmp/spool.get_options.$$.sh
#cat /tmp/spool.get_options.$$.sh
. /tmp/spool.get_options.$$.sh
rm -f /tmp/spool.get_options.$$.sh
SubjectFlag=""
case "$SpoolMode" in
test)
	SubjectFlag=" - Redirected from $spool_to to $SpoolTest"
	spool_to="$SpoolTest"
	;;
esac
#MailOptions="content:$spool_content attach:$spool_attach to:$spool_to cc:$spool_cc bcc:$spool_bcc from:$spool_from subject:$spool_subject"
MailOptions="$TicketParameters $SpoolParameters"
#MESSAGE $LINENO "mail options: $MailOptions"
}
#------------------------------------------------------------------------------
PUSH ()
#------------------------------------------------------------------------------
{
#MESSAGE -l $LINENO "PUSH $*"
MessageKey="`NEW_PASSWORD 12`.$AuthenticationKey.$Machine.$CurrentUser"
MESSAGE $LINENO "action $ActionType.$MessageKey.action is spooled because mode is $SpoolMode"
cd $SpoolPush
GET_ACTION_OPTIONS
#MESSAGE $LINENO "content $spool_content attach $spool_attach"
echo "$MailOptions" > $SpoolPush/$ActionType.$MessageKey.action
if [ -f "$spool_content" ] ; then
	#MESSAGE $LINENO "content $spool_content moved to content:$ActionType.$MessageKey.action.content"
	cp -a $spool_content $SpoolPush/$ActionType.$MessageKey.action.content
	echo "content:$ActionType.$MessageKey.action.content" >> $SpoolPush/$ActionType.$MessageKey.action
fi
if [ -f "$spool_attach" ] ; then
	#MESSAGE $LINENO "attach $spool_attach moved to attach:$ActionType.$MessageKey.action.attach"
	cp -a $spool_attach $SpoolPush/$ActionType.$MessageKey.action.attach
	echo "attach:$ActionType.$MessageKey.action.attach" >> $SpoolPush/$ActionType.$MessageKey.action
fi
#MESSAGE $LINENO "mail options pushed in action ticket:
#`cat $SpoolPush/$ActionType.$MessageKey.action`"
#MESSAGE $LINENO "mail content:
#`cat $SpoolPush/$ActionType.$MessageKey.action.content`"
#MESSAGE $LINENO "mail attach:
#`cat $SpoolPush/$ActionType.$MessageKey.action.attach`"
}
#------------------------------------------------------------------------------
COLLECT_SPOOL ()
#------------------------------------------------------------------------------
{
#MESSAGE $LINENO "COLLECT_SPOOL $*"
#Read Spool List
if [ -e $VSDIR ] ; then
	SpoolCollect=""
	if [ -z "$VserverList" ] ; then
		VserverList=`ls $VSDIR`
	fi
	ButList=" $ButList "
	for vserverid in $VserverList ; do
		case "$ButList" in
		*' '$vserverid' '*)
			;;
		*)
			SpoolCollect="$SpoolCollect $VSDIR/$vserverid$SpoolDir"
			;;
		esac
	done
else
	SpoolCollect="$SpoolDir"
	MESSAGE -short "L"
fi
#MESSAGE $LINENO "Locations are $SpoolCollect"
for spooldir in $SpoolCollect ; do
	#MESSAGE $LINENO "Looking into $spooldir"
	if [ -d $spooldir ] ; then
		PushList=`ls -d $spooldir/*.push | xargs`
	else
		PushList=""
	fi
	#MESSAGE $LINENO "push directories found are $PushList"
	for pushdir in $PushList ; do
		#MESSAGE $LINENO "Checking into $pushdir"
		if [ -w $pushdir ] ; then
			case "$SpoolMode" in
			puller|local|unknown)
				mv $pushdir/* $SpoolPull 2>/dev/null
				MESSAGE -short "."
				#MESSAGE -l $LINENO "Move $pushdir/* contents to $SpoolPull"
				;;
			test|pusher|*)
				cp $pushdir/* $SpoolPull 2>/dev/null
				MESSAGE -short "l"
				#MESSAGE -l $LINENO "Copy $pushdir/* contents to $SpoolPull"
				;;
			esac
		else
			MESSAGE $LINENO "No write rights on $pushdir, this directory is discarded"
		fi
	done
done
}
#------------------------------------------------------------------------------
PULL ()
#------------------------------------------------------------------------------
{
#MESSAGE $LINENO "PULL ActionType $ActionType"
cd $SpoolPull
GET_ACTION_OPTIONS
case "$ActionType" in
mail)
	#MESSAGE $LINENO "/usr/local/bin/MAIL --send $MailOptions"
	MESSAGE -short "M"
	/usr/local/bin/MAIL --send $MailOptions
	ActionResult="done"
	;;
proxy)
	MESSAGE -short "P"
	case "$SpoolMode" in
	puller|local|unknown)
		#--push	proxy [service:name_of_service]
		if [ ! -z "$spool_service" ] ; then
			cloe --proxy -collect -cert $ActionMachine $spool_service
		else
			cloe --proxy -collect -cert -reset $ActionMachine
		fi
		ActionResult="done"
		;;
	test|pusher|*)
		echo "$LINENO proxy parameters cloe --proxy $spool_collect $spool_vserver $spool_service"
		ActionResult="todo"
		;;
	esac
	;;
file-export)
	MESSAGE -short "x"
	case "$SpoolMode" in
	puller|local|unknown)
		#--push	file-export
		MESSAGE $LINENO "cloe --vserver -file-copy $ActionMachine $spool_file $spool_to"
		#cloe --vserver -file-copy $ActionMachine $spool_file $spool_to
		ActionResult="done"
		;;
	test|pusher|*)
		echo "$LINENO service_move parameters cloe --file-copy $ActionMachine $spool_file $spool_to"
		ActionResult="todo"
		;;
	esac
	;;
file-import)
	MESSAGE -short "i"
	case "$SpoolMode" in
	puller|local|unknown)
		#--push	file-import
		MESSAGE $LINENO "cloe --vserver -file-copy $spool_from $spool_file $ActionMachine"
		#cloe --vserver -file-copy $spool_from $spool_file $ActionMachine
		ActionResult="done"
		;;
	test|pusher|*)
		echo "$LINENO service_move parameters cloe --file-copy $spool_from $spool_file $ActionMachine"
		ActionResult="todo"
		;;
	esac
	;;
service-export)
	MESSAGE -short "X"
	case "$SpoolMode" in
	puller|local|unknown)
		#--push	service-export
		MESSAGE $LINENO "cloe --vserver -service-replicate $ActionMachine $spool_service $spool_to"
		cloe --vserver -service-replicate $ActionMachine $spool_service $spool_to
		ActionResult="done"
		;;
	test|pusher|*)
		echo "$LINENO service_move parameters cloe --service-replicate $ActionMachine $spool_service $spool_to"
		ActionResult="todo"
		;;
	esac
	;;
service-import)
	MESSAGE -short "I"
	case "$SpoolMode" in
	puller|local|unknown)
		#--push	service-import
		MESSAGE $LINENO "cloe --vserver -service-replicate $spool_from $spool_service $ActionMachine"
		cloe --vserver -service-replicate $spool_from $spool_service $ActionMachine
		ActionResult="done"
		;;
	test|pusher|*)
		echo "$LINENO service_move parameters cloe --service-replicate $spool_from $spool_service $ActionMachine"
		ActionResult="todo"
		;;
	esac
	;;
*)
	MESSAGE $LINENO "generic spool action $ActionType for $spool_content is not supported"
	;;
esac
}

#------------------------------------------------------------------------------
UPDATE ()
#------------------------------------------------------------------------------
{
#echo "$LINENO UPDATE $*"
OldVersion=`$0 --version -noblabla`
if [ ! -z "$1" ] ; then
	cd /usr/local/bin
	rm -f $0.new-version
	if [ ! -z "$2" ] ; then
		source="$1.$2"
	else
		source="$1"
	fi
	if wget -q $source -O $0.new-version ; then
		NewKey=`md5sum $0.new-version | cut -d" " -f1`
		OldKey=`md5sum $0 | cut -d" " -f1`
		case "$NewKey" in
		$OldKey)
			echo "$0 is uptodate"
			rm -f $0.new-version
			;;
		*)
			echo "$OldVersion"
			diff $0 $0.new-version
			rm -f $0
			mv $0.new-version $0
			chmod 755 $0
			$0 --version
			echo "$0 is updated from $source"
			;;
		esac
	else
		rm -f $0.new-version
		echo "$LINENO Failed to download $0 from $source"
		exit 1
	fi
else
	MESSAGE "$LINENO download $0 code source is not configured"
fi
}
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
#this code is tabbed to be out of reach of check loop option
	case "$1" in
	--*)
		Option="$1"
		;;
	*)
		Option="--$1"
		;;
	esac

#------------------------------------------------------------------------------
shift
ActionParameters="$*"
OptionList=" `cat $0 | grep "^--" | grep ")$" | cut -d")" -f1 | cut -d"-" -f3- | xargs` "
#MESSAGE -l $LINENO "spool started  $Option $*"
case "$Option" in
#------------------------------------------------------------------------------
--background)
	NOT_LOOPING_ONLY
	LoopOption="$1"
	shift
	ActionParameters="$*"
	CHECK_LOOP_OPTION $LoopOption pull
	nohup $0 --loop_forever $LoopSignature $LoopOption $ActionParameters 2>$SpoolLogFile &
	MESSAGE $LINENO "spool loop is started --loop_forever $LoopSignature $LoopOption $ActionParameters"
	;;
#------------------------------------------------------------------------------
--loop_forever)
	LoopSignature="$1"
	shift
	LoopOption="$1"
	shift
	ActionParameters="$*"
	CHECK_LOOP_OPTION $LoopOption pull
	LOOP_FOREVER $LoopOption $ActionParameters
	;;
#------------------------------------------------------------------------------
--loop_status)
	LOOP_SIGNATURE
	runningprocesses=`/bin/ps axo pid,cmd`
	if echo "$runningprocesses" | grep -q "$LoopSignature" ; then
		echo "spool loop status: loop is looping"
	else
		echo "spool loop status: no loop is looping"
	fi
	if [ ! -f  $SpoolLoopStatus ] ; then
		echo "spool loop status: loop can be reactivated anytime, consider --background option"
	else
		echo "spool loop status: loop cannot be reactivated, consider --start option"
	fi
	echo "spool loop process signature: $LoopSignature"
	;;
#------------------------------------------------------------------------------
--pull)
	case "$CurrentUser" in
	$AllowedUser|root)
		VserverList=`echo "$*" | cut -d! -f1`
		ButList=`echo \"$*\" | cut -d! -f2`
		COLLECT_SPOOL
		cd $SpoolPull
		ToDoPull=`ls $SpoolPull | xargs`
		MESSAGE -short "+"
		#MESSAGE $LINENO "liste `pwd` des tickets d'action $ToDoPull"
		for ActionTicket in $ToDoPull ; do
			if [ -f $ActionTicket ] ; then
				ActionResult="todo"
				ActionType=`echo "$ActionTicket" | cut -d. -f1`
				ActionKey=`echo "$ActionTicket" | cut -d. -f2`
				ActionAuthenticationKey=`echo "$ActionTicket" | cut -d. -f3-5`
				ActionMachine=`echo "$ActionTicket" | cut -d. -f4`
				ActionUser=`echo "$ActionTicket" | cut -d. -f5`
				TicketParameters=`cat $ActionTicket | xargs`
				#MESSAGE $LINENO "liste TicketParameters `cat $ActionTicket | xargs`"
				CHECK_AUTHENTIC
				PULL
				case "$ActionResult" in
				done)
					#MOVE $SpoolPull/${ActionTicket}* $SpoolDone
					mv $SpoolPull/${ActionTicket}* $SpoolDone
					;;
				failed|todo)
					mv $SpoolPull/${ActionTicket}* $SpoolNotDone
					;;
				esac
			fi
		done
		;;
	*)
		MESSAGE "$LINENO you must be $AllowedUser or root to pull ActionTickets from spool"
		;;
	esac
	;;
#------------------------------------------------------------------------------
--push)
	#MESSAGE -l "$LINENO push option $* SpoolMode $SpoolMode"
	ActionType="$1"
	shift
	CHECK_ACTION $ActionType
	TicketParameters=""
	SpoolParameters="$*"
	case "$SpoolMode" in
	pusher|test)
		PUSH
		;;
	local|puller|unknown|*)
		MESSAGE $LINENO "action is done or message is sent because mode is $SpoolMode"
		PULL
		;;
	esac
	;;
#------------------------------------------------------------------------------
--start)
	UNSTOP_LOOP
	;;
#------------------------------------------------------------------------------
--stop)
	STOP_LOOP
	;;
#------------------------------------------------------------------------------
--version|-v)
	echo "<!--spool version is $SpoolVersion -->"
	;;
#-------------------------------------------------------------------------
--change|-c)
	cat $0 | grep "^##v" | cut -b 4-
	exit 0
	;;
#------------------------------------------------------------------------------
--config)
	echo "Spool default configuration"
	cat $0 | grep -m 1 -B 100 "#EndConfig" | grep -A 100 "#StartConfig"
	echo "Spool specific configuration $SpoolConfig for $CurrentUser"
	cat $SpoolConfig
	;;

#------------------------------------------------------------------------------
--config_reset)
	rm -f $SpoolConfig
	;;
#------------------------------------------------------------------------------
--log)
	MESSAGE -on
	echo "$LogShorts"
	cat -n $SpoolLogFile
	;;
#------------------------------------------------------------------------------
--live)
	MESSAGE -on
	echo "$LogShorts"
	tail -f $SpoolLogFile
	;;
#------------------------------------------------------------------------------
--mode)
	case "$1" in
	test|local|pusher|puller)
		echo "$1" > $SpoolModeFile
		;;
	*)
		echo "$SpoolMode"
		;;
	esac
	;;
#------------------------------------------------------------------------------
--allow)
	#echo "allowed file is $SpoolAllowedUserFile"
	case `whoami` in
	root)
		if [ ! -z "$1" ] && cat /etc/group | grep "^$1:" > /dev/null ; then
			echo "$1" > $SpoolAllowedUserFile
		else
			echo "$AllowedUser"
		fi
		;;
	*)
		if [ ! -z "$1" ] ; then
			echo "You must be root to set allowed user"
		else
			echo "$AllowedUser"
		fi
		;;
	esac
	;;
#------------------------------------------------------------------------------
--pace)
	case `whoami` in
	root)
		if [ ! -z "$1" ] ; then
			echo "$1" > $SpoolLoopPaceFile
		else
			echo "$Pace"
		fi
		;;
	*)
		if [ ! -z "$1" ] ; then
			echo "You must be root to set allowed user"
		else
			echo "$Pace"
		fi
		;;
	esac
	;;
#------------------------------------------------------------------------------
--update|-u)
	Release="$1"
	#MESSAGE -l "$LINENO spool script --update : $UpdateScriptSource"
	UPDATE $UpdateScriptSource $Release
	$0 --config_reset
	;;
#-------------------------------------------------------------------------
--rescue|-r)
	echo "#! /bin/bash
	# $TODAY_DATE --- created by $0 $COMMANDE $* - version $MYVERSION revision $REVISION

	echo \"Commande : wget -q $UpdateScriptSource\"
	mv /usr/local/bin/spool /usr/local/bin/spool.old-version
	if wget -q $UpdateScriptSource ; then
		diff /usr/local/bin/spool.old-version /usr/local/bin/spool
		chmod 755 /usr/local/bin/spool
	else
		echo \"ERROR : Failed to download spool new version\"
	fi
	/usr/local/bin/spool --version
	exit 0
	"	> /usr/local/bin/rescue.spool
	chmod 755 /usr/local/bin/rescue.spool
	MESSAGE -v "$LINENO| Command /usr/local/bin/rescue.spool is installed"
	exit 0
	;;	
#------------------------------------------------------------------------------
--help|-h|--?|-?)
	echo "spool : Execute actions safely through a protected relay server
syntax :
spool --command [parameters]
-- can be ommited

command :
--help

spool management:
================


--push	action_type list_of[key:value]
		first parameter is action type, every action type is associated to default values, mail and proxy are available
		optional parameters key:value are superceeding directives to defaults

--push	mail [content:pushed.txt] [attach:path_to_file] [to:addr@dom] [cc:toto@dom] [bcc:tata@dom] [from:addr@dom] [subject:text and text]
		if action_type is mail, a mail content and its options are pushed to spool to be sent by --pull
		if mode is pusher or test, stores pushed.txt and parameters as action ticket in push_spool directory
		if mode is local, puller or unknown, send the message through local smtp server

--push	proxy [service:name_of_service]
		if action type is proxy (default), a cloe proxy command is executed to update proxy redirections
		if mode is pusher or test, stores action in push_spool directory

--push file-export [file:path_to_file] [to:target_vserver]
		if action type is file-export, a cloe --vserver -file-export command is executed to move a service to a target vserver
		if mode is pusher or test, stores action in push_spool directory

--push file-import [file:path_to_file] [to:target_vserver]
		if action type is file-import, a cloe --vserver -file-import command is executed to move a service to a target vserver
		if mode is pusher or test, stores action in push_spool directory

--push service-export [service:name_of_service] [to:target_vserver]
		if action type is service-export, a cloe --vserver -service-export command is executed to move a service to a target vserver
		if mode is pusher or test, stores action in push_spool directory

--push service-import [service:name_of_service] [from:origin_vserver]
		if action type is service-import, a cloe --vserver -service-import command is executed to move a service from an origin vserver
		if mode is pusher or test, stores action in push_spool directory

--pull	[list of vserver_ids] [! list of excluded vserver_ids]
		collect actions from push_spool directories and execute actions according to parameters in the title and inside the action file

details:
=======


Builtin values are :
No built-in values

Spool execution modes are used for spool synchronisation:
test		commands on services are not executed and mail is sent to alternative test mail address
local		service is local,
pusher		service is remote,
puller		service executes pushed actions
unknown		equivalent to local, is the default value
these default values are often set by other scripts.
if mode is not indicated, spool --mode returns current mode

background operations:
=====================

All pushed files of the spool are usually operated periodically
by --pull in a loop activated or re-activated by crontab

--background	[spool_command] [list of vserver_ids] [! list of excluded vserver_ids]
		check the loop is active else restart it by --loop_forever signature
		spool_command is any valid spool command, pull is the default
--loop_forever	signature [spool_command] [list of vserver_ids] [! list of excluded vserver_ids]
		loop forever on spool command
		signature is a process identifier, its value is printed below
		loop frequency is set by Pace parameter of the configuration of root user: $Pace s
--start		#let the background loop restart
--stop		#stop the next background loop
--loop_status	#print information about loop process

get information:
===============

--live					#print last lines and follow spool log file
--log					#print spool log file
					#first use enables log functionality
$LogShorts

commands for configuration:
===========================

--allow [user_name]					#set user allowed to collect and pull instead of root (default) or print it
--config						#prints hardcoded parameters and context files
--config_reset						#resets configuration to default
--defaults mail|proxy|service_move|txt [default parameters]	#set default parameters (see below) or print them
--defaults_reset mail|proxy|service_move|txt		#reset mail default parameters
--mode [mode]						#set spool execution mode (see below) or print it
--pace [nn]						#set nap time between two loop ierations or print it
these values are often set by other scripts upon context (xoe, cloe, hoe scripts by SISalp).

documentation and version management:
====================================

--change				#print change log
--licence				#print licence
--rescue				#create a rescue.spool command for broken update
--update [release_number]		#download a new version of this script
--version				#print spool version and revision

configuration files:
===================

Parameters defined per user are located in $SpoolConfig configuration file
"
	cat  $SpoolConfig
	echo "current mode in use: $SpoolMode"
	echo "user allowed to send messages is $AllowedUser "
	echo "current interval between pull/send in background loop : $Pace s"
	$0 --loop_status
	$0 --version
	;;
#------------------------------------------------------------------------------
--licence|-l)
	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
2018-today: spool is an original work from SISalp, https://sisalp.fr"
	;;
#------------------------------------------------------------------------------
*)
	echo "503 Option $Option is not supported by spool command"
	$0 --help
	;;
#------------------------------------------------------------------------------
esac
exit 0
