#!/usr/bin/env bash

# use vim to rename all the files provided as arguments
# bails if the number of lines do not match the number of arguments
#
# bash renamer.sh *.jpg

bail() { echo "error: $*" >&2; exit 1; }

renamer() {

  cleanup() { [[ $tmp ]] && rm -f "${tmp}"; }
  trap cleanup EXIT

  tmp="$( mktemp )"

  for file in "$@"; do
    echo "$file"
  done > "$tmp"

  vim "$tmp"

  (( $# != $( wc -l "$tmp" | awk '{print $1}' ) )) && {
    bail "file lines do not match number of arguments"
  }

  while read -r line; do

    if [[ $1 == "$line" ]]; then
      echo "leaving $line"

    else
      mv --no-clobber --verbose -- "$1" "$line" ||
        bail "mv --verbose $1 $line failed"
    fi

    shift
  done < "$tmp"
}

if [[ $1 ]]; then
  renamer "$@"
else
  # shellcheck disable=SC2035
  renamer *
fi
