#!/bin/sh

# Vimer - A convenience wrapper for gvim/mvim --remote(-tab)-silent.

# The MIT License (MIT)
# Copyright (c) 2010-2016 Susam Pal
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

VERSION=0.2.1-DEV
AUTHOR="Susam Pal"
COPYRIGHT="Copyright (c) 2010-2016 $AUTHOR"

LICENSE_URL="http://susam.in/licenses/mit/"
SUPPORT_URL="https://github.com/susam/vimer/issues"

NOTICE="
This is free and open source software. You can use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of it,
under the terms of the MIT License. You can obtain a copy of the
MIT License at <$LICENSE_URL>.

This software is provided \"AS IS\", WITHOUT WARRANTY OF ANY KIND,
express or implied. See the MIT License for details."

NAME=${0##*/}

TMP_DIR=/tmp/vimer
EDITORS="gvim mvim"

# Starting point of this script.
# Arguments: All arguments this script was invoked with
main() {
    VIM_CMD=${VIM_CMD:-$(find_vim)}
    parse_arguments "$@"
}

# Find a GVim or MacVim.
# If either GVim or MacVim is found, print its name; do not print
# anything otherwise.
find_vim() {
    for v in $EDITORS; do
        if command -v "$v" >/dev/null 2>&1; then
            printf "%s" "$v"
            return
        fi
    done
    # Finally try $EDITOR
    if [ -n "$EDITOR" ] && command -v "$EDITOR" >/dev/null 2>&1; then
        printf "%s" "$EDITOR"
    fi
}

# Parse command line arguments passed to this script.
# Arguments: All arguments this script was invoked with
# Errors: Exit with an error message if invalid arguments are specified.
parse_arguments() {
    while [ $# -gt 0 ]; do
        case $1 in
            -t|--tab)
                tab=-tab
                ;;
            -s|--server)
                [ $# -lt 2 ] && quit "Argument missing after: \"$1\"."
                server=$2
                shift
                ;;
            -n|--name)
                printf "%s\n" "$VIM_CMD"
                exit
                ;;
            -h|--help)
                show_help
                exit
                ;;
            -v|--version)
                show_version
                exit
                ;;
            --) # End of all options
                shift
                break
                ;;
            -*)
                quit "Invalid option: $1"
                ;;
            *)
                break
                ;;
        esac
        shift
    done

    if [ $# -eq 0 ]; then
        exec_vim
    elif [ "$1" = "-" ]; then
        [ $# -gt 1 ] && quit "Too many edit arguments: \"$2\"."
        exec_vim_with_stdin
    else
        exec_vim "$@"
    fi
}

# Save standard input in a temporary file and edit it.
exec_vim_with_stdin() {
    mkdir -p "$TMP_DIR" || quit "Cannot create temporary directory: $TMP_DIR."
    stdin_file=$(mktemp "$TMP_DIR/_STDIN_XXXXXX")
    cat > "$stdin_file"
    exec_vim "$stdin_file"
}

# Execute GVim or MacVim with specified arguments.
# Arguments: All arguments specified as individual arguments.
# Errors: Exit with an error message if VIM_CMD variable is not set.
exec_vim() {
    [ -z "$VIM_CMD" ] && quit "Cannot find GVim or MacVim."
    opts=""
    [ -n "$server" ] && opts="$opts --servername $server"
    [ -n "$tab" ] && opts="$opts --remote$tab-silent"
    [ $# -gt 0 ] && opts="$opts --remote-silent"
    eval exec "$VIM_CMD" $opts "$@"
}

# Terminate the script with an error message.
# Arguments: String to print to standard error stream.
# Errors: Unconditionally cause the script to terminate with an error message and exit code 1.
quit() {
    printf "%s: %s\n" "$NAME" "$*" >&2
    exit 1
}

# Show help.
show_help() {
    cat <<eof
Usage: $NAME [-t] [-s NAME] [-n] [-h] [-v] [--] [-|FILE...]
This is a wrapper script to open files in existing GVim or MacVim.
If an existing instance of GVim or MacVim is running, the files are
opened in it, otherwise, a new GVim or MacVim instance is launched.
If no arguments are specified, a new GVim or MacVim instance is
launched.

If this script cannot find GVim or MacVim, set the VIM_CMD environment
variable with the command to execute GVim or MacVim as its value.

Arguments:
  -                  Read text from standard input.
  FILE...            Read text from one or more files.

Options:
  -t, --tab          Open each file in new tab.
  -s, --server NAME  Open files in GVim server with specified NAME.
  -n, --name         Show the name/path of GVim/MacVim being used.
  -h, --help         Show this help and exit.
  -v, --version      Show version and exit.

Report bugs to <$SUPPORT_URL>.
eof
}

# Show version and copyright.
show_version() {
    cat <<eof
Vimer $VERSION
$COPYRIGHT
$NOTICE
eof
}

# Start.
[ -z "$import" ] && main "$@"
