#!/bin/sh

# Copyright (C) 2019-present naheel-azawy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Meanings of exit codes:
# code | meaning    | action of ranger
# -----+------------+-------------------------------------------
# 0    | success    | Display stdout as preview
# 1    | no preview | Display no preview at all
# 5    | image      | Do not display anything nor cache output

# ==== constants ====

CFG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/stpv"
CFG_FILE="$CFG_DIR/config.sh"
IMAGE_CACHE_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/stpv"

RET_NO_MATCH=10
RET_FALLBACK=11

# ==== config ====

PV_IMAGE_ENABLED=1        # show image previews when possible
PV_TYPE=img               # (img or text) where text shows image previews in the terminal
PREFER_TEXT=              # prefer text over images when displaying documents
DARK_DOCS=                # invert documents preview color in image previews
SAFE=1                    # kill itself if needed (check main for details)
AUTO_ORIENT=1             # auto orient images
MAX_IMG_CACHE_SIZE=300kb  # max image cache size
MAX_IMG_CACHE_W=1920      # max image cached image width
MAX_IMG_CACHE_H=1080      # max image cached image height
TIMEOUT=5                 # maximum time in seconds stpv should take, approximately

# ==== global parameters ====

stpv_id=
file_path=
w=70 h=10
x=0  y=0

image_cache_hash=
image_cache_path=
file_extension=
file_extension_lower=
mimetype=
is_doc=
show_pv_image=1
show_fallback=1
magick=convert

handlers=
gen_deps=
deps_tbl='| function | type | cli program | image program |'

if [ "$1" = '--gen-deps' ]; then
    gen_deps=1
fi

# ==== main ====

real_main() {
    load_config

    [ $# = 0 ] || [ "$1" = -h ] || [ "$1" = --help ] && usage

    if [ "$1" = '--clear' ]; then
        stpvimg --clear "$2"
        exit
    fi

    file_path="$1"
    file_path=$(realpath -s "$file_path")

    [ -e "$file_path" ] || {
        echo "ERROR: file '$file_path' not found"
        return 1
    }

    # prevent caching caches
    echo "$file_path" | grep -q "^$IMAGE_CACHE_DIR" && {
        echo 'stpv cache file'
        return
    }

    if exists magick; then
        magick=magick
    fi

    if [ $# -ge 5 ]; then
        w="$2" h="$3" x="$4" y="$5"
    elif [ $# -eq 1 ]; then
        cols=$(($(tput cols) / 2))
        lins=$(($(tput lines) - 2))
        x="$cols" y="1" w="$cols" h="$lins"
    elif [ $# -eq 2 ]; then
        cols=$(($(tput cols) / 2))
        lins="$2"
        x="$cols" y="1" w="$cols" h="$lins"
    else
        usage
    fi

    # for stpvimg
    export PV_IMAGE_ENABLED PV_TYPE

    [ $# -ge 6 ] && stpv_id="$6"
    [ "$id" ]    && stpv_id="$id"
    [ ! "$stpv_id" ]  && stpv_id=-1

    [ "$stpv_id" ] && stpvimg --clear "$stpv_id"

    if [ -n "$PV_IMAGE_ENABLED" ] &&
           exists stpvimg         &&
           stpvimg --enabled      &&
           stpvimg --alive "$stpv_id"; then
        show_pv_image=1
    else
        show_pv_image=
    fi

    image_cache_hash=$(echo "$file_path" | md5sum - | cut -d ' ' -f1)
    image_cache_path="$IMAGE_CACHE_DIR/$image_cache_hash.jpg"
    file_extension="${file_path##*.}"
    file_extension_lower=$(echo "$file_extension" | tr '[:upper:]' '[:lower:]')

    if exists mimetype; then
        mimetype=$(mimetype --dereference --brief --mimetype -- "$file_path")
        show_fallback=
        handle_now
        handler_exit_code=$?
        if [ $handler_exit_code = $RET_FALLBACK ]; then
            # if nothing is found using mimetype, try file
            mimetype=$(file --dereference --brief --mime-type -- "$file_path")
            show_fallback=1
            handle_now
        else
            return $handler_exit_code
        fi
    else
        mimetype=$(file --dereference --brief --mime-type -- "$file_path")
        handle_now
    fi
}

main() {
    load_config
    if [ "$1" = '--eval' ]; then
        shift
        "$@"
    elif [ -n "$gen_deps" ]; then
        echo "$deps_tbl" | column -s '|' -o '|' -t
    elif [ "$1" = '--real' ]; then
        shift
        real_main "$@"
    elif [ -n "$SAFE" ]; then
        # Because this script is expected to run inside a file
        # manager. Now imagine scrolling over lots of files
        # quickly. This will create tons of processes that are
        # not so light... Keep in mind `convert` runs a lot in
        # here... So, this will save your life and keep your
        # machine safe!
        exec timeout "$TIMEOUT" "$0" --real "$@"
    else
        real_main "$@"
    fi
}

# ==== helpers ====

list_descendants() {
    # https://unix.stackexchange.com/a/124148/183147
    children=$(ps -o pid= --ppid "$1")
    echo "$children"
    for pid in $children; do
        list_descendants "$pid"
    done
}

usage() {
    BIN=$(basename "$0")
    >&2 printf "usage: %s [--clear] [FILE] [ w h x y ] [ stpv_id ]\n" "$BIN"
    exit 1
}

load_config() {
    mkdir -p "$CFG_DIR"
    # shellcheck disable=SC1090
    [ -f "$CFG_FILE" ] && . "$CFG_FILE"
}

handle_now() {
    case "$mimetype" in
        application/pdf          | \
            application/*office* | \
            application/ms*      | \
            application/vnd.ms-* | \
            application/vnd.oasis.opendocument.*)
            is_doc=1 ;;
    esac
    case "$file_extension_lower" in
        pdf|stl|slx) is_doc=1 ;;
    esac

    # if text is preferred for documents
    [ -n "$is_doc" ] && [ -n "$PREFER_TEXT" ] &&
        show_pv_image=

    echo "$handlers" | while read -r handler; do
        if [ -n "$handler" ]; then
            eval "$handler" </dev/null
            ret=$?
            case $ret in
                "$RET_NO_MATCH") ;;
                *) return $ret ;;
            esac
        fi
    done
}

exists() {
    command -v "$1" >/dev/null
}

run_if_exists() {
    if exists "$1"; then
        "$@"
    else
        return 1
    fi
}

newer_than() {
    [ -s "$1" ] && [ -s "$2" ] && {
        res=$(find "$1" -prune -newer "$2")
        [ -n "$res" ]
    }
}

image_cached() {
    if newer_than "$image_cache_path" "$file_path"; then
        return 0
    else
        mkdir -p "$IMAGE_CACHE_DIR"
        rm -f "$image_cache_path"
        return 1
    fi
}

image_needed() {
    [ -n "$show_pv_image" ]
}

image_prepare() {
    conv_file="$image_cache_path"
    [ ! -f "$conv_file" ] && conv_file="$file_path"

    dims="$(identify -ping -format '%w\n%h\n' "${conv_file}[0]")"
    width="$(echo "$dims" | head -1)"
    height="$(echo "$dims" | tail -1)"

    [ -n "$width" ] || [ -n "$height" ] ||
        return "$RET_NO_MATCH"

    if [ -n "$MAX_IMG_CACHE_H" ] && [ "$height" -gt "$MAX_IMG_CACHE_H" ]; then
        width=$((width * MAX_IMG_CACHE_H / height))
        height="$MAX_IMG_CACHE_H"
    fi

    if [ -n "$MAX_IMG_CACHE_W" ] && [ "$width" -gt "$MAX_IMG_CACHE_W" ]; then
        height=$((height * MAX_IMG_CACHE_W / width))
        width="$MAX_IMG_CACHE_W"
    fi

    if [ -n "$is_doc" ] && [ -n "$DARK_DOCS" ]; then
        dark_opts='-channel RGB -negate'
    else
        dark_opts=
    fi

    if [ -n "$AUTO_ORIENT" ]; then
        auto_orient_opts='-auto-orient'
    else
        auto_orient_opts=
    fi

    if [ -n "$MAX_IMG_CACHE_SIZE" ]; then
        max_img_size_opts="-define jpeg:extent=$MAX_IMG_CACHE_SIZE"
    else
        max_img_size_opts=
    fi

    # shellcheck disable=SC2086
    $magick "${conv_file}[0]"          \
            $dark_opts                 \
            $auto_orient_opts          \
            $max_img_size_opts         \
            -resize ${width}x${height} \
            "$image_cache_path"
}

image_show_pv() {
    stpvimg --add "$stpv_id" "$image_cache_path" \
            "$x" "$y" "$w" "$h" &&
        return 5
}

colorize_src() {
    if exists bat; then
        batcmd=bat
    elif exists batcat; then
        batcmd=batcat
    else
        batcmd=
    fi

    if [ "$1" = "--md" ]; then
        shift
        if exists mdcat; then
            mdcat "$1"
        elif [ -n "$batcmd" ]; then
            $batcmd --color always        \
                    --style plain         \
                    --paging never        \
                    --language markdown   \
                    --terminal-width "$w" \
                    --wrap character      \
                    -- "$@"
        elif exists highlight; then
            highlight --replace-tabs=4 --out-format=ansi \
                      --style='pablo' --force --syntax=markdown -- "$@"
        else
            cat
        fi
    else
        if [ "$( stat --printf='%s' -- "$1" )" -gt 262143 ]; then # > 256KiB
            cat "$1"
        fi

        if [ -n "$batcmd" ]; then
            $batcmd --color always        \
                    --style plain         \
                    --paging never        \
                    --terminal-width "$w" \
                    --wrap character      \
                    -- "$@"
        elif exists highlight; then
            highlight --replace-tabs=4 --out-format=ansi \
                      --style='pablo' --force -- "$@"
        elif exists source-highlight; then
            source-highlight --tab=4 --out-format=esc \
                      --style=esc256.style --failsafe -i "$@"
        else
            cat "$1"
        fi
    fi
}

view_pandoc() {
    exists pandoc || return 1
    text=$(pandoc "$1" -t gfm+yaml_metadata_block --columns="$w" -s)
    echo "$text" | colorize_src --md
}

add() {
    handlers="${handlers}$1
"
    if [ -n "$gen_deps" ]; then
        func="$1"
        kind="$2"
        deps="$3"
        deps_img="$4"
        [ -n "$kind" ] &&
            deps_tbl="$deps_tbl
| $func | $kind | $deps | $deps_img |"
    fi
}

add_top() {
    handlers="$1
${handlers}"
    if [ -n "$gen_deps" ]; then
        func="$1"
        kind="$2"
        deps="$3"
        deps_img="$4"
        [ -n "$kind" ] &&
            deps_tbl="$deps_tbl
| $func | $kind | $deps | $deps_img |"
    fi
}

# ==== handlers ====

add handle_link
handle_link() {
    [ -L "$file_path" ] && {
        printf '\033[1m\033[36mSymbolic link to\033[0m ->\n'
        printf '\033[1m\033[34m%s\033[0m\n' "$(readlink "$file_path")"
        echo
    }

    return "$RET_NO_MATCH"
}

add handle_directory directory ls -
handle_directory() {
    [ "$mimetype" = inode/directory ] ||
        return "$RET_NO_MATCH"

    ls --color --group-directories-first "$file_path"
}

add handle_archive archive xzcat,zcat,atool,bsdtar -
handle_archive() {
    case "$file_extension_lower" in
        a|ace|alz|arc|arj|bz|bz2|cab|cpio|deb|gz|jar|lha|lz|lzh|lzma|lzo| \
            rpm|rz|t7z|tar|tbz|tbz2|tgz|tlz|txz|tZ|tzo|war|xpi|xz|Z|zip) ;;
        *) return "$RET_NO_MATCH" ;;
    esac

    if echo "$file_path" | grep -Eq '.+\.json\.xz$'; then # json
        xzcat "$file_path" | jq -C .
    elif echo "$file_path" | grep -Eq '.+\.el\.gz$'; then
        zcat "$file_path" > "/tmp/$$.el" &&
            colorize_src "/tmp/$$.el" &&
            rm -f "/tmp/$$.el"
    else # Others
        run_if_exists atool --list -- "$file_path" ||
            run_if_exists bsdtar --list --file "$file_path"
    fi
}

add handle_rar rar unrar -
handle_rar() {
    [ "$file_extension_lower" = rar ] ||
        return "$RET_NO_MATCH"

    # Avoid password prompt by providing empty password
    run_if_exists unrar lt -p- -- "$file_path"
}

add handle_7z 7z+iso 7z -
handle_7z() {
    [ "$file_extension_lower" = 7z ] ||
        [ "$file_extension_lower" = iso ] ||
        return "$RET_NO_MATCH"

    # Avoid password prompt by providing empty password
    run_if_exists 7z l -p -- "$file_path"
}

add handle_html html w3m,lynx,elinks,pandoc -
handle_html() {
    case "$file_extension_lower" in
        htm|html|xhtml|mhtml) ;;
        *) return "$RET_NO_MATCH" ;;
    esac

    run_if_exists w3m -dump "$file_path"         ||
        run_if_exists lynx -dump -- "$file_path" ||
        run_if_exists elinks -dump "$file_path"  ||
        run_if_exists view_pandoc "$file_path"
}

add handle_json json jq,=text-source -
handle_json() {
    [ "$mimetype" = application/json ] ||
        [ "$file_extension_lower" = json ] ||
        return "$RET_NO_MATCH"

    run_if_exists jq -C . "$file_path" ||
        colorize_src "$file_path"      ||
        cat "$file_path"
}

add handle_markdown markdown pandoc,=text-source -
handle_markdown() {
    case "$file_extension_lower" in
        md|rst) ;;
        *) return "$RET_NO_MATCH" ;;
    esac

    view_pandoc "$file_path"      ||
        colorize_src "$file_path" ||
        cat "$file_path"
}

add handle_csv csv pandoc,cat -
handle_csv() {
    [ "$mimetype" = application/csv ] ||
        [ "$file_extension_lower" = csv ] ||
        return "$RET_NO_MATCH"

    [ "$(du "$file_path" | cut -f 1)" -le 1000 ] && {
        tmp_file_path="${file_path##*/}"
        tmp_file_path="/tmp/${tmp_file_path%.*}.txt"
        run_if_exists pandoc "$file_path" -o "$tmp_file_path" &&
            cat "$tmp_file_path" &&
            rm -f "$tmp_file_path"
    }
}

add handle_diff diff delta,diff-so-fancy,=text-source -
handle_diff() {
    case "$mimetype" in
        text/x-diff | text/x-patch) ;;
        *) return "$RET_NO_MATCH" ;;
    esac

    # use the user-specified git diff pager if it is set
    if git config core.pager >/dev/null; then
        eval "$(git config core.pager)" < "$file_path" && return 0
    fi
    # fancy diff pagers
    run_if_exists delta         < "$file_path" && return 0
    run_if_exists diff-so-fancy < "$file_path" && return 0
    run_if_exists colordiff     < "$file_path" && return 0
    # colorize_src uses highlight or bat, both of which support diff/patch syntax.
    colorize_src "$file_path" && return 0
}

add handle_pdf pdf pdftotext,mutool,exiftool pdftoppm
handle_pdf() {
    [ "$mimetype" = application/pdf ]     ||
        [ "$file_extension_lower" = pdf ] ||
        return "$RET_NO_MATCH"

    if image_needed; then
        if ! image_cached; then
            run_if_exists pdftoppm -f 1 -l 1     \
                     -scale-to-x 1920            \
                     -scale-to-y -1              \
                     -singlefile                 \
                     -jpeg -tiffcompression jpeg \
                     -- "$file_path" "${image_cache_path%.*}" &&
                image_prepare || return
        fi
        image_show_pv
    else
        run_if_exists pdftotext -layout -l 10 -nopgbrk -q -- "$file_path" - &&
            return 0
        run_if_exists mutool draw -F txt -i -- "$file_path" 1-10 && return 0
        run_if_exists exiftool "$file_path" && return 0
    fi
}

add handle_epub epub epub2txt -
handle_epub() {
    [ "$file_extension_lower" = epub ] ||
        return "$RET_NO_MATCH"

    run_if_exists epub2txt "$file_path"
}

add handle_text text-source mdcat,bat,highlight,source-highlight,cat -
handle_text() {
    case "$mimetype" in
        text/* | */xml                | \
            application/javascript    | \
            application/x-elc         | \
            application/x-shellscript | \
            application/x-desktop     | \
            application/x-php) ;;
        *) return "$RET_NO_MATCH" ;;
    esac

    colorize_src "$file_path" ||
        cat "$file_path"
}

add handle_image image exiftool convert,identify
handle_image() {
    case "$mimetype" in
        image/*) ;;
        *) return "$RET_NO_MATCH" ;;
    esac

    if image_needed; then
        if ! image_cached; then
            image_prepare || return
        fi
        image_show_pv
    else
        run_if_exists exiftool "$file_path"
    fi
}

add handle_video video exiftool ffmpegthumbnailer
handle_video() {
    case "$mimetype" in
        video/*) ;;
        *) return "$RET_NO_MATCH" ;;
    esac

    if image_needed; then
        if ! image_cached; then
            ffmpegthumbnailer -i "$file_path" -o "${image_cache_path}" -s 0 &&
                image_prepare || return
        fi
        image_show_pv
    else
        run_if_exists exiftool "$file_path"
    fi
}

add handle_audio audio exiftool -
handle_audio() {
    case "$mimetype" in
        audio/*|application/octet-stream) ;;
        *) return "$RET_NO_MATCH" ;;
    esac

    if image_needed; then
        if ! image_cached; then
            exiftool -b -Picture "$file_path" > "${image_cache_path}" &&
                image_prepare || return
        fi
        image_show_pv
    else
        run_if_exists exiftool "$file_path"
    fi
}

add handle_office office pandoc,libreoffice libreoffice
handle_office() {
    case "$mimetype" in
        application/*office*|application/ms*|application/vnd.ms-*| \
            application/vnd.*.opendocument.*) ;;
        *) return "$RET_NO_MATCH" ;;
    esac

    if image_needed; then
        if ! image_cached; then
            cache_dir="${image_cache_path%/*}"
            tmp_file_path="${file_path##*/}"
            tmp_file_path="${cache_dir}/${tmp_file_path%.*}.jpg"
            rm -f "$tmp_file_path"
            libreoffice                       \
                --headless                    \
                --convert-to jpg "$file_path" \
                --outdir "$cache_dir" >/dev/null        &&
                mv "$tmp_file_path" "$image_cache_path" &&
                image_prepare || return
        fi
        image_show_pv
    else
        tmp_file_path="${file_path##*/}"
        tmp_file_path="/tmp/${tmp_file_path%.*}.txt"
        run_if_exists pandoc "$file_path" -o "$tmp_file_path" 2>/dev/null \
            && cat "$tmp_file_path"                                       \
            && rm -f "$tmp_file_path"                                     \
            && return 0
        run_if_exists libreoffice         \
            --headless                    \
            --convert-to txt "$file_path" \
            --outdir /tmp >/dev/null      \
            && cat "$tmp_file_path"       \
            && rm -f "$tmp_file_path"
    fi
}

add handle_xounralpp xounralpp - xournalpp
handle_xounralpp() {
    [ "$mimetype" != application/x-xopp ] ||
        ! image_needed                    &&
        return "$RET_NO_MATCH"

    if ! image_cached; then
        cache_dir="${image_cache_path%/*}"
        tmp_file_path="${file_path##*/}"
        tmp_file_pathbase="${cache_dir}/${tmp_file_path%.*}"
        rm -f "${tmp_file_pathbase}.jpg"
        rm -f "${tmp_file_pathbase}-"*".jpg"
        # shellcheck disable=SC2015
        run_if_exists xournalpp                     \
            --create-img "${tmp_file_pathbase}.jpg" \
            "$file_path" &&
		    mv "${tmp_file_pathbase}.jpg" "$image_cache_path" ||
		        mv "${tmp_file_pathbase}-1.jpg" "$image_cache_path"
        rm -f "${tmp_file_pathbase}-"*".jpg"
        image_prepare || return
    fi
    image_show_pv
}

add handle_torrent torrent transmission-show -
handle_torrent() {
    [ "$file_extension_lower" = torrent ] ||
        return "$RET_NO_MATCH"

    run_if_exists transmission-show -- "$file_path"
}

add handle_stl stl - openscad+convert
handle_stl() {
    [ "$file_extension_lower" != stl ] ||
        ! image_needed                 &&
        return "$RET_NO_MATCH"

    if ! image_cached; then
        size=512
        tmpf="/tmp/__stpv_$$_stl"
        {
            printf 'import("'
            printf '%s' "$file_path"
            printf '");'
        } > "$tmpf"
        run_if_exists openscad    \
            -o "$tmpf.png"        \
            --imgsize=$size,$size \
            "$tmpf"               \
            2>/dev/null                        &&
            $magick "$tmpf.png" "$tmpf.jpg"    &&
            mv "$tmpf.jpg" "$image_cache_path" &&
            rm "$tmpf"                         &&
            image_prepare || return
    fi
    image_show_pv
}

add handle_drawio drawio - drawio
handle_drawio() {
    [ "$file_extension_lower" = drawio ] ||
        return "$RET_NO_MATCH"

    if image_needed; then
        if ! image_cached; then
            run_if_exists drawio --export --crop \
                          "$file_path"           \
                          -o "$image_cache_path" \
                          >/dev/null &&
                image_prepare || return
        fi
        image_show_pv
    else
        return "$RET_NO_MATCH"
    fi
}

add handle_simulink unzip - unzip
handle_simulink() {
    [ "$file_extension_lower" = slx ] ||
        return "$RET_NO_MATCH"

    if image_needed; then
        if ! image_cached; then
            if ! unzip -l -- "$file_path" |
                    grep -q metadata/thumbnail.png; then
                # no thumbnail found
                return "$RET_NO_MATCH"
            fi
            unzip -p -- "$file_path" metadata/thumbnail.png \
                  > "$image_cache_path" &&
                image_prepare || return
        fi
        image_show_pv
    else
        return "$RET_NO_MATCH"
    fi
}

add handle_proc
handle_proc() {
    echo "$file_path" | grep -q '^/proc/' ||
        return "$RET_NO_MATCH"

    cat "$file_path"
}

add handle_fallback
handle_fallback() {
    if [ -n "$show_fallback" ]; then
        echo '----- File Type Classification -----' &&
            file --dereference --brief -- "$file_path"
    fi
    return "$RET_FALLBACK"
}

main "$@"
