#!/bin/bash

#FUNCTION DEFS
#filename of the form in.### where a file of this name does not exist
oldfilename() {
  in=$1
  i=0
  istr=`printf "%03d" $i`
  out=$in.$istr
  while [[ -e $out ]]; do
    i=$(( i + 1 ))
    istr=`printf "%03d" $i`
    out=$in.$istr  
  done
  echo $out
}

#MAIN
replist=$1
extension=$2
usage="
Usage:  replacer.sh <replacement list> <search extension>

This script makes backups of each file each time it is run (numbered 000, 001,
etc).  However, to be safe, you should always back up your code tree to a safe
place before running this script!

The replacement list file should have two columns:  The first is the value to be
replaced, the second is the value to replace with.

The search extension is the extension type of the files to be replaced.  Do not
include the '.'.  If you want to replace all .mf files, specify just 'mf' here.
Each find and replace will be executed on all files in all subdirectories of
the working directory that have the extension specified by the search extension
parameter.

" 

if [[ ! -e "$replist" ]]; then
  echo "ERROR:  Replacement list $replist does not exist."
  echo -e "$usage"
  exit -1
fi

if [[ "${#extension}" -le "0" ]]; then
  echo "ERROR:  You must specify a search extension."
  echo -e "$usage"
  exit -1
fi


#find all the mf files
files=`find -iname "*.${extension}"`

#make backups
for file in $files; do
    #back up the old file
    oldfile=`oldfilename $file`
    echo "Backing up $file"
    echo "  to $oldfile"
    echo
    cp "$file" "$oldfile"
done

#iterate over replacements
cat $replist | dos2unix | grep -v -e "^;" | while read finder replacer errfield; do
  if [[ "${#errfield}" -gt "0" ]]; then
    echo "******************************************************************************"
    echo
    echo "Syntax error:  Too many arguments on line:  $finder $replacer $errfield"
    echo "This line was skipped!"
    echo
    echo "******************************************************************************"
    continue;
  fi
  if [[ "${#finder}" -eq "0" ]]; then
    echo "Skipping blank line"
    continue;
  fi
  if [[ "${#replacer}" -eq "0" ]]; then
    echo "Skipping empty replace"
    continue;
  fi
  echo "Replacing '$finder' with '$replacer'"
  #replace each one
  for file in $files; do
    echo "  in $file"
    sed -i "s/$finder/$replacer/g" $file  
  done
done
echo "replacer finished"
