#!/bin/ksh -x

f="$1"

if [ -z "$f" ];
then
    echo "no argument given"
    exit 2
fi

###################################################
# SSH
###################################################

if print "$f" | egrep -qi '^shell:|^ushell:|^cvs:|^home:';
then
    _server=${f%%:*}
    _dir=${f#*:}
    ssh -tt $_server "vim $_dir"
    exit 0
fi

###################################################
# TRY TO FIND MIME TYPE
###################################################

if print "$f" | egrep -qi '^http[s]{0,1}://';
then
    MIME="$(webmime "$f")"
    TYPE="http"
fi

if print "$f" | egrep -qi '^gopher[s]{0,1}://';
then
    MIME=""
    TYPE="gopher"
fi

if [ -f "$f" ]
then
    MIME="$(file -ib "$f")"
    TYPE="file"
fi

###################################################
# TRANSLATE MIME TYPES TO EXTENSIONS
###################################################

case "$MIME" in
    # full qualified
    application/ogg) EXT=ogg; ;;
    application/pdf) EXT=pdf; ;;
    application/postscript) EXT=ps; ;;
    application/vnd.oasis.opendocument.*) EXT=docx; ;;
    audio/mpeg) EXT=mp3; ;;
    audio/midi) EXT=midi; ;;
    image/webp) EXT=webp; ;;
    application/x-gzip) EXT=gz; ;;
    # with wildcards
    audio/*) EXT=generic_audio; ;;
    video/*) EXT=generic_video; ;;
    image/*) EXT=generic_image; ;;
    # vim can handle a lot!
    text/*) EXT=generic_text; ;;
esac

# no extension yet? Extract from file
[ -z "$EXT" ] && EXT="$(print "${f##*.}" | tr '[:upper:]' '[:lower:]')"

case "$EXT" in
    aiff) EXEC="mpv"; ;;
    mkv) EXEC="mpv"; ;;
    docx) EXEC="libreoffice"; ;;
    flv) EXEC="mpv"; ;;
    m2ts) EXEC="mpv"; ;;
    mp3) EXEC="mpv"; ;;
    mp4) EXEC="mpv"; ;;
    pdf) EXEC="zathura"; ;;
    out) EXEC="kdump -RTf"; ;;
    sid) EXEC="sidplay"; ;;
    torrent) EXEC="aria2c"; ;;
    txt) EXEC="vim"; ;;
    webm) EXEC="mpv"; ;;
    xlsx) EXEC="libreoffice"; ;;
    jpg) EXEC="nsxiv"; ;;
    generic_text) EXEC="vim"; ;;
    generic_video) EXEC="mpv"; ;;
    generic_image) EXEC="nsxiv"; EXEC_HTTP="$BROWSER"; ;;
    generic_audio) EXEC="mpv"; ;;
esac

echo "TYPE=$TYPE | MIME=$MIME | EXT=$EXT | EXEC=$EXEC"

case "$TYPE" in
    gopher) exec $EXEC_GOPHER "$f"; ;;
    http) exec $EXEC_HTTP "$f"; ;;
    file) exec $EXEC "$f"; ;;
esac

exit 0
