#!/bin/sh

init_variables() {
  progname=${0##*/}

  tmpfile_orig="$(mktemp)"
  tmpfile_dest="$(mktemp)"
  trap 'rm -f -- "${tmpfile_orig}" "${tmpfile_dest}"' EXIT
}

exit_error() {
  [ -z "$1" ] || echo "${progname}: $1"
  exit 1
} >&2

init_files() {
  ls >"${tmpfile_orig}"
  cp -- "${tmpfile_orig}" "${tmpfile_dest}"
}

edit() {
  "${EDITOR:-vi}" "${tmpfile_dest}"
}

validate_files() {
  ORIG_COUNT="$(wc -l "${tmpfile_orig}" | cut -d' ' -f1)"
  DEST_COUNT="$(wc -l "${tmpfile_dest}" | cut -d' ' -f1)"

  if [ "${ORIG_COUNT}" -ne "${DEST_COUNT}" ]; then
    exit_error 'Lines count mismatch'
  fi
}

rename() {
  paste "${tmpfile_orig}" "${tmpfile_dest}" \
    | while read -r line; do
      file_orig="$(echo "${line}" | cut -f1)"
      file_dest="$(echo "${line}" | cut -f2)"
      mv "${file_orig}" "${file_dest}"
    done
}

init_variables

init_files
edit
validate_files
rename
