#!/usr/bin/env bash
#
#   vlst - view the .lst file(s) corresponding to the given source file(s)
#
#   • This brings up the the files in vim as the arglist; `:next` and
#     `:previous` will cycle through them.
#   • `autoread` is set so that when changing to a file it will be
#     automatically reloaded if the source was rebuilt.
#   • If only one file is given, /dev/null is added to the end of the
#     vim argument list so you can :next :previous to reload the current
#     file instead of having to type :e. (This assumes that :next and
#     :previous are bound to quick-access keys such as ^N and ^P.)
#   • A few other options are set to make the formatting nice.
#
#   Bugs:
#   • This works only for paths relative to $T8_PROJDIR; it should find
#     the absolute path and then part of that relative to $T8_PROJDIR to
#     find the listing file location in the build directory.
#   • For this program, :quit should exit rather than complaining when the
#     last buffer hasn't been edited.
#   • Doesn't check to see if source or list files exist.
#
set -eu -o pipefail

die() { local code="$1"; shift; echo 1>&2 "$@"; exit $code; }
usage() { die 2 "Usage: vlst source-file ..."; }

####################################################################

lstfiles=()

for f in "$@"; do
    lstfiles+=("$T8_PROJDIR"/.build/obj/${f%.*}.lst)
done

case ${#lstfiles[@]} in
    0) usage;;
    1) lstfiles+=(/dev/null)
esac

exec vim -R -c 'set autoread nolist nowrap' ${lstfiles[@]}
