#!/usr/bin/env bash
#
# renumberfiles - renumber a bunch of files sequentially start(arg1)
# by default with an increment of 1 and the number padded to digits(arg2)
#
# ---
# source: https://github.com/mrolli/dotfiles

filter="*"
numdig=2
prefix=""
dryrun="echo"
start=1
save_ext=true

usage() {
  printf %s "\
Usage:
  $(basename "$0") [-f 'filter'] [-d numDigits] [-p prefix 'string'] [-s startInt] [-n]

Renumber a bunch of files sequentially start at ${start}, by default
with an increment of 1 and the number padded to ${numdig} digits.
Filter can be used to select only a subset of all files in the current
working dir or to fix numeric sort, i.e. when normal globbing would sort 10
between 1 and 2 and thus the previous file 10 would become file 02.

This can be fixed with a filter like this:

  $(basename "$0") -f '*.?.jpg *.??.jpg'

Options:
  -d       - Number of the digits to pad the number part to
             (default: ${numdig})
  -f       - Glob pattern to select the files for the action
             (default: ${filter})
  -n       - By default the renaming is carried out as a dry-run to illustrate
             what would happen. Add the flag -n to really rename the files.
  -p       - Prefix to prepend to the number part, also provide the delimiter
             (default: ${prefix})
  -x       - Do not take extension into account
             (default: extension split off before renaming, finally readded again)
             This flag turns this behaviour off.

Flags:
  -h, --help    - Display this message.
"
  exit "${1:-0}"
}

while getopts 'hnd:f:p:s:x' opt; do
  case "${opt}" in
    d) numdig=${OPTARG} ;;
    f) filter="${OPTARG}" ;;
    h) usage 0 ;;
    n) dryrun="" ;;
    p) prefix="${OPTARG}" ;;
    s) start=${OPTARG} ;;
    x) save_ext=false ;;
    *) usage 1 ;;
  esac
done

i="${start}"
workdone=0
for file in ${filter}; do
  ${save_ext} && ext=".${file##*.}"
  name="${prefix}$(printf "%${numdig}s" "${i}" | tr " " "0")"
  i=$((i + 1))
  [ "${file}" = "${name}${ext}" ] && continue
  ${dryrun} mv -i "${file}" "${name}${ext}"
  workdone=1
done

if [ "${workdone}" -eq 0 ]; then
  printf '%s\n' "Nothing to do."
fi

[ -n "${dryrun}" ] \
  && printf '%s\n' "\
This was only a dry-run. Add -n if changes should really take effect.
"

exit 0
