#!/bin/sh 

#set -x
#
# Usage
############################

usage() {
    echo "To be able to use cacaoadm command, this script supposes "
    echo "that SunOS package ${SUNOS_CACAO_PKG} is installed, or "    
    echo "package ${LINUX_CACAO_PKG} is installed, in the case of Linux."
    echo "It also supports tarball install, looking for 'cacao_2*' directories."
    echo ""
    if [ "$MASETUP" = "1" ]
    then
      echo "Usage: "
      echo "masetup -h"
      echo "    Outputs this message."
      echo ""
      echo "masetup -i"
      echo "    Initialize JES MF Master Agent."
      echo "    Only does something useful the first time it is called, otherwise does nothing."
    else
      echo "Usage: "
      echo "mfwksetup -h"
      echo "    Outputs this message."
      echo ""
      echo "mfwksetup -i"
      echo "    Initialize JES MF."
      echo "    Only does something useful the first time it is called, otherwise does nothing."
      echo ""
      echo "mfwksetup -r <path_to_CP_xml> [-l <log_file>]"
      echo "    Register and deploy a CP module into the common agent container (cacao)"
      echo "    A restart of cacao is not required after this command"
      echo "    Example: mfwksetup -r /var/tmp/com.sun.cmm.ws.xml"
      echo ""
      echo "mfwksetup -u <CP_xml> [-l <log_file>]"
      echo "    Undeploy and unregister a CP module from the common agent container (cacao)"
      echo "    A restart of cacao is not required after this command"
      echo "    Example: mfwksetup -u com.sun.cmm.ws.xml"
      echo ""    
      echo "mfwksetup -s <module_name> [-l <log_file>]"    
      echo "    If not cacao is started and the module identified by <module_name>"
      echo "    is unlocked."
      echo ""    
      echo "mfwksetup -p <module_name> [-l <log_file>]"
      echo "    The module identified by <module_name> is locked in cacao."    
      echo ""    
      echo "mfwksetup -e [-l <log_file>]"
      echo "    Enable cacao to startup automatically during subsequent system boots"
      echo "    and gracefully to stop during system shutdown."        
  #    echo "mfwksetup -d \"<path_to_CP_xml> <field_name> <value2set>\" [-l <log_file>]"
  #   echo "    Allows to patch the deployment descriptor <path_to_CP_xml> of the CP,"
  #    echo "    looking for <field_name> and setting <value2set>."    
    echo ""
    echo "mfwksetup list-settings"
    echo "    This will list the environment settings that the script"
    echo "    uses.  This interface is useful for other JESMF scripts"
    echo "    or for products that need to find the location of"
    echo "    JESMF dependencies or directories.  The currently supported"
    echo "    settings are CACAO_HOME, MFWK_HOME, CACAO_INSTANCE_HOME."
    echo "    'mfwkadm' can always be found under MFWK_HOME/bin/mfwkadm."
    echo "    'cacaoadm' can always be found under CACAO_HOME/bin/cacaoadm."
    echo "    For example, this is an example output from this"
    echo "    option:"
    echo "    CACAO_HOME=/usr/lib/cacao"
    echo "    MFWK_HOME=/opt/SUNWmfwk"
    echo "    CACAO_INSTANCE_HOME=/etc/cacao/instances/default"
    echo "    MFWK_JAVA_HOME=/usr/jdk/jdk1.5.0_01"
    echo "    NSS_LIB_HOME=/usr/lib/mps/secv1"
    echo "    NSS_TOOLS_HOME=/usr/sfw/bin"
    echo ""
    echo "mfwksetup -c <pkg_name> <product_code_name> <product_name>" \
         "<install_location>"
    echo "     Create Descriptor (Solaris Only): uses the package info for "\
         "<pkg_name> to find values for the"
    echo "     parameters of the descriptor.  See also the -m option"
    echo "     The descriptor is written to the file "\
         " \"./com.sun.cmm.<product_code_name>.xml\""
    echo "     This can be used as is, or could be used as the basis" \
         " for a product's own way to generate a descriptor file."
    echo "     The generated file also contains comments that explain"
    echo "     the attributes and the relation of some of them to the " 
    echo "     instrumentation"
    echo "     eg. mfwksetup -m -c \"SUNWwebsvr\" \"ws\"" \
         " \"Java ES Web Server\" \"/opt/SUNWwebsvr\""
    echo "Note: the InstallDate is hard coded at the moment!"
    echo ""
    echo "mfwksetup -m" 
    echo "      Solaris only. Used in conjunction with -c to specify that a" \
         "supported mib"
    echo "      for this product should be enabled. For JES R5 "
    echo "      this parameter only has an effect for prducts with code names"
    echo "      'ws' and 'ds'"
    echo ""
    echo "mfwksetup -P" 
    echo "      Patch installation post-processing."
    echo "      Must be run after 2.0u1 patched has been applied."
    echo ""
    echo "mfwksetup -U" 
    echo "      Solaris only. Rollbacks a patch installation that was installed with '-P'."
    echo ""
  fi
  echo "The -l <log_file>, can be added to any of the above forms."
  echo "    It allows to output to the file <log_file>, the execution details"
  echo "    of this command."    

  exit 1
}


mLog2() {
    echo "`date` $*" >> ${LOG_FILE}
}

mLog() {
    echo "$*"
}

# Following code is copied from cacaoadm(1)
#
mfwk_clean_path () {
    path_to_clean=$1

    # this awk statement will also remove occurence of '//'
    # a side effect will also remove leading slash
    # -> empty field but the last one will be skip
    echo "$path_to_clean" | awk -F/ '{
        realpath="";
        skip_it=0;
        for (i=NF; i>0; i--) {
                if ($i         == ".")              continue;
                if (length($i) == 0&& i != 1)       continue;
                if ($i         == "..") {skip_it++; continue;}
                if (skip_it    > 0 )    {
                        skip_it--;
                        continue;
                }
                if (length(realpath) > 0) {
                   realpath=$i"/"realpath;
                } else {
                   realpath=$i;
                }
        }
    } END {print realpath}' 2>/dev/null
}

registerNodeAgent() {
  echo "Registering Node Agent in Cacao from descriptor '${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml'"
  RET_MSG=`${CACAO_ADM} register-module ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml 2>&1`
  RET_CODE=$?
  if [ ${RET_CODE} -ne 0 ] 
  then
    mLog "Error : Calling [${CACAO_ADM} register-module ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml]"
    mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
    cleanUpConfig
    exit 1
  fi
}

# Calls CLIs of CPs to find out which version is running
#doCallCLIs() {
#  FILE_VERSIONS=
#  if [ "${OS}" = "SunOS" ]; then
#     FILE_VERSIONS=/etc/opt/SUNWmfwk/config/mfwk.versions.properties
#     CMD_ds="/opt/SUNWdsee/ds6/bin/dsadm --version|grep 'Slapd Library'|head -1|awk '{print \$4}'"
#     CMD_ws="/var/opt/SUNWwbsvr7/admin-server/bin/startserv -version|grep 'Sun Java System Web Server'|awk '{print \$6}'"
#     CMD_ps="/opt/SUNWportal/bin/psconfig --version|grep 'System Portal Server'|sed 's/^.*System Portal Server //g'"
#     CMD_am="/opt/SUNWam/bin/amadmin --version|grep 'Sun Java System Access Manager'|awk '{print \$6}'"
#     CMD_cacao="/usr/sbin/cacaoadm --version"
#     CMD_as="/opt/SUNWappserver/sbin/asadmin version|grep 'Version ='|awk '{print \$10}'"
#  elif [ "${OS}" = "Linux" ]; then
#     FILE_VERSIONS=/etc/opt/sun/mfwk/config/mfwk.versions.properties
#     CMD_ds="/opt/sun/ds6/bin/dsadm --version|grep 'Slapd Library'|head -1|awk '{print \$4}'"
#     CMD_ws="/var/opt/sun/webserver7/admin-server/bin/startserv -version|grep 'Sun Java System Web Server'|awk '{print \$6}'"
#     CMD_ps="/opt/sun/portal/bin/psconfig --version|grep 'System Portal Server'|sed 's/^.*System Portal Server //g'"
#     CMD_am="/opt/sun/identity/bin/amadmin --version|grep 'Sun Java System Access Manager'|awk '{print \$6}'"
#     CMD_cacao="/opt/sun/cacao/bin/cacaoadm --version"
#     CMD_as="/opt/sun/appserver/bin/asadmin version|grep 'Version ='|awk '{print \$10}'"
#  fi
#
#  if [ ! -z "${FILE_VERSIONS}" ]; then
#    rm -f ${FILE_VERSIONS}
#    touch ${FILE_VERSIONS}
#
#    for pcn in ds ws ps am cacao as
#    do
#      str_to_exec=$(eval echo \$CMD_${pcn})
#      ver_res=$(eval ${str_to_exec}) > /dev/null 2>&1
#      if [ ! -z "${ver_res}" ]; then
#        echo "com.sun.mfwk.${pcn}.version=${ver_res}" >> ${FILE_VERSIONS}
#        echo "Found version \"${ver_res}\" for ${pcn}"
#      fi
#    done
#  fi
#
#}

# Does the steps required after patching mfwk to 2.0U1 level:
# 1) unregister agent descriptor if necessary
# 2) patch new mfwk.properties.template
# 3) patch the new agent descriptor with BASEDIR, INSTALLDATE, ...
# 4) register new descriptor in cacao
# 5) call some specif ServiceTag code on s10.

doPatch() {
  if [ "$MASETUP" = "1" ] ; then
    mLog "This option is not supported."
    exit 1
  fi

  if [ -r ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml.20 ]; then
    mLog "Patch has already been applied. Nothing to do."
    exit 1
  else
    if [ -r ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml ] ; then
      mv ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml \
         ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml.20
    fi
    if [ -r ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample ] ; then
      mv ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample \
         ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample.20
    fi
    patchAgentDescriptorAndProperties

    # Check if the "2.0" file is different from the current one. If they are the same, we try to patch a 2.0u1 install
    diff ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample \
         ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample.20 > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      # Files are the same
      mLog "Cannot do this on a fresh u1 install."
      rm ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample.20
      rm ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml.20
      exit 1
    fi

    # Remove MF 2.0 Agent from Cacao.
    RET_MSG=`${CACAO_ADM} unregister-module com.sun.mfwk.xml 2>&1`

    registerNodeAgent

    #doCallCLIs
  fi
}

# Rollback a patch previously installed with "-P"
doRollbackPatch() {
  if [ "$MASETUP" = "1" ] ; then
    mLog "This option is not supported."
    exit 1
  fi
  if [ "${OS}" != "SunOS" ] ; then
    mLog "This option is only supported on Solaris."
    exit 1
  fi

  if [ ! -r ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample.20 ]; then
    mLog "No patch was installed (cannot find ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample.20 ), exit."
    exit 1
  fi
  if [ ! -r ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml.20 ]; then
    mLog "No patch was installed (cannot find ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml.20 ), exit."
    exit 1
  fi
  mv ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml.20 \
     ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml

  mv ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample.20 \
     ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample

  # Remove MF 2.0u1 Agent from Cacao.
  RET_MSG=`${CACAO_ADM} unregister-module com.sun.mfwk.xml 2>&1`

  registerNodeAgent
}


#
# setupEnvironment
############################

setEnvSunOS() {

#set -x
 PKG_AGENT=SUNWmfwk-rt

  DIR=`dirname $0`
  FIRST_CHAR=`echo $DIR | awk '{print substr($0,0,1)}'`
  if [ "${FIRST_CHAR}" != "/" ]; then
	DIR=`pwd`"/${DIR}"
  fi
  
  CMD_BRUT="${DIR}/`basename $0`"
  # Remove /./ parts, and repeated /////
  CMD=`mfwk_clean_path ${CMD_BRUT}`

  # Get base dir of mfwk, from path of running command
  if [ "$MASETUP" = "1" ]
  then
    MFWK_BASEDIR=`echo ${CMD} | sed 's#SUNWmfwk/bin/masetup##g'`
  else
    MFWK_BASEDIR=`echo ${CMD} | sed 's#SUNWmfwk/bin/mfwksetup##g'`
  fi
  BASEDIR=$MFWK_BASEDIR

  # Now look for our install strategy
  # Are we installed from a package ?

  # Default case: tarball
  MFWK_INSTALL_TYPE=tarball
  pkginfo 'SUNWmfwk-rt.*' > /dev/null 2>&1
  if [ $? -eq 0 ]; then
    for pkg in `pkginfo 'SUNWmfwk-rt.*'|awk '{print $2}'`
    do
      pkgparam $pkg BASEDIR > /dev/null 2>&1
      if [ $? -eq 0 ]; then
        PACKAGE_BASEDIR=`pkgparam $pkg BASEDIR`
        # Compare inode numbers (to account for trailing '/' and such)
        if [ "`ls -laid ${PACKAGE_BASEDIR} | awk '{print $1}'`" = "`ls -laid ${MFWK_BASEDIR} | awk '{print $1}'`" ]; then
          # This is us !
          if [ "`ls -laid ${MFWK_BASEDIR} | awk '{print $1}'`" = "`ls -laid /opt | awk '{print $1}'`" ]; then
	      MFWK_INSTALL_TYPE=sunos_pkg_default
          else
	      MFWK_INSTALL_TYPE=sunos_pkg_reloc
          fi
          break
        fi
      fi
    done
  fi

  # Look for Cacao in default location
  if [ "${MFWK_INSTALL_TYPE}" = "tarball" ]; then
    # Look for "cacao_2" first for dsee
    CACAO_RLOC_DIR="${MFWK_BASEDIR}/cacao_2"
    if [ ! -d "${CACAO_RLOC_DIR}" ]; then
      # Look for latest cacao_2.* directory.
      # We don't use 'ls' to avoid extraneous error messages.
      # The following line works because the shell sorts the result of "X_*"
      for i in ${MFWK_BASEDIR}/cacao_2.*
      do
        [ -d "$i" ] && CACAO_RLOC_DIR="$i"
      done
    fi
    CACAO_ADM="${CACAO_RLOC_DIR}/usr/sbin/cacaoadm"
    CACAO_HOME=${CACAO_RLOC_DIR}/usr/lib/cacao
  elif [ "${MFWK_INSTALL_TYPE}" = "sunos_pkg_default" ]; then
    CACAO_RLOC_DIR="/"
    CACAO_ADM="${CACAO_RLOC_DIR}/usr/sbin/cacaoadm"
    CACAO_HOME=/usr/lib/cacao
  elif [ "${MFWK_INSTALL_TYPE}" = "sunos_pkg_reloc" ]; then
    CACAO_RLOC_DIR="${MFWK_BASEDIR}"
    CACAO_ADM="${CACAO_RLOC_DIR}/usr/sbin/cacaoadm"
    CACAO_HOME=${CACAO_RLOC_DIR}/usr/lib/cacao
  else
    mLog "Error : unable to determine MFWK_INSTALL_TYPE : [${MFWK_INSTALL_TYPE}]"
    exit 1
  fi

  if [ ! -f $CACAO_ADM ]; then
    # try to get cacaoadm from PATH (6381635)
    type cacaoadm > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      # We need to remove extra '//' because link to cacaoadm not cleanly set by Cacao ('//' in path).
      CACAO_ADM=`type cacaoadm | awk '{print $3}' | sed 's#///*#/#g'`
      if [ `file -h ${CACAO_ADM} | awk '{print $2}'` = "symbolic" ]; then
        # cacaoadm is the symbolic link -> resolve it first
        LINK=`file -h ${CACAO_ADM} | awk '{print $5}'`
        BASE=`dirname ${CACAO_ADM}`
        CACAO_ADM=`echo "${BASE}/${LINK}" | sed 's#/[^/]*/\.\./#/#g' | sed 's#/[^/]*/\.\./#/#g' | sed 's#///*#/#g'`
      fi
      if [ "${CACAO_ADM}" = "/usr/lib/cacao/bin/cacaoadm" ]
      then
        CACAO_RLOC_DIR="/"
        CACAO_HOME=/usr/lib/cacao
      else
        CACAO_RLOC_DIR=`echo ${CACAO_ADM} | sed 's#usr/lib/cacao/bin/cacaoadm##g'`
        CACAO_HOME=${CACAO_RLOC_DIR}/usr/lib/cacao
      fi
    else
      mLog "Error : unable to find a suitable Cacao install"
      exit 1
    fi
  fi

  CACAO_TOPDIR=${CACAO_RLOC_DIR}
  CACAO_INSTANCE_HOME=${CACAO_TOPDIR}/etc/cacao/instances/default

  OS_CONF_DIRNAME="SUNWmfwk"
  OS_DIRNAME="SUNWmfwk"

  MFWK_HOME=${MFWK_BASEDIR}/${OS_DIRNAME}

  if [ "${MFWK_INSTALL_TYPE}" = "tarball" ]; then
    MFWK_CONF_BASEDIR=${MFWK_BASEDIR}

  elif [ "${MFWK_INSTALL_TYPE}" = "sunos_pkg_default" ]; then
    MFWK_CONF_BASEDIR=""

  elif [ "${MFWK_INSTALL_TYPE}" = "sunos_pkg_reloc" ]; then
    MFWK_CONF_BASEDIR="${MFWK_BASEDIR}"

  else
    mLog "Error : unable to determine MFWK_INSTALL_TYPE : [${MFWK_INSTALL_TYPE}]"
    exit 1
  fi

# here:
# BASEDIR is the pkg basedir
# MFWK_CONF_BASEDIR is the dir to prefix /etc; /var paths with to get conf and logs
# MFWK_HOME is the prefix of the lib, xml , bin dirs and sample config
# MFWK_BASEDIR is the dir to prefix to get the libs and bins and xmls

  TEMP_FILE=/tmp/.mfwksetup.${MY_UID}.${MY_DATE}.$$
  LIBDIR=lib
  # Location of jar file of servicetags
  BASE_ST_DIR=/opt/SUNWstjapi/share/lib
}

setupEnvironmentSunOS() {
   
    setEnvSunOS

    # Test if cacaoadm is runable
    TRASH=`${CACAO_ADM} -V 2>&1`
    if [ $? -ne 0 ] 
    then
         mLog "Error : Running : [${CACAO_ADM}]"
         exit 1
    fi
    if [ "$MASETUP" = "1" ]
    then
      FILE_FLAG_FOR_MFWK_CONF_SUNOS="${MFWK_CONF_BASEDIR}/etc/opt/SUNWmfwk/config/masteragent.properties.sample"
    else
      FILE_FLAG_FOR_MFWK_CONF_SUNOS="${MFWK_CONF_BASEDIR}/etc/opt/SUNWmfwk/config/security/password.agent"
    fi
}

setEnvLinux() {

#set -x
  PKG_AGENT=sun-mfwk-rt

  DIR=`dirname $0`
  FIRST_CHAR=`echo $DIR | awk '{print substr($0,0,1)}'`
  if [ "${FIRST_CHAR}" != "/" ]; then
	DIR=`pwd`"/${DIR}"
  fi

  CMD_BRUT="${DIR}/`basename $0`"
  # Remove /./ parts, and repeated /////
  CMD=`mfwk_clean_path ${CMD_BRUT}`

  # Get base dir of mfwk, from path of running command
  if [ "$MASETUP" = "1" ]
  then
    MFWK_BASEDIR=`echo ${CMD} | sed 's#mfwk/bin/masetup##g'`
  else
    MFWK_BASEDIR=`echo ${CMD} | sed 's#mfwk/bin/mfwksetup##g'`
  fi
  BASEDIR=$MFWK_BASEDIR

  # Now look for our install strategy
  # Are we installed from a package ?

  # Default case: tarball
  MFWK_INSTALL_TYPE=tarball
  rpm -qi sun-mfwk-rt > /dev/null 2>&1
  if [ $? -eq 0 ]; then
    PACKAGE_BASEDIR=`rpm -qil sun-mfwk-rt|grep mfwksetup|sed 's#mfwk/bin/mfwksetup##g'`
    # Compare inode numbers (to account for trailing '/' and such)
    if [ "`ls -laid ${PACKAGE_BASEDIR} | awk '{print $1}'`" = "`ls -laid ${MFWK_BASEDIR} | awk '{print $1}'`" ]; then
      # This is us !
      if [ "`ls -laid ${MFWK_BASEDIR} | awk '{print $1}'`" = "`ls -laid /opt/sun | awk '{print $1}'`" ]; then
	MFWK_INSTALL_TYPE=linux_pkg_default
      else
        MFWK_INSTALL_TYPE=linux_pkg_reloc
      fi
    fi
  fi

  # Look for Cacao in default location
  if [ "${MFWK_INSTALL_TYPE}" = "tarball" ]; then
    # Look for "cacao_2" first for dsee
    CACAO_RLOC_DIR="${MFWK_BASEDIR}/cacao_2"
    if [ ! -d "${CACAO_RLOC_DIR}" ]; then
      # Look for latest cacao_2.* directory.
      # We don't use 'ls' to avoid extraneous error messages.
      # The following line works because the shell sorts the result of "X_*"
      for i in ${MFWK_BASEDIR}/cacao_2.*
      do
        [ -d "$i" ] && CACAO_RLOC_DIR="$i"
      done
    fi
    CACAO_ADM="${CACAO_RLOC_DIR}/cacao/bin/cacaoadm"
    # Workaround for 6771542 (incompatibility introduced in Cacao 2.2)
    if [ ! -f $CACAO_ADM ]; then
      CACAO_ADM="${CACAO_RLOC_DIR}/cacao2/bin/cacaoadm"
    fi
    CACAO_HOME=${CACAO_RLOC_DIR}/cacao
  elif [ "${MFWK_INSTALL_TYPE}" = "linux_pkg_default" ]; then
    CACAO_RLOC_DIR="/"
    CACAO_ADM="${CACAO_RLOC_DIR}/opt/sun/cacao/bin/cacaoadm"
    CACAO_HOME=/opt/sun/cacao
  elif [ "${MFWK_INSTALL_TYPE}" = "linux_pkg_reloc" ]; then
    CACAO_RLOC_DIR="${MFWK_BASEDIR}"
    CACAO_ADM="${CACAO_RLOC_DIR}/cacao/bin/cacaoadm"
    CACAO_HOME=${CACAO_RLOC_DIR}/cacao
  else
    mLog "Error : unable to determine MFWK_INSTALL_TYPE : [${MFWK_INSTALL_TYPE}]"
    exit 1
  fi

  if [ ! -f $CACAO_ADM ]; then
    # try to get cacaoadm from PATH (6381635)
    type cacaoadm > /dev/null 2>&1
    if [ $? -eq 0 ]; then
      CACAO_ADM=`type cacaoadm | awk '{print $3}'`
      if [ "${CACAO_ADM}" = "/opt/sun/cacao/bin/cacaoadm" ]
      then
        CACAO_RLOC_DIR="/"
        CACAO_HOME=/opt/sun/cacao
      else
        CACAO_RLOC_DIR=`echo ${CACAO_ADM} | sed 's#cacao/bin/cacaoadm##g'`
        CACAO_HOME=${CACAO_RLOC_DIR}/cacao
      fi
    else
      mLog "Error : unable to find a suitable Cacao install"
      exit 1
    fi
  fi

  CACAO_TOPDIR=${CACAO_RLOC_DIR}
  CACAO_INSTANCE_HOME=${CACAO_TOPDIR}/etc/opt/sun/cacao/instances/default

  OS_DIRNAME="mfwk"
  OS_CONF_DIRNAME="sun/mfwk"

  MFWK_HOME=${MFWK_BASEDIR}/${OS_DIRNAME}

  if [ "${MFWK_INSTALL_TYPE}" = "tarball" ]; then
    MFWK_CONF_BASEDIR=${MFWK_BASEDIR}

  elif [ "${MFWK_INSTALL_TYPE}" = "linux_pkg_default" ]; then
    MFWK_CONF_BASEDIR=""

  elif [ "${MFWK_INSTALL_TYPE}" = "linux_pkg_reloc" ]; then
    MFWK_CONF_BASEDIR="${MFWK_BASEDIR}"

  else
    mLog "Error : unable to determine MFWK_INSTALL_TYPE : [${MFWK_INSTALL_TYPE}]"
    exit 1
  fi

  TEMP_FILE=/tmp/.mfwksetup.${MY_UID}.${MY_DATE}.$$
  LIBDIR=share/lib

  # Location of jar file of servicetags
  BASE_ST_DIR=/opt/sun/servicetag/share/lib

}

setupEnvironmentLinux() {

   setEnvLinux

    # Test if cacaoadm is runable
    TRASH=`${CACAO_ADM} -V 2>&1`
    if [ $? -ne 0 ] 
    then
         mLog "Error : Running : [${CACAO_ADM}]"
         exit 1
    fi
    if [ "$MASETUP" = "1" ]
    then
      FILE_FLAG_FOR_MFWK_CONF_LINUX="${MFWK_CONF_BASEDIR}/etc/opt/sun/mfwk/config/masteragent.properties.sample"
    else
      FILE_FLAG_FOR_MFWK_CONF_LINUX="${MFWK_CONF_BASEDIR}/etc/opt/sun/mfwk/config/security/password.agent"
    fi
}

cleanUpConfig() {
  if [ "$MASETUP" = "1" ]
  then
    mLog "Cleaning up config"
    rm -f ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/masteragent.properties.sample
  else
    mLog "Cleaning up config in ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config"
    rm -rf ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config
  fi
}

# Hardcoded paths for shared components
#     SUNOS
JAXWS_LIBDIR_SUNOS=/opt/SUNWjax/share/lib
JAXB_LIBDIR_SUNOS=/opt/SUNWjax/share/lib
JAXP_LIBDIR_SUNOS=/usr/share/lib
JAF_LIBDIR_SUNOS=/usr/share/lib
SAAJ_LIBDIR_SUNOS=/usr/share/lib
WSCL_LIBDIR_SUNOS=/usr/share/lib
#    LINUX
JAXWS_LIBDIR_LINUX=/opt/sun/share/lib
JAXB_LIBDIR_LINUX=/opt/sun/share/jaxb/lib
JAXP_LIBDIR_LINUX=/opt/sun/share/lib
JAF_LIBDIR_LINUX=/opt/sun/share/lib
SAAJ_LIBDIR_LINUX=/opt/sun/share/lib
WSCL_LIBDIR_LINUX=/opt/sun/private/share/lib

# Replaces Shared Components tokens in the passed file with
# the right library locations according to the platform and
# the installation type (tarball or not)
modifySharedComponentsDependencies() {

    # Tmp copy of the file to modify so that we can replace the original
    ORIGFILE=`basename $1`
    TMPFILE=/tmp/$ORIGFILE.$$
    cp -f $1 $TMPFILE

    # Process the file
    if [ "${MFWK_INSTALL_TYPE}" = "tarball" ] ; then
	# Tarball install: replace every token with path to bundled jar files
	LIB_PATH=$BASEDIR/$OS_DIRNAME/$LIBDIR

	sed "s;JAXWS_TOKEN;${LIB_PATH};g" $TMPFILE | \
        sed "s;JAXB_TOKEN;${LIB_PATH};g" | \
	sed "s;JAXP_TOKEN;${LIB_PATH};g" | \
	sed "s;JAF_TOKEN;${LIB_PATH};g" | \
	sed "s;SAAJ_TOKEN;${LIB_PATH};g" | \
	sed "s;WSCL_TOKEN;${LIB_PATH};g" > $1
    else
	# Package install (reloc or not): replace every token with 
	# path to matching well known shared component
	if [ "${OS}" = "SunOS" ] ; then 
	    sed "s;JAXWS_TOKEN;${JAXWS_LIBDIR_SUNOS};g" $TMPFILE | \
	    sed "s;JAXB_TOKEN;${JAXB_LIBDIR_SUNOS};g" | \
	    sed "s;JAXP_TOKEN;${JAXP_LIBDIR_SUNOS};g" | \
	    sed "s;JAF_TOKEN;${JAF_LIBDIR_SUNOS};g" | \
	    sed "s;SAAJ_TOKEN;${SAAJ_LIBDIR_SUNOS};g" | \
	    sed "s;WSCL_TOKEN;${WSCL_LIBDIR_SUNOS};g" > $1
	else
	    if [ "${OS}" = "Linux" ] ; then
		sed "s;JAXWS_TOKEN;${JAXWS_LIBDIR_LINUX};g" $TMPFILE | \
		sed "s;JAXB_TOKEN;${JAXB_LIBDIR_LINUX};g" | \
		sed "s;JAXP_TOKEN;${JAXP_LIBDIR_LINUX};g" | \
		sed "s;JAF_TOKEN;${JAF_LIBDIR_LINUX};g" | \
		sed "s;SAAJ_TOKEN;${SAAJ_LIBDIR_LINUX};g" | \
		sed "s;WSCL_TOKEN;${WSCL_LIBDIR_LINUX};g" > $1
	    else
		echo "ERROR: unsupported platform type (neither Solaris nor Linux)"
	    fi
	fi
    fi
    
    # Remove tmp copy
    rm $TMPFILE
}

# Tune the cacao descriptors (MA or NA) and various launch script by
# pointing to the right place wether it is a package installation or
# a tarball installation. Modify the MA or NA cacao descriptor as
# needed. If this is a package installation, point to hardcoded
# JES shared components loaction. If tarball installation, point to
# embedded shared components libraries.
# WARNING: this function is assumed to be run in doConfigureGeneric()
# so that it just have to modify the created agent cacao descripor
doConfigureSharedComponents() {

    # Tune the agent cacao descriptor (MA or NA)
    if [ "$MASETUP" = "1" ] ; then
	FILE_TO_TUNE=${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.masteragent.xml 
    else
	FILE_TO_TUNE=${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml
    fi
    modifySharedComponentsDependencies $FILE_TO_TUNE

    # Tune the script that launches the OSSJ Web Services console
    modifySharedComponentsDependencies ${MFWK_BASEDIR}/${OS_DIRNAME}/ws/script/ossj_ws_console.ksh
}

patchAgentDescriptorAndProperties() {
  # Compute InstallDate
  INST_DATE=`date -u +"(((((%Y - 1)/4-492+(%Y - 1970)*365+%j-1)*24+%H)*60+%M)*60+%S)*1000+(%S*%M)%1000" | bc`

  sed "s;BASEDIR;${MFWK_BASEDIR};g" ${MFWK_BASEDIR}/${OS_DIRNAME}/xml/com.sun.mfwk.xml.template | \
  sed "s;OS_DIRNAME;${OS_DIRNAME};g" | \
  sed "s;OS_CONF_DIRNAME;${OS_CONF_DIRNAME};g" | \
  sed "s;BASECONFDIR;${MFWK_CONF_BASEDIR};g" | \
  sed "s;BASE_ST_DIR;${BASE_ST_DIR};g" | \
  sed "s;LIBDIR;${LIBDIR};g" | \
  sed "s;INSTALLDATE_TOKEN;${INST_DATE};g" | \
  sed 's;file://*;file:/;g' > ${TEMP_FILE}

  modifySharedComponentsDependencies ${TEMP_FILE}

  # CR 6595846 : convert encoding of current local to utf-8 encoding.
  RES_FILE="${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml"
  if [ "${OS}" = "SunOS" ]; then 
    if [ "`uname -r`" = "5.10" -o "`uname -r`" = "5.11"  -o "`uname -r`" = "5.12" ]; then
      cat ${TEMP_FILE} | iconv -t utf-8 - > ${RES_FILE}
    # If we are in ASCII (C), or nothing is set, no conversion required (ASCII is UTF-8)
    elif [ \( -z "${LANG}" \) -o \( "${LANG}" = "C" \) ]; then
      cp ${TEMP_FILE} ${RES_FILE}
    else
      cat ${TEMP_FILE} | iconv -t utf-8 -f ${LANG} > ${RES_FILE}
    fi
  elif [ "${OS}" = "Linux" ]; then
    cat ${TEMP_FILE} | iconv -t utf-8 - > ${RES_FILE}
  else
    cp ${TEMP_FILE} ${RES_FILE}
  fi
  rm -f ${TEMP_FILE}

  if [ -f ${MFWK_BASEDIR}/${OS_DIRNAME}/config/mfwk.properties.sample ] ;
  then
    sed "s;BASEDIR;${MFWK_BASEDIR};g" ${MFWK_BASEDIR}/${OS_DIRNAME}/config/mfwk.properties.sample | \
    sed "s;BASECONFDIR;${MFWK_CONF_BASEDIR};g" | \
    sed "s;OS_DIRNAME;${OS_DIRNAME};g" | \
    sed "s;OS_CONF_DIRNAME;${OS_CONF_DIRNAME};g" | \
    sed "s;LIBDIR;${LIBDIR};g" | \
    sed 's;=//*;=/;g' > ${TEMP_FILE}
    mv ${TEMP_FILE} ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/mfwk.properties.sample
  fi

  # Copy the swordfishId files
  for i in ${MFWK_BASEDIR}/${OS_DIRNAME}/config/mfwk.metadatauuids.*.properties
  do
    if [ -r $i ]; then
      cp $i ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/`basename $i`
    fi
  done
}

doConfigureGeneric() {

#set -x
    rm -f ${TEMP_FILE}
    if [ -r ${TEMP_FILE} ]
    then
      echo "Cannot remove temporary file ${TEMP_FILE} . Exiting..."
      exit 1
    fi

    mkdir -p ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config
    mkdir -p ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml

    if [ "$MASETUP" = "1" ]
    then
      cp ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/security/cert.agent ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/security/masteragent.cert

      if [ ! $? -eq 0 ]
      then
         mLog "Error : JES MF configuration is not correct"
         mLog "Error : problem accessing agent certificate [${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/security/cert.agent]"
         exit 1
      fi

      INST_DATE=`date -u +"(((((%Y - 1)/4-492+(%Y - 1970)*365+%j-1)*24+%H)*60+%M)*60+%S)*1000+(%S*%M)%1000" | bc`

      find ${MFWK_BASEDIR}/${OS_DIRNAME} -name com.sun.mfwk.masteragent.xml.template -print | while read i
      do
        sed "s;BASEDIR;${MFWK_BASEDIR};g" $i | \
        sed "s;OS_DIRNAME;${OS_DIRNAME};g" | \
        sed "s;OS_CONF_DIRNAME;${OS_CONF_DIRNAME};g" | \
	sed "s;BASECONFDIR;${MFWK_CONF_BASEDIR};g" | \
        sed "s;LIBDIR;${LIBDIR};g" | \
        sed "s;BASE_ST_DIR;${BASE_ST_DIR};g" | \
        sed "s;INSTALLDATE_TOKEN;${INST_DATE};g" | \
        sed 's;file://*;file:/;g' > ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/`basename $i '.template'`
      done

      # This should be the last thing done in the init part of 'masetup'
      if [ -f ${MFWK_BASEDIR}/${OS_DIRNAME}/config/masteragent.properties.sample ] ;
      then
        sed "s;BASEDIR;${MFWK_BASEDIR};g" ${MFWK_BASEDIR}/${OS_DIRNAME}/config/masteragent.properties.sample | \
	sed "s;BASECONFDIR;${MFWK_CONF_BASEDIR};g" | \
        sed "s;OS_DIRNAME;${OS_DIRNAME};g" | \
	sed "s;OS_CONF_DIRNAME;${OS_CONF_DIRNAME};g" | \
        sed "s;LIBDIR;${LIBDIR};g" | \
        sed 's;=//*;=/;g' > ${TEMP_FILE}
        mv ${TEMP_FILE} ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/masteragent.properties.sample
      fi

    else
      # Patch example descriptors
      find ${MFWK_BASEDIR}/${OS_DIRNAME} -name com.sun.cmm.\*.xml.template -print | while read i
      do
        sed "s;BASEDIR;${MFWK_BASEDIR};g" $i | \
        sed "s;OS_DIRNAME;${OS_DIRNAME};g" | \
        sed "s;OS_CONF_DIRNAME;${OS_CONF_DIRNAME};g" | \
	sed "s;BASECONFDIR;${MFWK_CONF_BASEDIR};g" | \
        sed "s;LIBDIR;${LIBDIR};g" | \
        sed 's;file://*;file:/;g' > ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/`basename $i '.template'` 
      done
      patchAgentDescriptorAndProperties

      echo "Creating the agent security materials in ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/security"
      (cd /tmp; ${MFWK_BASEDIR}/${OS_DIRNAME}/bin/genkey -d ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/security/)
  
      if [ ! $? -eq 0 ] ;
      then
         mLog "Error : Calling [genkey]"
         cleanUpConfig
         exit 1
      fi
  
      echo "Copying SNMP security files to ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/security/snmp"
      mkdir -p ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/security/snmp
      cp ${MFWK_BASEDIR}/${OS_DIRNAME}/config/security/snmp/* ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/config/security/snmp/
  
      if [ ! $? -eq 0 ] ;
      then
         mLog "Error : Copying SNMP security files"
         cleanUpConfig
         exit 1
      fi
  
      echo "Creating the logs directories in ${MFWK_CONF_BASEDIR}/var/opt/${OS_CONF_DIRNAME}/logs"
      umask 022
      mkdir -p ${MFWK_CONF_BASEDIR}/var/opt/${OS_CONF_DIRNAME}/logs
  
      # Create the OSS/J jobs' reports directories
      umask 022
      mkdir -p ${MFWK_CONF_BASEDIR}/var/opt/${OS_CONF_DIRNAME}/reports/measurement
      mkdir -p ${MFWK_CONF_BASEDIR}/var/opt/${OS_CONF_DIRNAME}/reports/opstatus
  
    fi

    # Tune the cacao descriptors (MA or NA) and various launch script by
    # pointing to the right place wether it is a package installation or
    # a tarball installation
    doConfigureSharedComponents

    # If we are called by the DSEE installer, do not mess with Cacao
    if [ "$NOPTION" = "1" ]; then
      if [ "$MASETUP" = "0" ]; then
        echo "Registering Node Agent in Cacao from descriptor '${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml'"
        RET_MSG=`${CACAO_ADM} register-module ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml 2>&1`
        RET_CODE=$?
        if [ ${RET_CODE} -ne 0 ] 
        then
          mLog "Error : Calling [${CACAO_ADM} register-module ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml]"
          mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
          cleanUpConfig
          exit 1
        fi
      fi
    else

      echo "Stopping Cacao (if needed)"
      RET_MSG=`${CACAO_ADM} stop 2>&1`
      RET_CODE=$?
      if [ ${RET_CODE} -ne 0 ] ; then
        mLog "Error : Calling [${CACAO_ADM} stop]"
        mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
        cleanUpConfig
        exit 1
      fi
  
      echo "Changing Cacao global parameter network-bind-address"
      RET_MSG=`${CACAO_ADM} set-param network-bind-address=0.0.0.0 2>&1`
      RET_CODE=$?
      if [ ${RET_CODE} -ne 0 ] ; then
        mLog "Error : Calling [${CACAO_ADM} set-param network-bind-address=0.0.0.0]"
        mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
        cleanUpConfig
        exit 1
      fi
  
      if [ "$MASETUP" = "0" ]
      then
        # Make sure JES MF Agent can be deployed in Cacao. Ensure old installations are cleaned up.
        RET_MSG=`${CACAO_ADM} unregister-module com.sun.mfwk.xml 2>&1`
      fi
  
      echo "Starting Cacao"
      RET_MSG=`${CACAO_ADM} start 2>&1`
      RET_CODE=$?          # 17 = Already running : OK
      if [ ${RET_CODE} -ne 17 ] ; then
        if [ ${RET_CODE} -ne 0 ] ; then
          mLog "Error : Calling [${CACAO_ADM} start]"
          mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
          cleanUpConfig
          exit 1
        fi
      fi
  
      echo "Wait until Cacao is ready to accept requests."
      sleep 1
      nbLoops=0
      while true
      do
        REP=`LC_ALL=C ${CACAO_ADM} status 2>&1 | awk 'BEGIN {ret=2} / instance is not running/ {ret=0} /^Uptime/ {ret=1} END {exit ret}' ; echo $?`
        case ${REP} in
          0)
            # container had problem to start
            mLog "Unable to start Cacao. Check Cacao log files. Possible port number conflict."
            cleanUpConfig
            exit 1
            ;;
          1)
            # container is now up and running
            break
            ;;
          2)
            # container not yet available
            # go for one more loop
            ;;
        esac
  
        nbLoops=`expr ${nbLoops} + 1`
        if [ ${nbLoops} -eq 60 ]; then
          mLog "Unable to start Cacao. Check Cacao log files. Possible port number conflict."
          cleanUpConfig
          exit 1
        fi
        sleep 5
      done
      
      if [ "$MASETUP" = "1" ]
      then
        echo "Unregistering Node Agent in Cacao"
        RET_MSG=`${CACAO_ADM} unregister-module com.sun.mfwk.xml 2>&1`
        RET_CODE=$?
        if [ ${RET_CODE} -ne 0 ]
        then
          mLog "Error : Calling [${CACAO_ADM} unregister-module com.sun.mfwk.xml]"
          mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
          cleanUpConfig
          exit 1
        fi
    
        echo "Registering Master Agent in Cacao"
        RET_MSG=`${CACAO_ADM} register-module ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.masteragent.xml 2>&1`
        RET_CODE=$?
        if [ ${RET_CODE} -ne 0 ]
        then
          mLog "Error : Calling [${CACAO_ADM} register-module ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.masteragent.xml]"
          mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
          cleanUpConfig
          exit 1
        fi
  
        echo "Restarting Cacao"
        RET_MSG=`${CACAO_ADM} restart 2>&1`
        RET_CODE=$?
        if [ ${RET_CODE} -ne 0 ] ; then
          mLog "Error : Calling [${CACAO_ADM} restart]"
          mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
          cleanUpConfig
          exit 1
        fi
  
      else
  
        echo "Deploying Node Agent in Cacao from descriptor '${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml'"
        RET_MSG=`${CACAO_ADM} deploy ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml 2>&1`
        RET_CODE=$?
        if [ ${RET_CODE} -ne 0 ] 
        then
          mLog "Error : Calling [${CACAO_ADM} deploy ${MFWK_CONF_BASEDIR}/etc/opt/${OS_CONF_DIRNAME}/xml/com.sun.mfwk.xml]"
          mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
          cleanUpConfig
          exit 1
        fi
        
        registerNodeAgent

      fi
    fi
}

doConfigureMFWKSunOS() {  
  # We cannot use 'id -u' because it is not supported by the standard Solaris 'id'...
  MY_UID=`id|sed 's/uid=//g'|sed 's/(.*$//g'`
  MY_DATE=`date +"%Y_%m_%d_%H_%M_%S"`
  doConfigureGeneric
}

doConfigureMFWKLinux() {
  MY_UID=`id -u`
  MY_DATE=`date +"%Y_%m_%d_%H_%M_%S"`
  doConfigureGeneric
}

#
# checkConfigureMFWK, it supposed to be called just once in life
######################################################################
checkConfigureMFWK() {

    if [ "${OS}" = "SunOS" ]
    then 
        CACAO_PKG=${SUNOS_CACAO_PKG}
        if [ ! -f "${FILE_FLAG_FOR_MFWK_CONF_SUNOS}" ]
        then
            doConfigureMFWKSunOS
        elif [ "${OPERATION}" = "DO_INIT" ]
        then
            echo "Already configured: nothing to do."
        fi
    else
        if [ "${OS}" = "Linux" ]
        then
            if [ ! -f "${FILE_FLAG_FOR_MFWK_CONF_LINUX}" ]
             then
                doConfigureMFWKLinux
             elif [ "${OPERATION}" = "DO_INIT" ]
             then
                echo "Already configured: nothing to do."
             fi
         fi
    fi
}

#
# doInit
############################

doInit() {
    # Nothing to do
    return
    # checkConfigureMFWK
}

#
# doRegisterModule
############################

doRegisterModule() {

    mLog2 "Registering module ${MODULE} in cacao"    

    # Check that the module xml file exists
    if [ ! -f "${MODULE}" ]
    then
        mLog "Error : File [${MODULE}] not found."
        exit 1
    fi
    
    mLog2 "Calling [${CACAO_ADM} register-module ${MODULE}]"
    
    RET_MSG=`${CACAO_ADM} register-module ${MODULE} 2>&1`
    RET_CODE=$?
    if [ ${RET_CODE} -ne 0 ] 
    then
         mLog "Error : Calling [${CACAO_ADM} register-module ${MODULE}]"
         mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
         exit 1
    fi
    
if [ "$NOPTION" = "0" ]; then

    mLog2 "Calling [${CACAO_ADM} deploy ${MODULE}]"
    
    RET_MSG=`${CACAO_ADM} deploy ${MODULE} 2>&1`
    RET_CODE=$?
    if [ ${RET_CODE} -ne 0 ] 
    then
         mLog "Error : Calling [${CACAO_ADM} deploy ${MODULE}]"
         mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
         exit 1
    fi
fi

    mLog2 "Registration of module ${MODULE} ended"
}


#
# doUnRegisterModule
############################

doUnRegisterModule() {

    # Check operand terminates with '.xml'
    # Replace string that ends up with '.xml' with nothing
    # If one gets something, then string does not ends up
    # with '.xml'
    XML_TEST=`echo ${MODULE} | sed 's/.*\.xml//'`
    if [ "X${XML_TEST}" != "X" ] ; then
	echo
	mLog "Error: Parameter should terminate with .xml (xml cacao module descriptor)."
	echo
	usage
	exit 1
    fi

    mLog2 "Unregistering module ${MODULE} from cacao"    
    
    BASE_NAME=`basename ${MODULE} .xml`

if [ "$NOPTION" = "0" ]; then
    mLog2 "Calling [${CACAO_ADM} undeploy ${BASE_NAME}]"
    
    RET_MSG=`${CACAO_ADM} undeploy ${BASE_NAME} 2>&1`
    RET_CODE=$?
    if [ ${RET_CODE} -ne 0 ] 
    then
         mLog "Error : Calling [${CACAO_ADM} undeploy ${BASE_NAME}]"
         mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
         exit 1
    fi
fi

    BASE_NAME=`basename ${MODULE}`
    
    mLog2 "Calling [${CACAO_ADM} unregister-module ${BASE_NAME}]"
    
    RET_MSG=`${CACAO_ADM} unregister-module ${BASE_NAME} 2>&1`
    RET_CODE=$?
    if [ ${RET_CODE} -ne 0 ] 
    then
         mLog "Error : Calling [${CACAO_ADM} unregister-module ${BASE_NAME}]"
         mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
         exit 1
    fi

    mLog2 "Unregistration of module ${MODULE} ended"
}


#
# doStartModule
############################

doStartModule() {
    mLog2 "Starting module ${MODULE} in cacao"    
  
    mLog2 "Calling [${CACAO_ADM} start]"
    
    RET_MSG=`${CACAO_ADM} start 2>&1`
    RET_CODE=$? 
    # Check if it worked well (0) or if it was already started (17)
    if [ ${RET_CODE} -ne 0 ] && [ ${RET_CODE} -ne 17 ]
    then
         mLog "Error : Calling [${CACAO_ADM} start]"
         mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
         exit 1
    fi

    mLog2 "Calling [${CACAO_ADM} unlock ${MODULE}]"
    
    RET_MSG=`${CACAO_ADM} unlock ${MODULE} 2>&1`
    RET_CODE=$? 

    if [ ${RET_CODE} -ne 0 ] 
    then
         mLog "Error : Calling  [${CACAO_ADM} unlock ${MODULE}]"
         mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
         exit 1
    fi

    mLog2 "Start of module ${MODULE} ended"
}


#
# doStopModule
############################

doStopModule() {
    mLog2 "Stopping module ${MODULE} in cacao"    
  
    mLog2 "Calling [${CACAO_ADM} lock ${MODULE}]"
    
    RET_MSG=`${CACAO_ADM} lock ${MODULE} 2>&1`
    RET_CODE=$? 

    if [ ${RET_CODE} -ne 0 ]
    then
         mLog "Error : Calling [${CACAO_ADM} lock ${MODULE}]"
         mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
         exit 1
    fi

    mLog2 "Stop of module ${MODULE} ended"
}

#
# doCacaoadmListParams
############################
doCacaoadmListParams() 
{
    MFWK_JAVA_HOME=`${CACAO_ADM} list-params | grep "java-home" | cut -d'=' -f 2`
    NSS_LIB_HOME=`${CACAO_ADM} list-params | grep "nss-lib-home" | cut -d'=' -f 2`
    NSS_TOOLS_HOME=`${CACAO_ADM} list-params | grep "nss-tools-home" | cut -d'=' -f 2`
}

#
# doListParams
############################
doListParams()
{
    # Let try to retrieve params
    doCacaoadmListParams
    
    # If cacao has never been started, these params will be empty
    # Doing a rebuild-dependencies should fix the problem
    # If not, user action is required
    if test -z "${MFWK_JAVA_HOME}" || test -z "${NSS_LIB_HOME}" || test -z "${NSS_TOOLS_HOME}"
    then
        mLog2 "java_home or nss_home not set--asking cacao to rebuild it's dependencies"
	${CACAO_ADM} rebuild-dependencies > /dev/null 2> /dev/null
        RET_CODE=$?
        if [ $RET_CODE -eq 17 ] ; then
          # failed becuase cacao already running, stop it and restart
          # This sceanrio was reported, though it seems to be
          # a race condition scenario: and so hopefully rare..
          # perhaps cacao is starting up and has not yet
          # set it's params...
          ${CACAO_ADM} stop > /dev/null 2> /dev/null
          ${CACAO_ADM} rebuild-dependencies > /dev/null 2> /dev/null
          ${CACAO_ADM} start> /dev/null 2> /dev/null
          
        fi
	# Let retry
	doCacaoadmListParams
    else    
      # So the settings have values, but we had the scenario of an older
      # cacao conf lying around while the dependencies pointed to
      # by that conf have been removed, so try to spot that
      # and cope with it.
       if test -f "${MFWK_JAVA_HOME}/bin/java" && test -f "${NSS_TOOLS_HOME}/certutil"
       then
          mLog2 "Settings look good"          
       else
        mLog "java_home or nss_home seem to be invalid--asking cacao to rebuild it's dependencies"
	${CACAO_ADM} rebuild-dependencies > /dev/null 2> /dev/null
        RET_CODE=$?
        if [ $RET_CODE -eq 17 ] ; then
          # see comment above for an explanation here
          # failed becuase cacao already running, stop it and restart
          ${CACAO_ADM} stop > /dev/null 2> /dev/null
          ${CACAO_ADM} rebuild-dependencies > /dev/null 2> /dev/null
          ${CACAO_ADM} start> /dev/null 2> /dev/null
        fi
	# Let retry
	doCacaoadmListParams
       fi
    fi
}


#
# doListSettings
############################

doListSettings()
{
   
    mLog2 "Do List Settings"  
    if [ "${OS}" = "SunOS" ]
    then
        setEnvSunOS
    elif [ "${OS}" = "Linux" ]
    then
	setEnvLinux
    else
	mLog "Unknown OS...aborting"
	exit 1
    fi

    doListParams

    mLog2 "CACAO_ADM=${CACAO_ADM}"
    mLog2 "MFWK_BASEDIR=${MFWK_BASEDIR}"
    mLog2 "BASEDIR=${BASEDIR}"

    mLog2 "JAVA_HOME=${JAVA_HOME}"
    mLog2 "NSS_HOME=${NSS_HOME}"
    mLog2 "NSS_TOOLS_HOME=${NSS_TOOLS_HOME}"

    mLog "CACAO_HOME=${CACAO_HOME}"
    mLog "MFWK_HOME=${MFWK_HOME}"
    mLog "CACAO_INSTANCE_HOME=${CACAO_INSTANCE_HOME}"
    mLog "MFWK_INSTALL_TYPE=${MFWK_INSTALL_TYPE}"

    mLog "MFWK_JAVA_HOME=${MFWK_JAVA_HOME}"
    mLog "NSS_LIB_HOME=${NSS_LIB_HOME}"
    mLog "NSS_TOOLS_HOME=${NSS_TOOLS_HOME}"
}

#
# doEnableCacao
############################

doEnableCacao() {
    mLog2 "Enabling cacao"    
  
    mLog2 "Calling [${CACAO_ADM} enable]"
    
    RET_MSG=`${CACAO_ADM} enable 2>&1`
    RET_CODE=$? 

    if [ ${RET_CODE} -ne 0 ]
    then
         mLog "Error : Calling [${CACAO_ADM} enable]"
         mLog "Msg: [${RET_MSG}] error=${RET_CODE}"
         exit 1
    fi

    mLog2 "Enabling cacao ended"
}


#
# doUpdate
############################

doUpdate()
{
    CP_XML=$1
    FIELD2CHANGE=$2
    VALUE2SET=$3

    mLog2 "Updating descriptor ${CP_XML}, field ${FIELD2CHANGE} with value ${VALUE2SET}"    
  
# ROB INSERT YOUR CODE HERE

    mLog2 "Update of descriptor ${CP_XML} ended"    
}

#
# doCreateDescriptor
############################
#
# This code for creating a product Cacao descriptor for integrating
# with JESMF is furnished as an aexample to help products 
# understand what is required here and how to find values for these
# attributes.
# See the doc http://jesmf.france/twiki/pub/JESMF20/WebHome/desc-guide.html
# for a description of these attributes.
#

doCreateDescriptor()
{
#pkg name
    PKG_NAME=$1
# eg "ws"
    CODE_NAME=$2
# eg. WebServer
    PROD_NAME=$3
# eg. /opt/SUNWgzip
    INSTALL_LOCATION=$4

if [ "$PKG_NAME" = "" ]
then
    mLog "pkg_name is a mandatory attribute"
    usage
    exit 1
fi
if [ "$CODE_NAME" = "" ]
then
    mLog "pkg_name is a mandatory attribute"
    usage
    exit 1
fi
if [ "$PROD_NAME" = "" ]
then
    mLog "pkg_name is a mandatory attribute"
    usage
    exit 1
fi
if [ "$INSTALL_LOCATION" = "" ]
then
    mLog "pkg_name is a mandatory attribute"
    usage
    exit 1
fi

if [ "$OS" != "SunOS" ]
then
    mLog "Sorry, Create Descriptor only supported on Solaris for the moment"
    exit 1
fi

FILENAME="com.sun.cmm.$CODE_NAME.xml"
mLog2 "Creating descriptor for Product: CODE_NAME=${CODE_NAME}," \
      "PROD_NAME=${PROD_NAME}, PKG_NAME=${PKG_NAME}"   \
      " in file $FILENAME"  

test -f "$FILENAME"
if [ $? ]
then
   mLog2 "Making backup copy of $FILENAME in $FILENAME.bak"
   cp $FILENAME $FILENAME.bak
fi
     
RevisionNumber=`pkgparam ${PKG_NAME} VERSION | cut -f2 -d, | cut -f2 -d=`
	
BuildNumber=$RevisionNumber

PatchID=`pkgparam ${PKG_NAME} PATCHLIST`
if [ "$PatchID" = "" ]
then
    PatchID="No patches currently applied"
fi

Caption=`pkgparam ${PKG_NAME} DESC`

Description=$Caption

# xxx need to convert to miliseconds
InstallDate="1234"
#`pkgparam ${PKG_NAME} INSTDATE`

ProductVersion=`pkgparam ${PKG_NAME} VERSION`

ProductIdentifyingNumber="$PKG_NAME-$ProductVersion"

ProductVendor=`pkgparam ${PKG_NAME} VENDOR`

# factor out hese in case we ever need to change them in the code below
#
MFWK_MODULENAME="com.sun.mfwk"
MFWK_STANDARD_MODULE_CLASS="com.sun.mfwk.MfCpModule"

echo "<?xml version='1.0' encoding='utf-8'?>" > $FILENAME
echo " "
echo "<!DOCTYPE module SYSTEM \"urn:sun:n1:cacao:module:dtd:1_1\">" \
     >> $FILENAME

echo "<!--
   This module instance name is used to refer the module instance.
   The latest part of the module name (i.e : "ws" in this example) MUST BE
   the same String (case sensitive) as "PRODUCT_CODE_NAME_CTX_KEY" in the 
   instrumented component product (initialize method of the Managed element 
   server).
-->" >> $FILENAME
echo "<module name=\"com.sun.cmm.$CODE_NAME\" " \
     "initial-administrative-state=\"UNLOCKED\">" >>$FILENAME

echo "<description>$Description</description>" >>$FILENAME

echo "<!--
   This section describes a strong dependencies on the Java ES MF
   Node Agent 2.0 Module. This implies that the Node Agent 2.0 must
   be loaded and started up by cacao before this module
   can be loaded and started. The name of the Node Agent Module
   is \"com.sun.mfwk\".
-->" >> $FILENAME
echo "<module-dependencies>" >>$FILENAME
echo "  <instance-dependency dependency-type=\"STRONG_DEPENDENCY\">" \
         >>$FILENAME
echo "      <name>$MFWK_MODULENAME</name>" >>$FILENAME
echo "  </instance-dependency>" >>$FILENAME
echo "</module-dependencies>" >>$FILENAME

echo "<!--
   The Java ES MF Node agent 2.0 provides a build-in or generic Module for
   Java ES Component Products using the Java ES Monitoring Framework
   instrumentation toolkit (java or C)
   The Name of this generic module is com.sun.mfwk.MfCpModule.
-->" >> $FILENAME
echo "<module-class>$MFWK_STANDARD_MODULE_CLASS</module-class>" >>$FILENAME

echo "<cacao-version-supported>2.0</cacao-version-supported>" >>$FILENAME
echo "<parameters>" >>$FILENAME

echo "<!--
       Java ES Product Name (exhaustive human readable string identifying the
       product) 
       This parameter must be filled and is case sensitive.
       This paraneter string MUST be the SAME as the "PRODUCT_NAME_CTX_KEY"
       provided at the initialize  method (Managed Element Server API) in the
       instrumented component product. 
-->" >> $FILENAME      
doParam "ProductName" $PROD_NAME

echo "<!--
       Java ES Installation Location 
       This parameter must be filled and is case sensitive.
       The String used here MUST be the SAME as the
       "PRODUCT_COLLECTIONID_CTX_KEY" provided at the initialize  method 
       (Managed Element Server API) in the instrumented component product.
-->" >> $FILENAME
doParam "InstalledLocation" "$INSTALL_LOCATION" 

if [ "$EnableMIB" != "" ]
then
    if [ "$CODE_NAME" = "ws" ]
    then
	MIBNAME=IWS-MIB
    fi
    if [ "$CODE_NAME" = "ds" ]
    then
	MIBNAME=DIRECTORY-SERVER-MIB
    fi
echo " <!--
       This parameter specifies the name of SNMP MIBS that will be supported
       for this Module instance by the Node Agent. This parameter is used by
       the Node Agent to instantiate the the appropriate mediation between
       SNMP requests and CMM objects.
       -->" >> $FILENAME
doParam "SupportedMIBs" "$MIBNAME"
fi
echo "<!--
       The InstalledProduct's Build Number.
 -->" >> $FILENAME
doParam "BuildNumber" "$BuildNumber"

echo " <!--
       The InstalledProduct's Patch ID.
-->"  >> $FILENAME
doParam "PatchID" "$PatchID"

echo "<!--
       The InstalledProduct's Revision
-->" >> $FILENAME
doParam "RevisionNumber" "$RevisionNumber"

echo "<!--
       The InstalledProduct's Installation Date in milliseconds.
-->" >> $FILENAME
doParam "InstallDate" "$InstallDate"

echo "<!--
        The Caption property is a short textual description (one-line string)
        of the installed product.
-->" >> $FILENAME
doParam "Caption" "$Caption"

echo "<!--
       The Description property provides a textual description of the
       installed product.
       -->" >> $FILENAME
doParam "Description" "$Description"

echo "<!--
       The scoping Product's identification.
-->" >> $FILENAME
doParam "ProductIdentifyingNumber" "$ProductIdentifyingNumber"

echo "<!--
       The scoping Product's vendor.
--> " >> $FILENAME
doParam "ProductVendor" "$ProductVendor"

echo "<!--
       The scoping Product's version.
-->" >> $FILENAME
doParam "ProductVersion" "$ProductVersion"
echo "</parameters>"  >>$FILENAME
echo "</module>"  >>$FILENAME

mLog2 "'${RevisionNumber}' '$BuildNumber' '$PatchID' '$InstallDate'" \
     "'$Caption' '$Description' '$ProductIdentifyingNumber'" \
     "'$ProductVendor' '$ProductVersion'"

mLog2 "Creation of descriptor ended"     

}

# helper routine for doCreateDescriptor()
#
doParam(){
echo "  <parameter>"  >>$FILENAME
echo "  <param-name>$1</param-name>"  >>$FILENAME
echo "  <param-value>$2</param-value>"  >>$FILENAME
echo "  </parameter>"  >>$FILENAME
}

########################################################################
########################################################################
########################################################################
########################################################################




############################
# MAIN
############################


# Variables of this script
############################

DO_LOG="NO"
LOG_FILE="/dev/null"

# Special '-N' hidden option of mfwksetup used by the DSEE installer.
NOPTION=0

SUNOS_CACAO_PKG="SUNWcacaort"
LINUX_CACAO_PKG="sun-cacaort"
CACAO_ADM=""

ENABLE_CACAO="DO_NOT_ENABLE_CACAO"
OPERATION="NO_OPERATION_SET"
MODULE=""

if [ `basename $0` = "masetup" ]
then
  MASETUP=1
else
  MASETUP=0
fi



# Start Running
############################


# Treat script call arguments
    if [ $# = 0 ] 
    then
      usage      
    fi

    if [ "$MASETUP" = "1" ]
    then
      # masetup
      while getopts r:u:s:p:d:l:meich c
      do
        case $c in
          i) OPERATION="DO_INIT";;       
          l) LOG_FILE=${OPTARG}
             DO_LOG="YES" ;;
          h) usage ;;
         \?) usage ;;
        esac             
      done
      shift `expr $OPTIND - 1`    

    else
      # mfwksetup

      if [ "$1" = "list-settings" ]
      then
	  OPERATION="DO_LIST_SETTINGS"
      fi
  
      while getopts r:u:s:p:d:l:meichNUP c
      do
        case $c in
          r) MODULE=${OPTARG} 
             OPERATION="DO_REGISTRATION";;       
          u) MODULE=${OPTARG}
             OPERATION="DO_UNREGISTRATION";;       
          s) MODULE=${OPTARG}
             OPERATION="DO_START";;       
          p) MODULE=${OPTARG}
             OPERATION="DO_STOP";;       
          d) XML_FIELD_VALUE="${OPTARG}"
             OPERATION="DO_UPDATE";;       
          e) ENABLE_CACAO="ENABLE_CACAO"
             OPERATION="DO_ENABLE";;       
          i) OPERATION="DO_INIT";;       
          l) LOG_FILE=${OPTARG}
             DO_LOG="YES" ;;
	  m) EnableMIB="YES" ;;          
	  c) CREATE_DESCRIPTOR="CREATE_DESCRIPTOR"
	     OPERATION="DO_CREATE_DESCRIPTOR";;
          h) usage ;;
          N) NOPTION=1;;
          P) OPERATION="DO_PATCH";;
          U) OPERATION="ROLLBACK_PATCH";;
         \?) usage ;;
        esac             
      done
      shift `expr $OPTIND - 1`    
    fi
  
# Setup log file

    if [ ${DO_LOG} = "YES" ]
    then
        TRASH=`touch ${LOG_FILE}`
        if [ $? != 0 ]
        then
            LOG_FILE="/dev/null"
        fi    
    fi


# Setup cacaoadm command location

    OS=`uname -s`
    
    if [ ${OPERATION} = DO_LIST_SETTINGS ]
    then
	doListSettings
	exit 0
    fi

    if [ "${OS}" = "SunOS" ]
    then 
        CACAO_PKG=${SUNOS_CACAO_PKG}
        setupEnvironmentSunOS
    else
        if [ "${OS}" = "Linux" ]
        then
            CACAO_PKG=${LINUX_CACAO_PKG}        
            setupEnvironmentLinux
        else 
            mLog "Error : Operationg system [${OS}], not recognized."
            mLog "Supported operating systems are: SunOS and Linux."
            exit 1            
        fi
    fi 

    checkConfigureMFWK

# Do operation based on arguments

    case ${OPERATION} in
        DO_REGISTRATION)   doRegisterModule ;;
        DO_UNREGISTRATION) doUnRegisterModule ;;
        DO_START)          doStartModule ;;
        DO_STOP)           doStopModule ;;
        DO_UPDATE)         doUpdate ${XML_FIELD_VALUE} ;;
        DO_ENABLE)         doEnableCacao ;;
        DO_PATCH)          doPatch ;;
        ROLLBACK_PATCH)    doRollbackPatch ;;
        DO_INIT)           doInit ;;
	DO_CREATE_DESCRIPTOR) doCreateDescriptor "$1" "$2" "$3" "$4" ;;
        NO_OPERATION_SET)  usage ;;
    esac

# Clean return code
exit 0

