#! /bin/bash
# Last edited on 2022-09-09 11:34:51 by stolfi

# Reads a bunch of lines from {stdin}, presumably from a 00-README file.
# 
# Looks for lines that have the form "${FNAME} --> ${NEWDIR} ${COMMENTS}".
# 
# Moves each file ${FNAME} from the current directory to the directory
# ${NEWDIR}.
# 
# Appends the line, minus the "-->
# ${NEWDIR}" part, to the file "${NEWDIR}/00-README".
# 
# Prints other lines to standard output

tmp="/tmp/$$"

mvfile="${tmp}.moves"
dirfile="${tmp}.dirs"
errfile="${tmp}.errs"
rm -f ${mvfile} ${dirfile} ${errfile}

gawk \
    -v mvfile=${mvfile} \
    -v dirfile=${dirfile} \
    -v errfile=${errfile} \
    ' /[ ][-][-][>][ ]/ {
        if (NF < 4) { printf "%d: ** bad {NF} [[%s]]\n", FNR, $0 >> errfile; next; } 
        if ($2 != "-->") { printf "%d: ** bad format [[%s]]\n", FNR, $0 >> errfile; next; } 
        fn = $1; newdir = $3; 
        # printf "%s --> %s\n", fn, newdir > "/dev/stderr"
        printf "%s\n", newdir >> dirfile
        qt = "\047";
        printf "mv -vi %s%s%s %s/\n", qt, fn, qt, newdir >> mvfile;
        lin = $0;
        gsub(/[ ]*-->[ ]*[^ ]+[ ]*/, " ", lin);
        printf "%s\n", lin >> (newdir "/00-README");
        next;
      }
      // { print; next; }
    '
    
dirbug=0
if [[ -s ${dirfile} ]]; then
  for dir in `cat ${dirfile} | sort | uniq` ; do 
    if [[ ! (-d ${dir} ) ]] ; then
      echo "** ${dir} is not a directory" 1>&2 
      dirbug=1
    fi
  done
fi

if [[ -s ${errfile} ]]; then 
  cat ${errfile} 1>&2
fi

if [[ ( -s ${errfile} ) || ( ${dirbug} -gt 0) ]]; then 
  echo "** no moves done" 1>&2 
fi

if [[ -s ${mvfile} ]]; then
  source ${mvfile}
fi

