#!/bin/sh
#
# Shell script to apply c4b patches to a current source tree
#
# usage:
#
# ./do-patches.sh [source tree base directory]
#

SRCBASE=/usr/src
PATCHDIR=`pwd`
C4BBASE=`pwd`/../..
BCKSFX=".org.c4b"



# Function to perform a patch with some required settings
# Note: The current directory must be set to the source tree base.
exec-patch()
{
   echo "patch -b ${BCKSFX} -N < $1"
   patch -b ${BCKSFX} -N < "$1"
}



# Evaluate command line parameters
while [ -n "$1" ]; do
   case "$1" in
      *)        SRCBASE="$1"; shift ;;
   esac
done



# Determine the full operating system name
t=`grep ^TYPE= "${SRCBASE}/sys/conf/newvers.sh"`
r=`grep ^REVISION= "${SRCBASE}/sys/conf/newvers.sh"`
b=`grep ^BRANCH= "${SRCBASE}/sys/conf/newvers.sh"`
if [ -z "$t" -o -z "$r" -o -z "$b" ]; then
   echo "ERROR: Failed to extract TYPE, REVISION and BRANCH from \"${SRCBASE}/sys/conf/newvers.h\""
   exit 1
fi
eval $t
eval $r
eval $b
# If the BRANCH is "Current", it must be newer than "Release". So in this
# case we just use "=" as the last separator instead of "-" for RELEASE.
case "$BRANCH" in
   [Cc][Uu][Rr][Rr][Ee][Nn][Tt])
      OSNAME="${TYPE}-${REVISION}=${BRANCH}" ;;
   
   *)
      OSNAME="${TYPE}-${REVISION}-${BRANCH}" ;;
esac
   


echo "Patching source tree at \"${SRCBASE}\" for \"${OSNAME}\""
sleep 3
cd ${SRCBASE}



# Execute all patches in the current patch directory
for i in "${PATCHDIR}"/patch-* ; do
   echo "Performing patch \"$i\"..."
   exec-patch "$i"
done



echo "Source tree patch complete."

