#!/bin/sh

# Based on https://github.com/cirala/vifmimg, licensed under GPL-3.0
# All changes are licensed under GPL-3.0
# Authors: cirala, L. Abramovich

# DESCRIPTION
#
# Launch an instance of ueberzug(1) and set the appropriate values so that
# it can be used by clifm to display images via the 'clifmimg' script.
# Consult the 'clifmimg' file itself for instructions on how to set up clifm's
# shotgun to preview images via 'clifmimg'.
#
# Previews for TAB completion (in FZF mode) are enabled by default. In any case,
# check the FzfPreview option in clifm's main configuration file.

# DEPENDENCIES
#
# ueberzug
#
# NOTE: Ueberzug needs to run on a graphical environment. Wayland is not supported.
#
# NOTE 2: Since the original ueberzug is unmaintained, we recommend using this fork
# instead: https://github.com/ueber-devel/ueberzug
#
# If running on the kitty terminal you can set CLIFM_KITTY_NO_UEBERZUG to 1 to use
# the kitty image protocol itself (currently slower than ueberzug). Run as follows:
#
# CLIFM_KITTY_NO_UERBERZUG=1 clifmrun --fzfpreview
#
# If running on Wayland, the kitty image protocol is used by default
#

ueberzug_cleanup() {
    rm -f -- "$CLIFM_FIFO_UEBERZUG" 2>/dev/null
    pkill -P $$ >/dev/null
}

# Prior to ueberzug 18.2.0, we need to silence stderr to avoid printing
# garbage on the screen
silence_stderr() {
	str="$(ueberzug version)"
	major="$(echo "$str" | cut -d'.' -f1)"
	minor="$(echo "$str" | cut -d'.' -f2)"

	if [ "$major" -ge 18 ] && [ "$minor" -ge 2 ]; then
		echo 0
	else
		echo 1
	fi
}

init_ueberzug() {
	CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/clifm"
	PREVIEW_DIR="$CACHE_DIR/previews"
	! [ -d "$PREVIEW_DIR" ] && mkdir -p "$PREVIEW_DIR"

	export CLIFM_FIFO_UEBERZUG="$CACHE_DIR/ueberzug-${$}"

	mkfifo "$CLIFM_FIFO_UEBERZUG"

	if [ "$(silence_stderr)" = "0" ]; then
		tail -f "$CLIFM_FIFO_UEBERZUG" | ueberzug layer --silent --parser json &
	else
		tail -f "$CLIFM_FIFO_UEBERZUG" | ueberzug layer --silent --parser json > /dev/null 2>&1 &
	fi
}

if ! type clifm > /dev/null 2>&1; then
	printf "clifm: Command not found\n"
	exit 127

elif [ "$TERM" = "xterm-kitty" ] && { [ -n "$CLIFM_KITTY_NO_UEBERZUG" ] \
|| [ -n "$WAYLAND_DISPLAY" ]; }; then
	export CLIFM_KITTY_IMG="${TMPDIR:-/tmp}/clifm_kitty_img"
	clifm "$@"

elif ! type ueberzug > /dev/null 2>&1 || [ -z "$DISPLAY" ] || [ -n "$WAYLAND_DISPLAY" ]; then
	clifm "$@"

else
	trap ueberzug_cleanup EXIT
	init_ueberzug

	clifm "$@"

	printf '{"action": "remove", "identifier": "clifm-preview"}\n' > "$CLIFM_FIFO_UEBERZUG"
fi
