#!/bin/sh
# This is a wrapper script for lf that allows it to create image previews with
# ueberzug. This works in concert with the lf configuration file and the
# lf-cleaner script.

cleanuplf() {
	exec 3>&-
	\rm "$FIFO_UEBERZUG"
}

lfub() {
	dircache=/tmp/$USER-lflastdir
	lfopt="--last-dir-path=$dircache"
	if [ -n "$SSH_CLIENT" ] || [ -n "$SSH_TTY" ]; then
		lf "$lfopt" "$@"
	else
		export FIFO_UEBERZUG="/tmp/ueberzug-$$"
		mkfifo "$FIFO_UEBERZUG"
		ueberzug layer -s <"$FIFO_UEBERZUG" -p json &
		exec 3>"$FIFO_UEBERZUG"
		trap cleanuplf HUP INT QUIT TERM PWR EXIT
		lf "$lfopt" "$@" 3>&-
	fi
	[ -f "$dircache" ] && dir="$(cat "$dircache")" && [ -d "$dir" ] && cd "$dir"
}

alias lf="lfub"