#!/bin/sh

###############################################################################
# UExtract v4.15 by JakeSFR (a.k.a. SFR)'2013-2025                            #
# GNU GPL v2 applies                                                          #
###############################################################################

# -----------------------------------------------------------------------------
# Associate ROX 'SendTo/OpenWith' and/or Thunar with UExtract
# -----------------------------------------------------------------------------

### ROX ###

[ "$(pwd)" = '/' ] && DOT='' || DOT='.'	# Woof/Fatdog build system
USER_HOME="$(eval echo ~${SUDO_USER})"	# XBPS

APP_NAME="UExtract"
APP_ICON="UExtract"
APP_PATH="/usr/local/apps/UExtract"
APP_CMD="/usr/local/apps/UExtract/AppRun %F"
APP_DESKTOP_PATH="${DOT}/usr/local/apps/UExtract/UExtract.desktop"
APP_EXTENSIONS="$(uextract -f | grep -vE '\[|\]|\?' | grep '^\.' | tr '\n' ';' | sed 's/\./\*\./g')"

# ROX

ROX_PATH=''

for i in "${DOT}/etc/xdg/rox.sourceforge.net/SendTo" \
		"${DOT}${USER_HOME}/.config/rox.sourceforge.net/SendTo" \
		"${DOT}${USER_HOME}/.config/rox.sourceforge.net/OpenWith" \
		"${DOT}/root/.config/rox.sourceforge.net/OpenWith"
do
	if [ -d "$i" ]; then
		grep -qi '^Void' /etc/issue 2>/dev/null && [ "$i" != "${i#${DOT}/etc}" ] && continue
		ROX_PATH="$(readlink -f "$i")"
		break
	fi
done


# Mime-Types are kept inside UExtract.desktop file
if [ -d "$ROX_PATH" ]; then
	for i in $(grep '^MimeType=' "$APP_DESKTOP_PATH" | cut -f2- -d '=' | tr ';' '\n' | tr '/' '_' | head -n -1); do
		mkdir -p "${ROX_PATH}/.${i}" 
		ln -sfT "$APP_PATH" "${ROX_PATH}/.${i}/${APP_NAME}"
	done
	
	mkdir -p "${ROX_PATH}/.group"
	ln -sfT "$APP_PATH" "${ROX_PATH}/.group/${APP_NAME}"	
	ln -sfT "$APP_PATH" "${ROX_PATH}/${APP_NAME}"
fi

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

### Thunar ###

if [ "$(pwd)" = "/" ] && (type thunar >/dev/null 2>&1 || type Thunar >/dev/null 2>&1); then
	
	TEMPLATE="<action>
	<icon>${APP_ICON}</icon>
	<name>${APP_NAME}</name>
	<command>${APP_CMD}</command>
	<description>Extract archives</description>
	<patterns>${APP_EXTENSIONS}</patterns>
	<directories/>
	<audio-files/>
	<other-files/>
	<video-files/>
</action>"
	
	CONFIG="$USER_HOME/.config/Thunar/uca.xml"
	CONFIG_BAK="${CONFIG}.bak"
	
	if [ -f "$CONFIG" ]; then
		cp -af "$CONFIG" "$CONFIG_BAK"

		grep -qF "<name>${APP_NAME}</name>" "$CONFIG_BAK" || {
			echo "$(grep -v '</actions>' "$CONFIG_BAK")
${TEMPLATE}
</actions>" > "$CONFIG"
		}
	else
		mkdir -p "${CONFIG%/*}"
		echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<actions>
${TEMPLATE}
</actions>" > "$CONFIG"
	fi

fi

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

# Create shortcut on pinboard/desktop
[ "$(pwd)" = "/" ] && /usr/local/apps/UExtract/createshortcut &

# =============================================================================
