#!/bin/bash

CWD=`pwd`
PATCH_DIR=/usr/SunTrafficManager/patch
OS_VER=`uname -r`
NUM_SUPPORTED_OS=3
SUPPORTED_OS_VER=( 2.4.9-e.3 2.4.9-e.12 2.4.21-4.EL )
JAVA_VER=j2sdk-1.4.2_02-fcs
IS_SUP=0
PREV_PATCHES=`ls $PATCH_DIR/SunTrafficManager*.patch 2> /dev/null | head -1`
PREV_SSTM_PKG=`rpm -qa | grep SunTrafficManager- | head -1`
PREV_VERSION=`rpm -q --queryformat '%{VERSION}\n' $PREV_SSTM_PKG`


# returns OK if $1 contains $2
strstr() {
  [ "$1" = "$2" ] && return 0
  slice=${1#*$2*}
  [ "$slice" = "$1" ] && return 1
  return 0
}

# Removes the RPMs and jafo kernel patches
sstm_remove() {
echo "Removing SSTM......"
#remove j2re if present
JAVA_SDK=`rpm -qa | grep j2sdk-1.4.2_02-fcs | head -1`
if [ "$JAVA_SDK" = "$JAVA_VER" ]; then
    echo "    Removing JRE 1.4.2_02......"
    rpm -e $JAVA_VER
fi
#remove previously installed kernel patch if it exists
cd /usr/src/linux-$MY_OS
if [ -n "$PREV_PATCHES" ]; then
    echo "    Removing previous SSTM kernel patches......"
    patch -NR -p0 < $PATCH_DIR/SunTrafficManager.$PREV_VERSION*linux_$MY_OS.patch
    patch -NR -p2 < $PATCH_DIR/SunTrafficManager.$PREV_VERSION.patch
fi
#remove old SSTM
if [ -n "$PREV_SSTM_PKG" ]; then 
    echo "    Removing previous SSTM package......"
    rpm -e $PREV_SSTM_PKG 
fi
rm -rf /usr/src/redhat/SOURCES/jafo_linux
rm -rf /usr/src/redhat/SOURCES/sstm_utils.*
rm -f /usr/src/linux-2.4/include/linux/modules/jafo_syms.*
rm -rf /usr/SunTrafficManager
}


for(( i = 0 ; i < $NUM_SUPPORTED_OS ; i++ ))
    do
	if strstr "$OS_VER" "${SUPPORTED_OS_VER[$i]}" ; then
	    IS_SUP=1
	    MY_OS=${SUPPORTED_OS_VER[$i]}
	    sstm_remove
	    echo " "
	    echo "Removal done."
	    echo " "
	    echo "Please run make xconfig followed by make dep"
	    echo "to remove SSTM symbols from the kernel."
	    break
	fi
    done
    if [ $IS_SUP = 0 ]; then 
	echo "version $OS_VER: not supported"
    fi
	
