#! /bin/sh
#
#  Script to apply Linux/98 kernel diffs.
#
#	Usage: sh lx98patch.sh DIFF1[.gz] [DIFF2[.gz] ...]
#
#	Run on top directory of Linux kernel source tree
#	(typically /usr/src/linux). Specified diff files are
#	applied in specified order.
#
#		Dec. 26, 1998	1st version
#		Jan. 15, 1999	2nd version (add time stamp restoring)
#
# Copyright (C) 1998  K.Takai <tak@kmc.kyoto-u.ac.jp>
#		      Kyoto University Microcomputer Club
#

TEMPFILE="${TMPDIR-/tmp}/lx98patch$$"

trap 'rm -f "$TEMPFILE"; exit 1' 1 2 3 9 15

if ! touch --version >/dev/null 2>&1
then
	echo This script needs GNU touch. >&2
	exit 1
fi

if patch --help > /dev/null 2>&1
then
	# GNU patch version 2.2 or later
	NEED_RM_ORIG=nil
else
	# old patch (not tested)
	NEED_RM_ORIG=t
	# .orig is used in ancient Linux/98 source :-<
	SIMPLE_BACKUP_SUFFIX=.ORIG
	export SIMPLE_BACKUP_SUFFIX
fi

for DIFF
do
	if [ ! -r "$DIFF" ]
	then
		echo "$DIFF: Not found. Aborting." >&2
		exit 1
	fi
	case "$DIFF" in
	 *.gz)	FILE="$TEMPFILE"
		gzip -dc < "$DIFF" > "$TEMPFILE" ;;
	 *.bz2)	FILE="$TEMPFILE"
		bzip2 -dc < "$DIFF" > "$TEMPFILE" ;;
	 *)	FILE="$DIFF"
		: ;;
	esac
	case $? in
	  0)	;;
	  *)	echo Can\'t uncompress "$DIFF". Aborting. >&2
		exit 1 ;;
	esac
	echo Applying "$DIFF" ...
	if ! sed -n '/^PREPATCH:/s///p' < "$FILE" | sh -x -e
	then
		echo "$DIFF:" Pre-patch command failed. Aborting. >&2
		exit 1
	fi
	if ! patch -p1 < "$FILE"
	then
		echo "$DIFF:" Patch failed. Aborting. >&2
		exit 1
	fi
	case "`find . \( -name \*.rej -o -name .\*.rej \)`" in
	 ?*)	echo "$DIFF:" Reject files found. Aborting. >&2
		exit 1 ;;
	esac
	case $NEED_RM_ORIG in
	  t)	find . -type f \( -name \*.ORIG -o -name .\*.ORIG \) |
		xargs rm -f ;;
	esac

	echo Fixing time stamp ...
	# This will work only with unified diffs.
	sed -n -e '/^diff /!d' -e n -e n -e 's=^+++ [^/]*/==p' "$FILE" |
	while read FILE DATE
	do
		touch -cd "$DATE" "$FILE"
	done
done
echo Done.
rm -f "$TEMPFILE"
exit 0
