#! /bin/sh
# bourne shell script
#
# This is the original RTM version that this patch applies to
VERSION="6.0,REV=2003.10.29"

#
# debug message
#
debug_log() {
  if [ $DEBUG != 0 ]; then
    log_msg $*
  fi
}

#
# initialize LOGFILE
#
log_init() {
  touch $LOGFILE
  echo "============ LOGFILE started `date` ==========" >> $LOGFILE
}

#
# log a message to the screen and to the LOGFILE
#
log_msg() {
  echo $*
  echo $* >> $LOGFILE
}

#
# log a message to the LOGFILE only
#
log_only() {
  echo $* >> $LOGFILE
}

#
# determine basedir
# - sets the variable basedir
#
get_basedir() {   # start of get_basedir
  PKGS=`pkginfo -R $ROOTDIR | grep SUNWmsgco | awk '{print $2}`
  # did we find the right PKG
  found=0
  for dir in $PKGS
  do
    pkgname=`basename $dir`
    basedir=`pkgparam -R $ROOTDIR $pkgname BASEDIR`
    version=`pkgparam -R $ROOTDIR $pkgname VERSION`
    if [ $version = "$VERSION" ]; then
      found=1
      break
    fi
  done
  if [ $ROOTDIR != "/" ]; then
    basedir=${ROOTDIR}$basedir
  fi
  # what if we do not find the pkg? should not possible...
  if [ $found -eq 0 ]; then
    echo "Error in postbackout, did not find a SUNWmsgco that matches expected VERSION: $VERSION"
    exit 1
  fi
}

#
# was configure run previously?
# - sets the variable isConfigured to either 0 or 1
# - requires basedir
get_isConfigured() {
  if [ -r $basedir/config ]; then
    isConfigured=1
  else
    isConfigured=0
  fi
  log_only "-- isConfigured = $isConfigured"
}

#
# perform_custom
#
perform_custom() {
  log_only "-- perform_custom being run"
  log_only "--   $basedir/sbin/imsimta cnbuild"
  $basedir/sbin/imsimta cnbuild >> $LOGFILE 2>&1
  log_only "--   return status $?" >> $LOGFILE 2>&1
  log_only "--   $basedir/sbin/imsimta cleandb"
  $basedir/sbin/imsimta cleandb >> $LOGFILE 2>&1
  log_only "--   return status $?" >> $LOGFILE 2>&1
  log_only "--   $basedir/sbin/imsimta version"
  $basedir/sbin/imsimta version >> $LOGFILE 2>&1
  log_only "     return status $?" >> $LOGFILE 2>&1
  log_only "--   $basedir/sbin/imsimta test -rewrite -debug postmaster"
  $basedir/sbin/imsimta test -rewrite -debug postmaster >> $LOGFILE 2>&1
  log_only "--   return status $?" >> $LOGFILE 2>&1
}

# main program starts here
#
# Do I need to do stop-msg?
# determine server-root
# determine ifConfigured
# if configured
#   backout_patch_config
#   perform_custom

get_basedir
PATCHDIR=$basedir/install/patch/$PatchNum
LOGFILE=$PATCHDIR/postbackout_`date +%Y%m%d%H%M%S`.log
log_init
get_isConfigured
if [ $isConfigured -eq 1 ]; then
  perform_custom
fi
