#!/usr/bin/env sh

set -eu

usage() {
  cat <<EOF

viml: Open file at specific line

Usage:
  viml <file>:<line>

Environment:
  EDITOR      The Vim editor to launch. [default: vim]

EOF
}

if [ "$#" -ne 1 ]; then
  2>&1 echo 'error: Only one <file>:<line> can be given'
  2>&1 usage
  exit 1
fi

file_line="$1"
IFS=: read -r file line <<EOF
${file_line}
EOF

if [ "${file}" = "" ]; then
  2>&1 echo 'error: Colon-separated file name was empty'
  2>&1 usage
  exit 1
fi

if [ "${line}" = "" ]; then
  2>&1 echo 'error: Colon-separated line number was empty'
  2>&1 usage
  exit 1
fi

# explicitly going for wordsplitting, to allow for when EDITOR has flags in it
# shellcheck disable=SC2086
exec ${EDITOR:-vi} "${file}" "+${line}"
