#!/bin/sh
#set -x
# create initial runtime configuration
#
INSTALLDIR=<msg.RootPath>
ARGS=$*
# check if -saveState is passed, if not, add it
SAVESTATE=$INSTALLDIR/install/saveState`date +%Y%m%d%H%M%S`
newargs="-saveState $SAVESTATE"
matches=`echo $ARGS | grep '\-saveState' | wc -l`
if [ "$matches" -eq 0 ]
then
  newargs="$newargs $ARGS"
else
  while [ $# -gt 0 ]
  do
    if [ $1 = "-saveState" ]
    then
      case $2 in
        /* ) USERSAVESTATE=$2;;
        * ) USERSAVESTATE=`pwd`/$2;;
      esac
      shift
      shift
      continue
    fi
    newargs="$newargs $1"
    shift
  done
fi

#
# must be root
#
set `/usr/bin/id`
if [ $1 != "uid=0(root)" ]; then
  echo
  echo "Initial Runtime configurator for Sun ONE Messaging Server \n"
  echo "To use this installer you will need to be the system's root user. \n"
  echo 
  exit 1
fi

#
# Look for a Java Runtime Environment 
#

if [ -x ${INSTALLDIR}/bin/base/jre/bin/java ]; then
  JAVA_HOME=${INSTALLDIR}/bin/base/jre
  export JAVA_HOME       	  ## Our private copy of java
elif [ -x /usr/jdk/entsys-j2se/bin/java ]; then
  JAVA_HOME=/usr/jdk/entsys-j2se
  export JAVA_HOME       	  ## Standard Orion location
elif [ -x /usr/j2se/bin/java ]; then
  JAVA_HOME=/usr/j2se
  export JAVA_HOME       	  ## Standard java location
elif [ ${JAVA_HOME} ]; then
  ## honor JAVA_HOME variable
  :
else
  /usr/j2se/bin/java	## No Java was found.  Execute the default java 
			## command to produce a meaningfull L10N message 
			## and then exit.
  exit 1
fi

#
# Now start execute the Java class file.
#
cd $INSTALLDIR/lib/config-templates
echo $JAVA_HOME/bin/java \
  -classpath "$INSTALLDIR/lib:$JAVA_HOME/lib/classes.zip" \
  $SETUPSDK_SWITCHES configure $newargs
$JAVA_HOME/bin/java \
  -classpath "$INSTALLDIR/lib:$JAVA_HOME/lib/classes.zip" \
  $SETUPSDK_SWITCHES configure $newargs

# copy savestate file to configure directory
if [ $SAVESTATE -a -s $SAVESTATE ]
then
  # determine log directory
  set `grep install.logfile $SAVESTATE`
  dirpath=`dirname $4`
  dir=`basename $4 .log`
  fulldir=$dirpath/$dir
  chmod 700 $fulldir
  echo "mv $SAVESTATE $fulldir/saveState"
  mv $SAVESTATE $fulldir/saveState
  chmod 400 $fulldir/saveState
  echo "Copying factory settings to $INSTALLDIR/data/setup"
  mkdir -p $INSTALLDIR/data/setup
  chown bin:bin $INSTALLDIR/data/setup
  chmod 700 $INSTALLDIR/data/setup
  cp -rp $fulldir $INSTALLDIR/data/setup
  cp -p ${fulldir}.log $INSTALLDIR/data/setup
  if [ "$matches" -ne 0 ]
  then
    cp $fulldir/saveState $USERSAVESTATE
    chmod 400 $USERSAVESTATE
  fi
fi
