#!/bin/sh

# Example AppRun for using the hooks of this repository.
# NOTE: It is meant to be used with sharun which uses a top level bin dir

if [ "$APPRUN_DEBUG" = 1 ]; then
	set -x
fi

set -e

APPDIR="$(cd "${0%/*}" && echo "$PWD")"
MAIN_BIN=pinta
BIN="${ARGV0:-$0}"
BIN="${BIN##*/}"

export APPIMAGE_ARCH=x86_64
export HOSTPATH="$PATH"
export PATH="$APPDIR/bin:$PATH"
export APPDIR

export HOST_HOME="${REAL_HOME:-$HOME}"
export HOST_XDG_CONFIG_HOME="${REAL_XDG_CONFIG_HOME:-${XDG_CONFIG_HOME:-$HOST_HOME/.config}}"
export HOST_XDG_DATA_HOME="${REAL_XDG_DATA_HOME:-${XDG_DATA_HOME:-$HOST_HOME/.local/share}}"
export HOST_XDG_CACHE_HOME="${REAL_XDG_CACHE_HOME:-${XDG_CACHE_HOME:-$HOST_HOME/.cache}}"
export HOST_XDG_STATE_HOME="${REAL_XDG_STATE_HOME:-${XDG_STATE_HOME:-$HOST_HOME/.local/state}}"

# Allow users to set env variables for specific AppImage
# This feature only works with the uruntime
if [ "$1" = '--appimage-add-env' ]; then
	shift
	for v do
		echo "$v" >> "$APPIMAGE".env
		>&2 echo "Added '$v' to $APPIMAGE.env"
	done
	exit 0
fi

# additional scripts can be placed in the top level bin dir
# those with a name that ends up .hook will be executed in the current shell
# those that end with .bg.hook will be executed in the background
# and those that end with .src.hook will be sourced in the AppRun
for hook in "$APPDIR"/bin/*.hook; do
	[ -x "$hook" ] || continue
	case "$hook" in
		*.src.hook) continue ;;
		*.bg.hook)  "$hook" &;;
		*.hook)     "$hook"  ;;
	esac
done

# source hooks need to run last
for hook in "$APPDIR"/bin/*.src.hook; do
	[ -e "$hook" ] || continue
	. "$hook"
done

# always unset ARGVO to avoid causing issues to child processes that use zsh
# We do it after running the hooks since some hooks need it
# we also save the original value of the var to ARG0 which does not conflict
export ARG0="$ARGV0"
unset ARGV0

# Check if BIN (ARGV0) matches a binary, fallback to $1, then binary in .desktop
if [ -f "$APPDIR"/bin/"$BIN" ]; then
	TO_LAUNCH="$APPDIR"/bin/"$BIN"
elif [ -f "$APPDIR"/bin/"$1" ]; then
	TO_LAUNCH="$APPDIR"/bin/"$1"
	shift
else
	TO_LAUNCH="$APPDIR"/bin/"$MAIN_BIN"
fi

# If LD_DEBUG=libs is set outside the AppImage the output is not helpful
# because it will include the libs of sh, grep, cat, etc from the hooks
# with this var we can set LD_DEBUG=libs for the bundled application only
if [ "$APPIMAGE_DEBUG" = 1 ]; then
	cat /etc/os-release >"$PWD"/"${APPIMAGE##*/}"-debug.log || :
	export LD_DEBUG=libs
	export VK_LOADER_DEBUG=all
	export LC_ALL=C
	export SHARUN_PRINTENV=1
	"$TO_LAUNCH" "$@" 2>>"$PWD"/"${APPIMAGE##*/}"-debug.log || :
	>&2 echo "Debug log at: '$PWD/${APPIMAGE##*/}-debug.log'"
else
	exec "$TO_LAUNCH" "$@"
fi
