#!/bin/sh
# Re-written for Fatdog64 702
# Use Xdialog instead of yafsplash, and do a direct save if ram-save 
# daemon is not running (instead of hanging)


### configuration
APPTITLE="save2flash"
F_SNAPMERGE_REQUEST=/tmp/snapmergepuppy.request	# /etc/init.d/20-ram-save
. $BOOTSTATE_PATH

### helpers
#$1-text
info() {
	if [ "$DISPLAY" ]; then
		Xdialog --title "$APPTITLE" --infobox "$1" 0 0 10000
	else
		echo "$1"
	fi
}

#$1-text
bginfo() {
	if [ "$DISPLAY" ]; then
		Xdialog --title "$APPTITLE" --no-buttons --infobox "$1" 0 0 1000000 & 
		XPID=$!
	else
		echo "$1"
	fi
}

### main
[ "$NOT_USING_AUFS" ] && exit 1
! [ "$TMPFS_MOUNT" -a "$SAVEFILE_MOUNT" ] && exit # exit if not using RAM layer
if dash /etc/init.d/20-ram-save status | grep -q running; then 
	# only queue request when daemon is running
	[ -e $F_SNAPMERGE_REQUEST ] && exit	# request already in progress

	# acknowledge request
	bginfo "Request to save RAM layer content is queued. Please wait,
another message will popup when the saving occurs..."

	# issue request to udevd-helper
	touch $F_SNAPMERGE_REQUEST
	while [ -e $F_SNAPMERGE_REQUEST ];do
		sleep 1
	done
	[ $XPID ] && kill $XPID
	[ ! $XPID ] && echo "Done."
	
else
	# if daemon is not running, do direct save
	[ -e $F_SNAPMERGE_REQUEST ] && exit	# request already in progress

	# when ram-save daemon is not running, we need root privs for fatdog-merge-layers
	if [ $(id -u) -ne 0 ]; then
		[ "$DISPLAY" ] && exec gtksu "$APPTITLE" "$0"
		echo "Must run as root." && exec su -c "$0"
	fi

	touch $F_SNAPMERGE_REQUEST
	bginfo "Saving session now, please wait ..."
	/usr/sbin/fatdog-merge-layers.sh "$TMPFS_MOUNT" "$SAVEFILE_MOUNT"
	[ $XPID ] && kill $XPID
	info "Save completed."
	rm -f $F_SNAPMERGE_REQUEST
fi


###END###
