#!/bin/ash
# save current session if fatdog is running in multisession mode
# Copyright (C) James Budiono 2012, 2015, 2018
# License: GNU GPL Version 3 or later
#
# Version 1.0 - initial release
#
# called from desktop
# Note1: originally taken from rc.shutdown save multisession code
# Note2: used for all multisession devices, not only DVD!

### configuration
APPTITLE="Save Multisession"
MULTI_SAVE_DIR=/tmp/save-multi	# tmp dir for creating multisession savefiles
EVENTMANAGER_CONFIG=/etc/eventmanager	# puppy event manager config file

# load configs
. $BOOTSTATE_PATH				# boot-time configuration
. $EVENTMANAGER_CONFIG			# MKSQUASHFS_OPTIONS
. /usr/sbin/fatdog-save-multisession.sh # shared multisession-saving code


### 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
}

#$1-text
yesno() {
	local resp
	if [ "$DISPLAY" ]; then
		Xdialog --title "$APPTITLE" --yesno "$1" 0 0
	else
		echo "$1"
		read resp
		test "$resp" = "YES"
	fi
}

# make sure we run as root
run_as_root() {
	if [ $(id -u) -ne 0 ]; then
		[ "$DISPLAY" ] && exec gtksu "$APPTITLE" "$0" # must run as root
		echo "Must run as root." && exec su -c "$0"
	fi
}

#################### main ###################
[ "$NOT_USING_AUFS" ] && exit 1
run_as_root

if [ "$MULTI_MOUNT" ]; then
	if [ -d $MULTI_SAVE_DIR ]; then
		info "Another session saving is in progress, try again after it is finished."
		exit 1
	fi
	if yesno "About to save the current session. 
Please remember to insert your disc back to $MULTI_DEVICE, and make sure that it is not full. 
If it is full, you need to burn a new copy of Fatdog64 to a new disc now.

YES to continue, or NO to cancel."; then
		
		bginfo "Saving session to $MULTI_DEVICE, please wait ..." 
		
		# wait for snapmergeppy to finish if there is one in progress
		echo "Waiting for RAM save task to finish..."
		while pidof snapmergepuppy > /dev/null; do sleep 1; done
		while pidof fatdog-merge-layers.sh > /dev/null; do sleep 1; done

		# save the session
		save_multisession not-shutdown
		[ $XPID ] && kill $XPID
	else
		info "Cancelled. Nothing is changed"
	fi
else
	info "Fatdog is not configured in multisession mode. This function cannot be used."
fi


