#!/bin/sh

#
# Designed to work with the "ednew" script, to generate a consolidated patch
# file for a directory tree.  Requires GNU diff or equivalent (something that
# can generate usable patch input.
#
# This code copyright October 1998 by
# W.M. Richards, NiEstu, Phoenix, AZ -- chipr@niestu.com
#
# This software is made freely available under the provisions of the Perl
# "Artistic" license:  http://language.perl.com/misc/Artistic.html
#
# This code is not supported and is not warranteed to perform any particular
# function. Contact chipr@niestu.com for aditional information.
# If you find bugs or make enhancements, it would be appreciated if you
# sent them on to the author at chipr@niestu.com.
#

#
# Usage: cd to top-level directory, run "patchgen patch-file-name".  Will
# run find and re-invoke itself with the "-p" argument to generate patches.
#

#
# Configuration
suffix="original"
diffopts="-u"

#-----------------------------------------------------------------------------

#
# Function to print syntax message and quit
function show_help
{
   cat <<EOF

Syntax:

   $0  patch-file-name

Make sure you are in the top-level directory of the tree.  Assumes that you
have used "ednew" or equivalent process to create ".$suffix" files containing
the original source.

EOF
   exit -1
}

#-----------------------------------------------------------------------------

#
# Function to create a patch and add it to the main patch file
function add_patch
{

#
# Capture arguments
   cwd="$1"
   patchfile="$2"
   origfile="$3"

#
# Massage full pathnames to relative forms
   origfile="${origfile##$cwd/}"
   newfile="${origfile%%.$suffix}"
   newfile="${newfile##$cwd/}"

#
# Create the patch and append it to the patch file
   echo "Adding patch for $newfile to $patchfile"
   cd "$cwd"
   diff $diffopts "$origfile" "$newfile" >>"$cwd/$patchfile"
}

#-----------------------------------------------------------------------------

#
# Main body of script code
#

#
# Check command-line syntax
if [ -z "$1" ]; then
   show_help
fi


#
# See if we're in add-patch mode; if so, add the patch
if [ "$1" = "-p" ]; then
   if [ -z "$2" -o -z "$3" ]; then
      echo "Ouch, this looks like a bit of a bug!  Have a -p but \"$2\" and \"$3\""
      show_help
   fi
   cwd="$2"
   patchfile="$3"
   origfile="$4"
   add_patch "$cwd" "$patchfile" "$origfile"

#
# If not, then this is initial invocation; save info and chase tree
else
   cwd=$(pwd)
   patchfile="$1"
   find $cwd -name "*.$suffix" -exec $0 -p "$cwd" "$patchfile" "{}" ";"
fi

#-----------------------------------------------------------------------------
