#!/bin/sh -e

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

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

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

# TODO: use $0 instead
exec "$destdir"/ID/bin/"$(basename "$1")"