#! /bin/bash
# Last edited on 2020-11-29 09:37:38 by jstolfi

# Renames a bunch of ".png" scan files with page-based names.

issue="$1"; shift;
spec="$1"; shift

issuedir="00-DATA/scan/raw/${issue}"

# usage: ${cmd} ${issue} ${spec} > .rename && source .rename
#
# where ${issue} is the issue's ISO date and ${spec} is a list
# of comma-separated rename specs.  Should be executed in the 
# directory ${issuedir}.
#
# Each rename spec should be "${oini}..${ofin}=${nini}..${nfin}"
#  meaning that each two consecutive figure numbers in the first range
#  is a page from the second range, top and bottom;  or

check_dir_tail.sh "${issuedir}"

gawk \
    -v spec="${spec}" \
    ' BEGIN {
        printf "spec = %s\n", spec  > "/dev/stderr"
        while (spec != "") {
          if (! match(spec, /^([.0-9]+)[=]([.0-9]+)[,]?(.*)$/, ff)) {
            printf "**bad spec %s\n", spec > "/dev/stderr"; exit(1)
          }
          old=ff[1];
          new=ff[2];
          spec=ff[3];
          printf "renaming %s to %s\n", old, new  > "/dev/stderr"
          if (match(old, /^([0-9]+)[.][.]([0-9]+)$/, og)) {
            if (! match(new, /^([0-9]+)[.][.]([0-9]+)$/, ng)) {
              printf "**bad spec multipair %s=%s\n", old, new > "/dev/stderr"; exit(1)
            }
            oini = og[1]+0;  ofin = og[2]+0;
            nini = ng[1]+0;  nfin = ng[2]+0;
            nk = nini;
            for (ok = oini; ok <= ofin; ok += 2) {
              printf "mv -vi %02d.png p%02d-1.png\n", ok, nk
              printf "mv -vi %02d.png p%02d-0.png\n", ok+1, nk
              nk++
            }
            printf "\n"
            if (nk != nfin+1) {
              printf "**mismatched file lists %s=%s\n", old, new > "/dev/stderr"; exit(1)
            }
          } else {
             printf "**bad spec pair %s=%s\n", old, new > "/dev/stderr"; exit(1)
          }
        }
      }
    '

