#!/bin/sh

#
# CONFIG VARIABLES
##################
HELPERPATH=/usr/lib/send_infra

#
# FUNCTION DEFINITION
#####################
source $HELPERPATH/.functions
source /etc/sysconfig

############
### MAIN ###
############
: "Overwrite configuration varibles"
####################################
# timeout in minutes
timeout_min=5
# timeout in seconds
timeout=`expr $timeout_min \* 120`



: "PROCESSING COMMAND LINE"
###########################

RET=0
while [ $# -ne 0 ]; do
    case "$1" in 
        -h|--help) : "help"
            help
            exit $RET
        ;;
        -w|--wait) : "will wait"
            WAIT=1
        ;;
      	*) : "none"
            
            shift $#
        ;;
    esac
    shift
done

: "Call command"
################
echo "RPMS_CHANGES"
echo "Stopping DMconfig"
/etc/init.d/dmconfig stop 2>/dev/null
echo "Cleaning DMconfig"
rm -rf /config/dm/.chksum* 2>/dev/null
if [ -e /tmp/rpms_changes ]; then
	echo "Starting applicationManager (if not started)"
	/etc/init.d/applicationManager launch 
	
	echo "Notifying ApplicationManager"
	res=`dbus-send --print-reply --dest=com.alcatel.ICTouch.ApplicationManagerService /ApplicationManager com.alcatel.ICTouch.ICTInterface.rpmsChanges 2>/dev/null`
	callret=$?
	if [ $callret -eq 1 ]; then
		echo "WARNING : Failed to call ApplicationManager : Datas can be lost" >&2
		RET=2
	else
		nb_changes=`echo $res|sed 's/^.* int32 //'`
		echo "Nb changes = $nb_changes"
		if [ $nb_changes != "0" ]; then
			echo "Managing downgrades and removals"
			echo "Waiting end of treatment"
			cpt=0
			while [[ $cpt -le $timeout -a -e /tmp/rpms_changes ]]
    			do
				usleep 500000
				cpt=`expr $cpt + 1`    	
    			done
			if [[ ! -e /tmp/rpms_changes ]]; then
				echo "Migration done in $cpt sec"
			else
				echo "Migration timeout ($timeout sec): Datas can be lost" >&2
				rm /tmp/rpms_changes
				exit 3
			fi
		else 
			echo "No changes"
		fi
		RET=0
	fi 
else
	echo "WARNING : No /tmp/rpms_changes file" >&2
	RET=1
fi
echo "Stopping applicationManager"
/etc/init.d/applicationManager stop


exit $RET
