#!/bin/bash
Prog=${0##*/}
__SUMMARY__=$(cat <<__TLDR__
$Prog

Open a command in an editor if that command is a script.

If X is available and -nw is not passed, will use \$XEDITOR or gvim.
Otherwise will use \$VISUAL or \$EDITOR or vim, whichever is found
first.

Usage:
    $Prog [-nw] COMMAND

    -nw        Do not use a GUI editor, even if X is available

__TLDR__
)

fail () {
    set +exu
    ret=${1}
    shift
    echo "$Prog:" "$@" >&2
    exit "$ret"
}

usage () {
    echo >&2 "$__SUMMARY__"
    exit "$1"
}

if [[ $1 = -h* || $1 = --h* ]]; then
    usage 0
fi

if [[ -n $DISPLAY ]]; then
    use_x=true
else
    use_x=false
fi
if [[ ${1:-} == -nw ]]; then
    use_x=false
    shift
fi

if [[ -z $1 ]]; then
    echo >&2 "Command not provided"
    usage 2
fi
command=$1

command_type=$(type -t "$command"); ret=$?
if [[ $ret != 0 ]]; then
    fail 3 "$command not found"
fi

if [[ $command_type != file ]]; then
    fail 4 "$command is not a script (probably a shell function or alias)"
fi

command=$(command -v "$command")

if file "$command" | cut -d: -f 2- | grep -q ELF; then
    fail 5 "$command is a binary"
fi

editor=
if $use_x; then
    editor=${XEDITOR:-gvim}
fi
if ! ( [[ $editor ]] && command -v "$editor" &>/dev/null ); then
    editor=${VISUAL:-${EDITOR:-vim}}
fi

if ! command -v "$editor"; then
    fail 127 "No editor found"
fi

"$editor" "$command"
