#!/bin/sh
#
# v - quick shortcut to an editor
#
# usage:
#     $ v
#     # => opens the current directory in your editor
#
#     $ v .
#     $ v /usr/local
#     # => opens the specified directory in your editor
#
# ---
# see: https://github.com/itchyny/bin
#
# see: https://github.com/pengwynn/dotfiles/blob/master/bin/e
# see: https://github.com/holman/dotfiles/blob/master/bin/e
#     exec "${EDITOR-}" "${1:-.}"

case "$#" in
  0)
    if command -v nvim >/dev/null 2>&1; then
      # set -- -
      # shift
      exec "${EDITOR:-nvim}"
      # exec "${EDITOR:-nvim}" +copen -q -
    else
      # true if file descriptor fd is open and refers to a terminal
      if [ -t 0 ]; then
        exec ${EDITOR:-vi} "$@" </dev/tty
      elif [ -t 1 ]; then
        f=$(mktemp)
        cat /dev/stdin >"${f}"
        ${EDITOR:-vi} --cmd "set efm=%f:%l:%c:%m,%f:%l:%m,%f:%s,%f" -q "${f}" </dev/tty
        exit_code="$?"
        rm -f "${f}" || :
        exit "${exit_code}"
      else
        exec ${EDITOR:-vi} "$@"
      fi
    fi
    ;;
  1)
    if [ -d "$1" ]; then
      exec "${EDITOR:-vi}" -c ":lcd %:p:h" "${1:-.}"
    else
      exec "${EDITOR:-vi}" "${1:-.}"
    fi
    ;;
  *)
    case "$1" in
      -*)
        arg="$1"
        shift
        exec "${EDITOR:-vi}" "${arg-}" "${@:-.}"
        ;;
      *)
        if [ "$#" -gt 1 ]; then
          exec "${EDITOR:-vi}" -p "$@"
        else
          exec "${EDITOR:-vi}" "${@:-.}"
        fi
        ;;
    esac
    ;;
esac
