#!/usr/bin/env sh

# Description: Open hovered or current directory in image viewer.
#              Supported image viewers open in thumbnail mode when
#              the hovered entry is a directory.
#
# Dependencies:
#   - imv (https://github.com/eXeC64/imv) or,
#   - sxiv (https://github.com/muennich/sxiv) or,
#   - ucollage (https://github.com/ckardaris/ucollage) or,
#   - lsix (https://github.com/hackerb9/lsix), or
#   - viu (https://github.com/atanunq/viu), or
#   - catimg (https://github.com/posva/catimg), or
#   - optional: ffmpegthumbnailer for video thumbnails
#   - optional: ffmpeg for audio thumbnails (album art)
#
# Shell: POSIX compliant
# Author: Arun Prakash Jana, Luuk van Baal

target="$(readlink -f "$1")"

exit_prompt() {
    [ -n "$1" ] && printf "%s\n" "$1"
    printf "%s" "Press any key to exit..."
    cfg=$(stty -g); stty raw -echo; head -c 1; stty "$cfg"
    clear
    exit
}

nthumb_cleanup() {
    [ -n "$!" ] && while [ -e /proc/"$!" ]; do sleep 1; done
    if [ -f "$target" ]; then
        rm -r "$(dirname "$target")"/.nthumbs
    elif [ -d "$target" ]; then
        rm -r "$target"/.nthumbs
    fi &
}

make_thumbs() {
    if [ -d "$target" ]; then cd "$target" || exit_prompt; fi
    if mkdir .nthumbs >/dev/null; then
        thumbs=1
    else
        exit_prompt
    fi
    for file in *; do
        case "$(file -bL --mime-type -- "$file")" in
          image/*) ln -s "$PWD/$file" "$PWD/.nthumbs/$file" ;;
          audio/*) ffmpeg -i "$file" ".nthumbs/${file%%.*}.jpg" -y >/dev/null 2>&1;;
          video/*) ffmpegthumbnailer -i "$file" -o .nthumbs/"${file%%.*}".jpg 2> /dev/null ;;
        esac
    done
    cd .nthumbs || return
}

view_dir() {
  find . -maxdepth 0 -print0 | xargs -0 "$1" --
}

if uname | grep -q "Darwin"; then
    [ -f "$1" ] && open "$1" >/dev/null 2>&1 &
elif type lsix >/dev/null 2>&1; then
    if [ -d "$target" ]; then
        cd "$target" || exit_prompt
    fi
    make_thumbs
    clear
    lsix
    nthumb_cleanup
    exit_prompt
elif type ucollage >/dev/null 2>&1; then
    make_thumbs
    ucollage
    nthumb_cleanup
    exit
elif type sxiv >/dev/null 2>&1; then
    make_thumbs
    if [ -f "$target" ]; then
        view_dir sxiv >/dev/null 2>&1 &
    elif [ -d "$target" ]; then
        sxiv -aqt . >/dev/null 2>&1 &
    fi
elif type imv >/dev/null 2>&1; then
    make_thumbs
    if [ -f "$target" ]; then
        view_dir imv >/dev/null 2>&1 &
    elif [ -d "$target" ]; then
        imv . >/dev/null 2>&1 &
    fi
elif type imvr >/dev/null 2>&1; then
    make_thumbs
    if [ -f "$target" ]; then
        view_dir imvr >/dev/null 2>&1 &
    elif [ -d "$target" ]; then
        imvr . >/dev/null 2>&1 &
    fi
elif type viu >/dev/null 2>&1; then
    clear
    viu -n "$1"
    exit_prompt
elif type catimg >/dev/null 2>&1; then
    clear
    catimg "$1"
    exit_prompt
else
    exit_prompt "Please install sxiv/imv/viu/catimg/lsix."
fi
[ -n "$thumbs" ] && nthumb_cleanup &