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

# Function to rename a patch backup file to its original name
undo-patch()
{
   local org_name;
   
   org_name=`expr "$1" : '\(.*\)'${BCKSFX}`
   echo "rename \"$1\" to \"${org_name}\""
   mv -f "$1" "${org_name}"
}



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



set -a

OWNNAME=`realpath $0`
if [ -z "${SRCBASE}" ]; then
   SRCBASE=/usr/src
fi
PATCHDIR=`pwd`
C4BBASE=`pwd`/../..
if [ -z "${ALL}" ]; then
   ALL=0
fi
BCKSFX=".org.c4b"

# 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 "Undoing c4b patches for source tree \"${SRCBASE}\" for \"${OSNAME}\""
if [ ${ALL} -eq 1 ]; then
   echo "Also removing c4b files and directories"
fi
sleep 3
cd "${SRCBASE}"



# find all files with suffix $BCKSFX and rename them to their original name
find "${SRCBASE}" -name "*${BCKSFX}" -exec "${OWNNAME}" -undo {} \;



# if requested remove all files and directories for c4b
if [ "${ALL}" -eq 1 ]; then

   echo "removing \"lib/libcapi20\""
   rm -Rf lib/libcapi20
   
   echo "removing \"sys/c4b\""
   rm -Rf sys/c4b
   
   echo "removing \"sys/i4b/i4bcapimgr\""
   rm -Rf sys/i4b/i4bcapimgr
   
   echo "removing \"sys/modules/kcapimgr\""
   rm -Rf sys/modules/kcapimgr
   
   echo "removing \"sys/modules/capidev\""
   rm -Rf sys/modules/capidev
   
   echo "removing \"sys/modules/avmaic\""
   rm -Rf sys/modules/avmaic
   
   echo "removing \"sys/modules/daic\""
   rm -Rf sys/modules/daic
   
   echo "removing \"sys/modules/ix1a\""
   rm -Rf sys/modules/ix1a
   
   echo "removing \"sys/modules/i4bcapimgr\""
   rm -Rf sys/modules/i4bcapimgr
   
   echo "removing \"usr.sbin/c4b\""
   rm -Rf usr.sbin/c4b
   
   echo "removing \"share/capi\""
   rm -Rf share/capi
   
   if [ ${OSNAME} \< "FreeBSD-5.1-RELEASE" ]; then
      echo "removing \"etc/rc.capi\""
      rm -f etc/rc.capi
   else
      echo "removing files from \"etc/rc.d\""
      for i in `ls ${C4BBASE}/rc.d/[a-z]*`; do
         rm -f etc/rc.d/$i
      done
   fi

fi

