#!/bin/ash
# Version 0.2.0, 8 April 2008 - see version information in main AppRun file.
# jamesbond 2014 - apply SFR bug fix from here: http://www.murga-linux.com/puppy/viewtopic.php?p=713099#713099
# JakeSFR 2022 - style changes (indentations), simplifications, fixes, improvements, corner cases, gettext, etc.

# std localisation stanza
export TEXTDOMAIN=fatdog
. gettext.sh

# Determine the path to this application.
cd "$(dirname "$0")"
THIS_APPDIR="$(pwd)"

# Get paths of: Trash AppDir, original item and the mountpoint
{ IFS='' read -r TRASH_APPDIR; IFS='' read -r FILEPATH; IFS='' read -r MNTPOINT; } <<- EOF
$(cat "${THIS_APPDIR}/.info")
EOF

FILENAME="$(basename "$FILEPATH")"

# Get the path of the item in Trash
ITEMPATH="${THIS_APPDIR}/Files/${FILENAME}"

# Whether to use gxmessage or xmessage
MSG="$(which gxmessage 2>/dev/null)" || MSG="xmessage"

# -----------------------------------------------------------------------------

RemoveItem() {
	# Delete this file and directory.
	rm -r "$THIS_APPDIR"
	
	# Update the icon
	"${TRASH_APPDIR}/AppRun" -update-icon
}

RestoreItem() {
	local item response

	# Remove existing item.
	rm -r "$FILEPATH"

	# Restore the item.
	if ! response="$(mv -f "$ITEMPATH" "$FILEPATH" 2>&1)"; then
		$MSG -center \
			-title "$(gettext "Error")" \
			"$(gettext "There was an error while restoring the item!")
$response"
		return
	fi

	# Get info from the shortcut file (if exists)
	if [ -e "$THIS_APPDIR/shortcut" ]; then
		while IFS='>' read -r x y label name; do
			# Restore the shortcut(s) on the desktop
			rox --RPC <<- EOF
			<?xml version="1.0"?>
			<env:Envelope xmlns:env="http://www.w3.org/2001/12/soap-envelope">
				<env:Body xmlns="http://rox.sourceforge.net/SOAP/ROX-Filer">
					<PinboardAdd>
						<Path>$name</Path>
						<X>$x</X>
						<Y>$y</Y>
						<Label>$label</Label>
					</PinboardAdd>
				</env:Body>
			</env:Envelope>
			EOF
		done <<- EOF
		$(cat "$THIS_APPDIR/shortcut")
		EOF
	fi

	RemoveItem
}

DeleteIt() {
	# Write confirmation dialogue
	$MSG -center \
		-buttons "$(gettext "No"),$(gettext "Yes"):21" \
		-default "$(gettext "No")" \
		-title "$(gettext "Confirm Delete")" \
		"$(gettext "Are you sure you want to permanently delete this item?")"
	
	# If they chose to cancel.
	[ $? -eq 21 ] || exit
	
	# Remove the item
	RemoveItem
}

RestoreIt() {
	# See if there is already a file or folder of the same name in the same location.
	if [ -e "$FILEPATH" ]; then

		$MSG -center \
			-buttons "$(gettext "Cancel"),$(gettext "Trash It"):31,$(gettext "Overwrite It"):32" \
			-default "$(gettext "Cancel")" \
			-title "$(gettext "Error")" \
			"$(eval_gettext "An item named '\$FILEPATH' already exists.
What would you like to do?")"
		
		case $? in
			32) true								;;	# Overwrite it
			31)	"$TRASH_APPDIR/AppRun" "$FILEPATH"	;;	# Trash It
			*)	return								;;	# Cancel
		esac

	fi

	# Check if the MNTPOINT is mounted and abort if not
	if ! mountpoint -q "$MNTPOINT"; then
		$MSG -center \
			-buttons "$(gettext "No"),$(gettext "Yes"):21" \
			-default "$(gettext "No")" \
			-title "$(gettext "Error")" \
			"$(eval_gettext "The '\$MNTPOINT' is not a mountpoint.
Do you want to restore the item manually to another location?")"
		if [ $? -eq 21 ]; then
			rox -d "$THIS_APPDIR/Files"
		fi
		return
	fi

	# If the destination is an external filesystem, check the item's size
	if [ "$MNTPOINT" != '/' ]; then
		if [ $(df -P "$MNTPOINT" | awk 'NR==2 {print $4}') -lt $(( $(du -s "$ITEMPATH" | cut -f1) + 1024 )) ]; then
			$MSG -center \
				-buttons "$(gettext "No"),$(gettext "Yes"):21" \
				-default "$(gettext "No")" \
				-title "$(gettext "Error")" \
				"$(eval_gettext "Unable to restore '\$FILENAME'.
Its size is greater than the available space on the destination device.
Do you want to restore the item manually to another location?")"
			if [ $? -eq 21 ]; then
				rox -d "$THIS_APPDIR/Files"
			fi
			return
		fi
	fi

	# If dest dir doesn't exist, ask to create one
	restore_path="$(dirname "$FILEPATH")"
	if [ ! -d "$restore_path" ]; then
		$MSG -center \
			-buttons "$(gettext "No"),$(gettext "Yes"):21" \
			-default "$(gettext "No")" \
			-title "$(gettext "Request")" \
"$(eval_gettext "Destination directory '\$restore_path' doesn't exist.
Create it?")"
		if [ $? -eq 21 ]; then
			mkdir -p "$restore_path"
		else
			return
		fi
	fi

	# Restore the item.
	RestoreItem
}

# -----------------------------------------------------------------------------

### START

# If they just clicked on the icon, or chose the "View File information" option.
if [ ! "$@" ]; then

	# Write the message.
	$MSG -center \
		-buttons "$(gettext "Cancel"),$(gettext "Show"):31,$(gettext "Open"):32,$(gettext "Restore"):33,$(gettext "Delete"):34" \
		-default "$(gettext "Cancel")" \
		-title "$(gettext "Trashed File Information")" \
		-file Info
	
	case $? in
		31)	rox -d "$THIS_APPDIR/Files"	;;
		32)	rox "$ITEMPATH"				;;
		33) RestoreIt					;;
		34) DeleteIt					;;
	esac

# If they chose the "Restore" option.
elif [ "$1" = "-restore" ]; then

	RestoreIt

# If they chose to open the item.
elif [ "$1" = "-open-file" ]; then

	rox "$ITEMPATH"

# If they chose to see the item.
elif [ "$1" = "-see-file" ]; then

	rox -d "$THIS_APPDIR/Files"

# If they chose to delete the file
elif [ "$1" = "-delete" ]; then

	DeleteIt

# If they dropped something to the icon.
else

	# Write the error message.
	$MSG -center \
		-buttons "$(gettext "Okay")" \
		-default "$(gettext "Okay")" \
		-title "$(gettext "Error")" \
		"$(gettext "You can't drop items onto things that are in the Trash.")"

fi
