#! /bin/csh -f

# Usage:
#
#    html-rename-pages -f <sed-script>
#
# where <sed-scrip> is a sed(1) script that describes the
# transformation from old page names to new page names. 
#
# The command finds all .html* source files and [Mm]akefiles
# in the current directory, renames them
# to new names as described by the given <sed script>, and then
# pipes them through the given <sed-script>.

set path = ( /usr/ucb /usr/bsd /usr/bin /bin )

if ( ( $#argv != 2 ) || ( "x$1" != "x-f" ) ) then
  echo "Usage: $0 -f <sed-script>"
  exit 1
endif

set script = "$2"
set temp = "/tmp/$$"

rm -f ${temp}-OLD-SOURCES ${temp}-MAKEFILES

find ./ \
  -type f \
  \( -name '[A-Za-z]*.html' \
  -o -name '[A-Za-z]*.html*[a-zA-Z0-9]' \
  \) \
  -print >> ${temp}-OLD-SOURCES

find ./ -type f -name 'makefile' -print  >> ${temp}-MAKEFILES
find ./ -type f -name 'Makefile' -print  >> ${temp}-MAKEFILES

rm -f ${temp}-NEW-SOURCES

# Rename files:

foreach old ( `cat ${temp}-OLD-SOURCES` )
  if ( ! ( -e $old ) ) then 
    echo "file $old not found"
  else
    set new = "${old:h}/`echo ${old:t} | sed -f $script`"
    if ( "x$old" == "x$new" ) then
      echo "$old" >> ${temp}-NEW-SOURCES
    else if ( -e $new ) then
      echo "file $new already exists"
    else
      echo -n "$old -> $new ?"
      if ( "x$<" == "xy" ) then
        mv $old $new
        echo "$new" >> ${temp}-NEW-SOURCES
      else
        echo "$old" >> ${temp}-NEW-SOURCES
      endif
    endif
  endif
end

# Filter files through script:

${STOLFIHOME}/bin/sed-files -f $script `cat ${temp}-NEW-SOURCES ${temp}-MAKEFILES | sort`

rm ${temp}-OLD-SOURCES ${temp}-NEW-SOURCES ${temp}-MAKEFILES

exit 0
