#! /bin/bash

help() {
    echo ""
    echo "Replace script for MEGAlib";
    echo "Copyright by Andreas Zoglauer"
    echo "";
    echo "Usage: replace 'original string' 'new string' directory additional-file-suffixes";
    echo "";
    echo "Remark 1: The quotation marks are only necessary if the string contains space characters.";
    echo "Remark 2: File-suffixes may be empty. Then only the defaults are used.";
    echo "";
}

Exchange() {
    echo "  Looking for $type-files"
    pat="*."$type;
    for i in $pat; do
        if (`test -e $i`); then
            echo "  Analysing file: $i";
            base=${i%.$type};
            newfile="/tmp/"$base"."$type".new";
            echo "sed s|$start|$stop|g"
            sed "s|$start|$stop|g" $i > $newfile;
            ret=`diff $i $newfile`;
            if (`test -z "$ret"`); then
                echo "    No modification necessary";
                rm -f $newfile
            else
                echo "    Updating file";
                mv $newfile $i;
            fi
        else
            echo "  No files found!"
        fi
    done
};


if [ $# -lt 3 ] ; then
    help; 
    exit 0;
fi;


start=$1
shift
stop=$1
shift
directory=$1
shift

types="cxx cpp cc h hh f"
while [ $# -gt 0 ] ; do
    types=$types" "$1
    shift
done



# Do some sanity checks on the input:
substr() {
  echo "$1" | cut -c$2-`expr $2 + $3 - 1`
}

length=${#start}

last='-'
for inc in `seq 1 $length`; do
    char=`substr "${start}" ${inc} 1`
    if ([ "$char" == "/" ] && [ "$last" != "\\" ]); then 
        echo "Error: All \"/\" must be preceded by a \"\\\"!"
        exit 1;
    fi
    last=$char
done

length=${#stop}

last='-'
for inc in `seq 1 $length`; do
    char=`substr "${stop}" ${inc} 1`
    if ([ "$char" == "/" ] && [ "$last" != "\\" ]); then 
        echo "Error: All \"/\" must be preceded by a \"\\\"!"
        exit 1;
    fi
    last=$char
done

current=`pwd`

for file in `find $directory -type d`; do
    dir=$current"/"$file;
    rcvs=`echo $dir | awk '{printf("%i\n",index($0,"CVS"))}'`
    rsvn=`echo $dir | awk '{printf("%i\n",index($0,".svn"))}'`
    if ([ $rcvs = 0 ] && [ $rsvn = 0 ]); then
        echo "Changing to $dir...";
        cd $dir;
        for type in $types; do
            rename ${start} ${stop} *.${type}
            Exchange;
        done
    fi
done

exit
