#!/bin/sh -ex

# TODO: extract self without resolving to $0 because it doesn't resolve links

if [ -z "$XDG_CACHE_HOME" ]; then
	destdir=/tmp/tarinstall
else
	destdir="$XDG_CACHE_HOME"/tarinstall
fi

if ! [ -d "$destdir" ]; then
	mkdir -p "$destdir"
fi


# If the file does not contain the .tin extension it was either renamed or
# linked somewhere, so if it was called as $ <exe> then try to find it in the
# current directory else try to find it in path. When found evaluate if it is
# a link, if it is traverse it and then set the archive variable
# TODO: for each match check if the file si really a tarinstall with a header

archive="$0"
if ! echo "$archive" | grep -q \.tin$; then
	if [ "$(dirname "$archive")" = '.' ]; then
		if [ -e "$archive" ]; then
			if [ -L "$archive" ]; then
				archive="$(readlink "$0")"
			fi
		else
			: > "$destdir"/paths
			( IFS=:
			for p in $PATH; do
				find -L "$p" -name "$archive" >> "$destdir"/paths
			done
			)
			while read -r l; do
				if [ -L "$l" ]; then
					archive="$(readlink "$l")"
					break
				elif [ -x "$l" ]; then
					archive="$l"
					break
				fi
			done < "$destdir"/paths
		fi
	fi
fi

if ! [ "$(head -n 1 "$destdir"/ID/checksum 2>/dev/null)" = 'SUM' ]; then
	rm -rf "$destdir"/ID
	tail -c +BYTES "$0" | lz4 -dc | tar -x -C "$destdir"
	echo "SUM" > "$destdir"/ID/checksum
fi

if [ "$(find "$destdir"/ID/bin -maxdepth 1 -type f | wc -l)" = '1' ]; then
	binname="$(find "$destdir"/ID/bin -maxdepth 1 -type f)"
else
	binname="$(basename "$0")"
	if echo "$binname" | grep -q \.tin$; then
		binname="$destdir"/ID/bin/"$(echo "$binname" | sed s/\.tin//)"
	fi
fi

ORIGIN="$destdir"/ID
LD_LIBRARY_PATH="$ORIGIN/lib"
PATH="$ORIGIN/bin":$PATH
export ORIGIN
export LD_LIBRARY_PATH
export PATH

# export LD_DEBUG='libs'

exec "$binname" "$@"