#!/usr/bin/env sh

cleanup() {
	rm -r "$LF_UEBERZUG_TEMPDIR" 2>/dev/null
	kill $ueberzugpid 2>/dev/null
}

export LF_UEBERZUG_TEMPDIR="$(mktemp -d -t lf-ueberzug-XXXXXX)"
trap cleanup INT

export LF_UEBERZUG_FIFO="$LF_UEBERZUG_TEMPDIR/fifo"
mkfifo "$LF_UEBERZUG_FIFO"
tail -f "$LF_UEBERZUG_FIFO" | ueberzug layer --silent &
ueberzugpid=$!

last_dir="$([ ! -f $XDG_RUNTIME_DIR/lf-last-dir ] || cat $XDG_RUNTIME_DIR/lf-last-dir)"


fid="$(mktemp)"

prev=$(pwd)
cd $last_dir
lf  -command '$printf $id > '"$fid"''  -last-dir-path=$XDG_RUNTIME_DIR/lf-last-dir "$@"
cd $prev
id="$(cat "$fid")"
archivemount_dir="$XDG_RUNTIME_DIR/__lf_archivemount_$id"
if [ -f "$archivemount_dir" ]; then
		cat "$archivemount_dir" | \
				while read -r line; do
						sudo umount "$line"
						rmdir "$line"
				done
		rm -f "$archivemount_dir"
fi
if [ -f "$tmp" ]; then
		dir="$(cat "$tmp")"
		rm -f "$tmp"
		if [ -d "$dir" ]; then
				if [ "$dir" != "$(pwd)" ]; then
						cd "$dir"
				fi
		fi
fi
cleanup
