#!/bin/sh
#
# ChangeURL
# Bourne shell script, should work on any Unix-based platform whose
# 'grep' command supports the -R and -l options.
#
# Global search and replace a URL in all html files on a website,
# including in subdirectories.
#
# Install this file in any directory that's in your PATH (or any
# other directory, if you don't mind invoking by specific # pathname).
# Give it execute permission:
#
#   cd (directory where you saved this this)
#   chmod +x ChangeURL
#
# Instructions:
#  1. cd to the desired website directory
#  2. Type "pwd" to make sure you are in the right directory.
#  3. type "ChangeURL.sh url1 url2"
#      (where url1 and url2 are the old and new URLs)
#
# Example:
#
#  cd projects
#  pwd
#  ChangeURL https://www.kermitproject.org http://www.kermitproject.org
#
# Result: Every file that contains the "url1" string is copied to a 
# new file with a ".backup" extension, and then all occurrences of "url1" 
# are changed to "url2" in the original file.
#
# After running the script, check that the modified files are correct.
# If so, you can use the companion script RemoveBackupFiles to delete
# the "*.backup" files.  If not, you can use the script RestoreBackupFiles
# to undo the changes (provided you have not removed the backup files).
#
# Note: As written, this script works only for changing URLs that
# start with "http"; thus it can't be used to change relative URLs or any
# other kind of text.  This is for safety.
#
# Author: Frank da Cruz, 4 June 2017

if [ $# != 2 ]; then
  echo Usage: $0 url1 url2
  exit 1
fi

grep -R xxx /dev/null > /dev/null
if [ $? -eq 2 ]; then
   echo "Fatal: grep command lacks -R option"
   exit 1
fi

grep -l xxx /dev/null > /dev/null
if [ $? -eq 2 ]; then
   echo "Fatal: grep command lacks -l option"
   exit 1
fi

for i in `grep -Rl http . | egrep "\.html$"`; do
   echo -n $i...
   grep $1 $i > /dev/null
   if [ $? -eq 0 ]; then
     cat $i | sed -e "s|$1|$2|g" > /tmp/_x || exit 1
     cp -p $i $i.backup || exit 1
     mv /tmp/_x $i || exit 1
     chmod 644 $i || exit 1
     echo OK
   else
     echo "(no change)"
   fi
done
exit
