#!/bin/sh

text_handle() {
    # Handle all other formats as text and cat them
    # if highlighting tools are aviable, try to use them
    if command -v bat > /dev/null; then
        bat -pp --color=always "$1"
    elif command -v highlight > /dev/null; then
        highlight "$1" --out-format ansi --force
    else
        cat "$1"
    fi
}

run_cmd() {
    cmd="$1"
    shift

    if command -v "$cmd" > /dev/null; then
        $cmd $@
    else
        # If we didn't found the requested command, check if
        # the file is text-like and try to use the text_handle
        # to show the preview, this may not be ideal for given
        # file-format, but at least we won't fail.
        case $(file --mime-type "$file" -bL) in
            text/*|application/json)
                echo "@@PREVIEW FALLBACK: Using text handle, $cmd command not found!"
                text_handle "$file"
                ;;
            *)
                echo "@@PREVIEW ERROR: Preview failed, $cmd command not found!"
                ;;
        esac
    fi
}

# Capture all directories at first, since they could
# potentionally match one of the file case statements
if [ -d "$1" ]; then
    tree "$1" -La 1
elif [ -f "$1" ]; then
    case "$1" in
        *.png|*.jpg|*.jpeg|*.mkv|*.mp4|*.m4v) run_cmd mediainfo "$1";;
        *.pdf) run_cmd pdftotext "$1";;
        *.tgz|*.tar.gz) run_cmd tar tzf "$1";;
        *.tar.bz2|*.tbz2) run_cmd tar tjf "$1";;
        *.tar.txz|*.txz) run_cmd xz --list "$1";;
        *.tar) run_cmd tar tf "$1";;
        *.zip|*.jar|*.war|*.ear|*.oxt) run_cmd unzip -l "$1";;
        *.rar) run_cmd unrar l "$1";;
        *.7z) run_cmd 7z l "$1";;
        *.iso) run_cmd iso-info --no-header -l "$1";;
        *.o) run_cmd nm "$1" | less ;;
        *.csv) cat "$1" | sed s/,/\\n/g ;;
        *odt,*.ods,*.odp,*.sxw) run_cmd odt2txt "$1";;
        *.doc) run_cmd catdoc "$1" ;;
        *.docx) run_cmd docx2txt "$1" - ;;
        *.torrent) run_cmd transmission-show "$1";;
        *) text_handle "$1" ;;
    esac
fi