#!/bin/sh -e
#
# Swiss army knife file opener.
#
# How is this different than xdg-open/mimeopen?
# - Can open multiple files at once, eg: o *.jpg
# - Handles terminal window tabbing (swallowing)
# - Doesn't fork a new process and terminal apps are run in the same terminal
# - Doesn't hide the program's stdout/stderr
# - Correctly handles weird filenames, including starting with a hyphen
# - Special handling for viewing markdown and other documents
# - Adds files to GTK's recently used file list
# - Is easier to type :)

# Default to opening the current directory
if [ "$#" -lt 1 ]; then
  set - "${PWD}"
fi

# Add files to GTK's recently used files list
if command -v file-history >/dev/null 2>&1; then
  file-history "$@" &
fi

case $(file --mime-type -bL -- "$1") in
  image/x-xcf | image/svg+xml | font/* | model/*)
    # Fallback to using mimeopen for specific media types
    i3-tabbed mimeopen --magic-only --no-ask -- "$@"
    ;;

  image/*)
    i3-tabbed sxiv -b -- "$@"
    ;;

  video/*)
    i3-tabbed mpv -- "$@"
    ;;

  application/pdf)
    i3-tabbed zathura -- "$@"
    ;;

  audio/*)
    # don't tab because mpv won't open a window
    mpv --audio-display=no -- "$@"
    ;;

  inode/directory)
    eza -- "$@"
    ;;

  application/gzip | application/java-archive | application/x-7z-compressed | \
    application/x-bzip2 | application/x-rar | application/x-tar | \
    application/x-xz | application/zip)
    prvw "$@"
    ;;

  *)
    # unknown mimetype, use the file extension to figure out what to do from here
    case "$1" in
      *.md | *.rst | *.docx | *.odt | *.epub)
        i3-tabbed pandoc-view "$1"
        ;;
      *.[1-8])
        man --local-file -- "$@"
        ;;
      *)
        ${EDITOR:-vi} -- "$@"
        ;;
    esac
    ;;
esac
