#!/bin/sh
# $Id: preremove,v 1.1.2.1 2005/03/14 15:08:05 jb122832 Exp $
# preremove - preremove script for scs

BASEDIR=`dirname $0`/..
UNINSTDIR=$BASEDIR/uninstall
SCSHOME=/scs

MODMGR=$SCSHOME/sbin/moduleMgr.pl
DBMGR=$SCSHOME/sbin/db_tool.pl
INITTOOL=$SCSHOME/sbin/init_tool.pl

RM=/bin/rm


#
# functions
#

printInfo() {
    echo "Info: $@"
}

printWarn() {
    echo "WARNING: $@"
}

errorExit() {
   echo "ERROR: $@" 1>&2;
   exit 1;
}


#
# Main
#


#
# Remove all the modules
#
printInfo "Removing installed Modules"
printInfo "Removing Allstart clients and distributions"
/scs/sbin/as_uninstall.pl -f > /dev/null 2>&1
if [ -x "$MODMGR" ] ; then 

  # Get a list of all Module id's
  MODLIST=`$MODMGR -l | awk '$1 ~ /^[0-9]+$/ { print $1; }'`

  # Now remove them
  for MODID in $MODLIST ;
  do
    printInfo "Removing Module Id: $MODID"
    if $MODMGR -u "$MODID" > /dev/null 2>&1 ; then
      printInfo "Removed Module Id: $MODID"
    else
      printWarn "Could not remove Module Id: $MODID"
    fi
  done
  printInfo "Module removal complete"
else
  printWarn "Can't find $MODMGR"
fi

#
# Disable our web server, tomcat and database
#

"$INITTOOL" stop init.scs-tomcat4 && printInfo "Stopped Tomcat"

if [ "$REMOVE_TOMCAT" = "$TRUE" ] ; then 
  "$INITTOOL" disable init.scs-tomcat4 || errorExit "Cannot disable tomcat"
  printInfo "Disabled tomcat"
fi

for i in httpd db
do
   SCRIPTNAME="init.scs-$i"
   if "$INITTOOL" type "$SCRIPTNAME" > /dev/null ; then 
      for mode in stop disable del
      do
         "$INITTOOL" $mode "$SCRIPTNAME"
	 if [ $? != 0 ] ; then 
            if [ $mode = "stop" ] ; then 
               errorExit "Cannot $mode $SCRIPTNAME"
            else 
               printWarn "Cannot $mode $SCRIPTNAME"
            fi
         fi
      done
   else
      printWarn "Cannot find init.scs-$i"
   fi
done

# TODO: if db is not running this script stops here!!!!
#
# Remove the db
#
if [ -x "$DBMGR" ] ; then 
   printInfo "Removing the Database"
   { "$DBMGR" destroy ; } || \
   errorExit "Database remove failed"
   printInfo "Removed Database"
else
   printWarn "Can't find $DBMGR"
fi

exit 0
