#!/bin/ksh
#
# $Id: applypatch.sh,v 1.1 2001/01/31 17:18:07 gjertsen Exp $
# $Log: applypatch.sh,v $
# Revision 1.1  2001/01/31 17:18:07  gjertsen
# Move patch scripts to tools directory.
#
# Revision 1.3  2000/06/29 23:08:50  schmuck
# Fix problem where script got confused when patch command created a
# backup copy of its input file, because it did not exactly match the
# input from which the diff was produced.
# Avoid file name collisions by using a tmp file for patch output.
#
# Revision 1.2  2000/06/23  22:07:31  eshel
# minor changes to messages
#
# Revision 1.1  2000/06/22  23:02:03  eshel
# add createpatch.sh and applypatch.sh to patch linux source .h files
#
#
## ###################################################################### ##
##        Copyright IBM 2000                                              ##
## ###################################################################### ##

#set nonomatch
#set -x;

# Verify correct number of parameters
if [ $# != 3 ]; then
  echo 'usage: applypatch.sh $SRC $DEST $FILENAME'
  exit 1
fi

# Get parameter values
PGM=${0##*/}
SRC="$1"
DEST="$2"
DIFF_FILE="$3"

# Construct name of the .h file to be patched and tmp file for patch output
H_FILE=${DIFF_FILE%.diff}.h
TMP_FILE=/tmp/$$.$H_FILE

# Compare checksums to verify that the source file to be patched matches
# the file that was used to produce the .diff file
CKSUM1=$(head -1 $DIFF_FILE)
CKSUM2=$(cksum $SRC/$H_FILE)
if [ "$CKSUM1" != "$CKSUM2" ]; then
  echo "$PGM: *** Warning: source file $SRC/$H_FILE has changed"
fi

# Run the patch command; output goes into /tmp
patch --no-backup-if-mismatch --output $TMP_FILE $SRC/$H_FILE $DIFF_FILE
if [ $? != 0 ]; then
  echo "$PGM: *** Error: patch command failed"
  exit 1
fi

# If a file with the same name as the source file exists in the current
# directory, verify that its content matches the result of applying the patch
if [ -f $H_FILE ]; then
  diff -q $H_FILE  $TMP_FILE > /dev/null
  if [ $? != 0 ]; then
    echo "$PGM: *** Error: result of applying $DIFF_FILE does not match ./$H_FILE"
    echo "$PGM: run createpatch.sh before running applypatch.sh again"
    rm $TMP_FILE
    exit 1
  fi
fi

# Install the patched .h file in the destination directory
/usr/bin/install -c -m 0444 $TMP_FILE $DEST/$H_FILE
rc=$?

# Clean up and return the result of the install command
rm $TMP_FILE
exit $rc
