#!/bin/sh

RED="\033[31m"
RESET="\033[0m"

set -C -f

f=$1
w=$2
h=$3
x=$4
y=$5

image() {
    f=$1
    w=$2
    h=$3
    x=$4
    y=$5
    # TODO: Maybe append some mediainfo output into the image with ffmpeg (when there's enough space)
    # I assume that will take a bit of math that I'll try to implement in perl or python
	if [ -f "$1" ] && [ -n "$DISPLAY" ] && [ -z "$WAYLAND_DISPLAY" ] && command -V ueberzug >/dev/null 2>&1; then
		printf '{"action": "add", "identifier": "PREVIEW", "x": "%s", "y": "%s", "width": "%s", "height": "%s", "scaler": "contain", "path": "%s"}\n' "$(($4 + 3))" "$(($5 + 1))" "$(($2 - 6))" "$(($3 - 2))" "$1" >"$FIFO_UEBERZUG"
	fi
	exit 1
}

video() {
    f=$1
    w=$2
    h=$3
    x=$4
    y=$5
	thumb="$(vidthumb "$f")" || (
		printf "%b" "\033[31mvidthumb script not in path\033[0m"
		return 1
	)
	image "$thumb" "$w" "$h" "$x" "$y"
}

text() {
	f=$1
	w=$2
	bat --color=always --style=plain --pager=never --terminal-width "$((w - 2))" "$f" && exit 1
	cat "$f"; exit 1
}

run() {
    #shellcheck disable=SC2068
	if ! command -v "$1" >/dev/null 2>&1; then
		printf "%b" "${RED}Cannot execute $1${RESET}"
		exit 1
	elif $@; then
		exit 1
	else
		printf "%b" "${RED}Failed to run command: $*${RESET}"
		exit 1
	fi
}

mimetest() {
    case "$1" in
        text/*) text "$f" "$w" ;;
        */pdf)
            [ ! -f "${CACHE}.jpg" ] && run pdftoppm -jpeg -f 1 -singlefile "$f" "$CACHE"
            image "${CACHE}.jpg" "$w" "$h" "$x" "$y"
            ;;
        */x-bzip-compressed-tar | */x-compressed-tar | */x-xz-compressed-tar) run als -- "$f" ;;
        */x-7z-compressed | */vnd.rar | */x-tar | */zip | */x-java-archive | */x-xz | */gzip) run 7z l "$f" | sed 1,11d ;;
        */x-cd-image) run iso-info --no-header -l "$f" ;;
        */x-bittorrent) run transmission-show "$f" ;;
        */vnd.sun.xml.writer) run odt2txt "$f" ;;
        */msword) run catdoc "$f" ;;
        */vnd.openxmlformats-officedocument.wordprocessingml.document) run docx2txt <"$f" ;;
        */vnd.ms-excel) run ssconvert --export-type=Gnumeric_stf:stf_csv "$f" "fd://1" | text --language=csv ;;
        */vnd.openxmlformats-officedocument.spreadsheetml.sheet) run ssconvert --export-type=Gnumeric_stf:stf_csv "$f" "fd://1" | text --language=csv ;;
        */epub+zip)
            [ ! -f "$CACHE" ] && run epub-thumbnailer "$f" "$CACHE" 1024
            image "$CACHE" "$w" "$h" "$x" "$y"
            ;;
        */pgp-encrypted) run gpg -d -- "$f" ;;
        */pkix-cert) run openssl x509 -text -noout -in "$f" ;;
        image/svg+xml)
            [ ! -f "$CACHE" ] && run inkscape --convert-dpi-method=none -o "$CACHE" --export-overwrite -D --export-png-color-mode=RGBA_16 "$f"
            image "$CACHE" "$w" "$h" "$x" "$y"
            ;;
        image/*) image "$f" "$w" "$h" "$x" "$y" ;;
        video/*) video "$f" "$w" "$h" "$x" "$y" ;;
        *opendocument*) run odt2txt "$f" ;;
        */markdown) run lowdown -Tterm "$f" ;;
        */html) run lynx -dump "$f" ;;
        *) return 1 ;;
    esac
}

CACHE="$HOME/.cache/lf/thumbnail-$(stat --printf '%n\0%i\0%F\0%s\0%W\0%Y' -- "$(readlink -f "$1")" | sha256sum | awk '{print $1}')"

filerun="$(file --brief --dereference --mime-type "$f")"
mimetest "$filerun" && exit 1

if command -v gio 1>/dev/null 2>&1; then
    giorun="$(gio info "$f" 2>/dev/null | grep standard::content-type | cut -d' ' -f4)"
    mimetest "$giorun" && exit 1
fi

printf "%b" "\$(file --mime-type)\t\t\t : $filerun\n"
[ -n "$giorun" ] && printf "%b" "\$(gio info)\t\t\t\t : $giorun\n"

mediainfo "$1" | head -n-2 | grep -v -e "Complete name" -e "General"

case $(file -b "$f") in
    *ascii* | *utf*) text "$f" "$w";;
esac

exit 1