#!/bin/bash

# LoongArch LATX Wine application helper.
# Adapted from /usr/bin/runapp in Loongnix's i386-runtime-extra.

APPNAME=`basename $0`
source /opt/apps/$APPNAME/"$APPNAME".metainfo

WINE_PREFIX="$HOME/.local/wine/$APPNAME"
WINE_CMD="wine"
APP_VER="1.0"

export WINEDLLPATH="$WINE_DIR/lib:$WINE_DIR/lib64"
export WINEPREDLL="/opt/apps/$APPNAME/lib"
export WINEPREFIX="$WINE_PREFIX"

if [ "$APPRUN_CMD" ]; then
	WINE_CMD="$APPRUN_CMD"
fi

if [ "$APP_VERSION" ]; then
	APP_VER="$APP_VERSION"
fi

FixLink() {
	if [ -d "$WINE_PREFIX" ];then
		CUR_DIR="$PWD"
		cd "$WINE_PREFIX/dosdevices"
		rm c: z:
		ln -s -f ../drive_c c:
		ln -s -f / z:
		cd "$CUR_DIR"
		ls -l "$WINE_PREFIX/dosdevices"
	fi
}

ExtractApp() {
	mkdir -p "$WINE_PREFIX"
        tar xf "$ARCHIVE_FILE" \
		-C "$WINE_PREFIX"
        mv "$WINE_PREFIX/drive_c/users/@current_user@" \
		"$WINE_PREFIX/drive_c/users/$USER"
        sed -i "s#@current_user@#$USER#g" \
		"$WINE_PREFIX"/*.reg
	FixLink
}

RemoveApp() {
	rm -rf "$WINE_PREFIX"
}

HelpApp() {
        echo -e "
Wine application helper options:

    -e, --remove    Remove extracted application files"
    -h, --help      Show program help information"
"
}

UpdateApp() {
	if [ -f "$WINE_PREFIX/pkg_version" ] && \
		[ "$(cat "$WINE_PREFIX/pkg_version")" = "$APP_VER" ]; then
		return
	fi

	tar xf "$ARCHIVE_FILE" \
		-C "$WINE_PREFIX" \
		--exclude-from=$UPDATE_IGNORE_FILE

	rm -rf "$WINE_PREFIX/drive_c/users"/\@current_user\@

	echo "$APP_VER" > "$WINE_PREFIX/pkg_version"

}

RunApp() {
        if [ ! -d "$WINE_PREFIX" ]; then
		ExtractApp | progressbar $APPNAME "Initializing application data for $APPNAME ..."
	else
		UpdateApp | progressbar $APPNAME "Updating $APPNAME ..."
        fi
	if [ -n "$APP_DIR" ]; then
		cd "$WINE_PREFIX/$APP_DIR"
		WINEPREFIX="$WINE_PREFIX" \
			"$WINE_CMD" "$WINE_PREFIX/$EXEC_PATH"
	else
		exec "$WINE_CMD" \
			"$WINE_PREFIX/$EXEC_PATH"
	fi
}

if command -v zenity >/dev/null 2>&1; then
	progressbar()
	{
		WINDOWID="" \
			zenity \
				--progress \
				--title="$1" \
				--text="$2" \
				--pulsate \
				--width=400 \
				--auto-close \
				--no-cancel \
		|| WINDOWID="" \
			zenity \
				--progress \
				--title="$1" \
				--text="$2" \
				--pulsate \
				--width=400 \
				--auto-close
	}
else
	echo "Wine application helper cannot find the zenity executable. Please install zenity."
	exit 1
fi

if [ $# -gt 1 ]; then
	echo "${APPNAME}: Invalid option specified."
	HelpApp
	exit 1
fi

if [ -n "$1" ]; then
	case $1 in
		"-e" | "--remove")
			RemoveApp
			;;
		"-h" | "--help")
			HelpApp
			;;
		*)
			echo "${APPNAME}: Invalid option specified."
			HelpApp
			exit 1
			;;
	esac
else
	RunApp
fi
