#!/bin/sh
#131112 L18L internationalisation

# std localisation stanza
export TEXTDOMAIN=fatdog
. gettext.sh
# performance tweak - use "C" if there is no localisation
! [ -e $TEXTDOMAINDIR/${LANG%.*}/LC_MESSAGES/$TEXTDOMAIN.mo ] &&
! [ -e $TEXTDOMAINDIR/${LANG%_*}/LC_MESSAGES/$TEXTDOMAIN.mo ] && LANG=C


### configuration
SWAPFILE_NAME=/mnt/home/fatdog64-swapfile
APPTITLE="$(gettext 'Create Swap File')"
. $BOOTSTATE_PATH # BOOTSTATE_PATH exported by /etc/profile

############# main ##############
# 1. can only create after creating a savefile
if [ ! "$SAVEFILE_MOUNT" ] ; then 
	Xdialog --title "$APPTITLE" --infobox "$(gettext 'You must create a save file first.')" 0 0 90000
	exit
fi

# 2. must be run as root
[ $(id -u) -ne 0 ] && exec gtksu "$APPTITLE" "$0"

# 3. ask for savefile size - enter loop until we get the right size; or cancelled
#sizeinfo=$(df -h | grep $SAVEFILE_DEVICE | awk '{print $2, " "partition and has ", $4, "free space,"; exit}')
sizeinfo=$(df -h | grep $SAVEFILE_DEVICE)
SIZE="$(echo $sizeinfo | awk '{print $2}')" 
FREE="$(echo $sizeinfo | awk '{print $4}')"
while true; do
	if choice=$(Xdialog --title "$APPTITLE" --stdout --inputbox "$(gettext 'To create a swap file that will automatically load at boot, enter the size below.') \n \n 
	$(eval_gettext '/mnt/home is a $SIZE partition and has $FREE free space, this is where the swap file will be created.') \n \n 
	$(gettext 'Enter the size in megabytes for your swap file. \n 
	For example, if you want a 1GB swap file enter 1000')" 0 0 ); then
		SIZE=$choice
	else
		#cancel clicked
		Xdialog --title "$APPTITLE" --infobox "$(gettext 'Cancelled, nothing is changed.')" 0 0 10000
		exit
	fi

	if [ $(( SIZE * 1000 )) -gt $(df | grep $SAVEFILE_DEVICE | awk '{print $4}') ] ; then
		Xdialog --title "$APPTITLE" --infobox "$(gettext 'The size you entered is too big.')" 0 0 90000 
	else break
	fi 
done

# 4. create it and use it now.
yaf-splash -fg black -transparent -placement top -text "$(gettext 'Creating swap file, please wait.')" &
XPID=$!

swapoff $SWAPFILE_NAME
rm $SWAPFILE_NAME
dd if=/dev/zero of=$SWAPFILE_NAME count=${SIZE} bs=1M  #can't seek to the end with swap
mkswap $SWAPFILE_NAME
swapon $SWAPFILE_NAME

kill $XPID

# 5. make the swap file permanent
! grep $SWAPFILE_NAME /etc/fstab > /dev/null && echo "$SWAPFILE_NAME     swap swap defaults          0       0" >> /etc/fstab
Xdialog --title "$APPTITLE" --infobox "$(gettext 'The swap file has been created and turned on.')" 0 0 90000
