#!/bin/sh

# Takes a directory name as an argument.  Searches for files that have
# the string "perl" in the first line, and replace the first line with
# a line pointing to the location of perl on the local machine.

# it could be that a user has perl aliased to a better (newer) version than
# the default. In that case, "which perl" will give a line like:
# perl:   aliased to /usr/local/perl561/bin/perl
# We do a little parsing here to guard against such a case - Split on /
# so that we just get tokens usr, local, perl561,..., then concatanate the
# tokens back together and print them. They can't be printed one at a time,
# because awk wants to put newline characters in between.
perlloc=`/bin/csh -c "which perl" | awk -F/ '{for (i=2; i<=NF; i++) x=x"/"$i; print x}'`
list=`/bin/ls $1`
#echo "converting perl programs in \"$1\""
for file in $list
do
 if [ -f $1/$file ]
 then
   line=`head -1 $1/$file`
   echo $line | grep perl  > /dev/null
   if [ $? = 0 ]
   then
      echo "#!"$perlloc > tp_tempfile 
      nlines=`wc -l $1/$file | awk '{print$1}'`
      nlines=`expr $nlines - 1`
#      echo "  $1/$file $nlines lines"
      tail -$nlines $1/$file >> tp_tempfile
      sed s\%"^[ 	]*use constant PSTDIR.*"%"use constant PSTDIR => \"$2\";"%g tp_tempfile > tp_tempfile2
      mv tp_tempfile2 $1/$file
      /bin/rm tp_tempfile
      chmod +x $1/$file
   fi
 fi
done
