#!/bin/sh -
#
# vils - `edit an ls`, i.e. it will load a list of filenames into your editor
# any changes to the filenames will result in renaming the respective files
#
# note:
#  - do not change the numbers in the first column, unless you know exactly
#    what you're doing
#  - if you remove an entire line, the corresponding file will _not_ be deleted
#    it just remains untouched
#  - you can use any character in filenames, with one special case:
#    backslashes have to be specified twice
#  - if there are any filename collisions, you will be asked if overwriting
#    the first file is OK
#  - do not try to exchange the filenames of two or more files. it won't work
#  - if you want to edit the filenames of certain files only, you can specify
#    them on the command line (default is ``*'')
#
# ---
# see: https://src.userspace.com.au/vils/tree/vils
# see: https://github.com/felix/vils

if [ -n "${VISUAL}" ]; then
  VICMD="${VISUAL}"
elif [ -n "${EDITOR}" ]; then
  VICMD="${EDITOR}"
elif command -v nvim >/dev/null 2>&1; then
  VICMD="nvim"
else
  VICMD="/usr/bin/vi"
fi

if [ "$1" = "--" ]; then
  shift
elif expr "x$1" : 'x-' >/dev/null; then
  printf '%s\n' "Usage: vils [file ...]" >&2
  exit 1
fi

# do not use a publicly writable directory such as `/tmp`, which would be a
# security hole because of possible race conditions!
tmp="$(mktemp "${TMPDIR:-/tmp}"/"$(basename "$0")".XXXXXX)" || exit

# shellcheck disable=SC2329
cleanup() {
  rm -f "${tmp}" "${tmp}".new
  exit 1
}
# trap cleanup 1 2 3 15
trap cleanup HUP INT QUIT TERM

path=.
[ "$#" -gt 0 ] && path="$*"

find "${path}" -maxdepth 1 \
  | sed "/^${path}$/d;s|^\./||" \
  | awk '{ printf "%04d %s\n", NR, $0 }' >"${tmp}"
cp "${tmp}" "${tmp}".new

${VICMD} "${tmp}".new

(
  cat "${tmp}"
  echo "xxx"
  cat "${tmp}".new
) \
  | awk '{
    if ($1 == "xxx")
      new=1;
    else if (!new)
      old[$1] = substr($0, 6);
    else {
      new = substr($0, 6);
      if (old[$1] && new && old[$1] != new)
        printf "%s|%s\n", old[$1], new;
    }
  }' \
  | (
    IFS='|'
    while read -r OLD NEW; do
      mv -i -- "${OLD}" "${NEW}"
    done
  )

rm -f "${tmp}" "${tmp}".new
exit 0
