#! /bin/sh
# Script to apply xemacs patches.
#   usage: patch-kernel [ sourcedir [ patchdir ] ]
#     The source directory defaults to the current directory, and the patch
#     directory defaults to the current directory.
#
# It determines the current xemacs version from version.sh
# It then looks for patches for the next sublevel in the patch directory.
# This is applied using "patch -p1 -s" from within the xemacs directory.
# A check is then made for "*.rej" files to see if the patch was
# successful.  If it is, then all of the "*.orig" files are removed.
#
#       Nick Holloway <Nick.Holloway@alfie.demon.co.uk>, 2nd January 1995.
# Modified for use with XEmacs - Jeff Miller <jmiller@smart.net> 8 August 1997.
# This was originally patch-kernel, which comes with the linux kernel source.

# Set directories from arguments, or use defaults.
sourcedir=${1-.}
patchdir=${2-..}

# set current VERSION, PATCHLEVEL, SUBLEVEL
source  $sourcedir/version.sh
# for newer version of gnu patch
POSIXLY_CORRECT=t

if [    -z "$emacs_major_version" \
     -o -z "$emacs_minor_version" \
     -o -z "$emacs_beta_version" ]
then
    echo "unable to determine current XEmacs version" >&2
    exit 1
fi

version=$emacs_major_version.$emacs_minor_version-b$emacs_beta_version
echo "Current XEmacs version is $version"

while :
do
    version=$emacs_major_version.$emacs_minor_version-b$emacs_beta_version    
    emacs_beta_version=`expr $emacs_beta_version + 1`
    jump=xemacs-$version-$emacs_major_version.$emacs_minor_version-b$emacs_beta_version
    patch=$jump.patch.gz 
    extras=$jump.extras.tar.gz  

    if [ ! -r $patchdir/$patch ]
    then
        break
    fi

    echo -n "Applying $patch... "
    if gunzip -dc $patchdir/$patch | patch -p1 -s -N -E -d $sourcedir
    then
	echo "done."
    else
        echo "failed.  Clean up yourself."
        break
    fi
    if [ "`find $sourcedir/ '(' -name '*.rej' -o -name '.*.rej' ')' -print`" ]
    then
        echo "Aborting.  Reject files found."
        break
    fi
   
    # Remove backup files
    find $sourcedir/ '(' -name '*.orig' -o -name '.*.orig' ')' -exec rm -f {} \;

    if [ -r $patchdir/$extras ]
    then
      echo -n "Adding $extras... "
      if gunzip -dc $patchdir/$extras | tar -x -C $sourcedir
      then
	echo "done."
      else
        echo "failed.  Clean up yourself."
        break
      fi
    fi
done
