#! /bin/sh

# Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
# ident "$Revision: 1.29.4.1 $ SMI"
#

MIN_JAVA_VERSION="1.4.2_03" 
MIN_JDMK_VERSION="5.1" 

# Must be able to determine target OS so can set up appropriate
# command environment.
OS=`uname -s`
ARCH=`uname -m | sed -e 's+sun4.+SPARC+' -e 's+i.86+x86+'`

if [ -z "${OS}" ]; then
   # No I18N at this point
   echo "Unable to determine operating system."
   exit 1
fi

if [ "${OS}" = "SunOS" ]; then
   # In order of dependency
   BIN="/usr/bin"
   CACAO_ROOT=/opt/SUNWcacao
   LIB_DIR=${CACAO_ROOT}/lib
   PRIVATE_BIN_DIR=${LIB_DIR}/tools
   JAR_DIR=${LIB_DIR}
   # From here: in alphabetical order
   AWK=/usr/bin/nawk
   DEFAULT_FILE=/etc/default/cacao
   ECHO=echo
   GET_TEXT=/usr/bin/gettext
   MANSECTION=1M
   PING=ping
   RPCINFO=/usr/bin/rpcinfo
   WHICH="/bin/ksh whence"  # `which` is csh and create problems sometimes
   HEAD="${BIN}/head"
   SORT="${BIN}/sort"
   DIRNAME="${BIN}/dirname"
   ID="/usr/xpg4/bin/id"
   TAIL="/usr/bin/tail"
   # Localization
   TEXTDOMAINDIR=/opt/SUNWcacao/locale
elif [ "${OS}" = "AIX" ]; then
   # In order of dependency
   BIN="/usr/bin"
   CACAO_ROOT=/opt/SUNWcacao
   LIB_DIR=${CACAO_ROOT}/lib
   PRIVATE_BIN_DIR=${LIB_DIR}/tools
   JAR_DIR=${LIB_DIR}
   # From here: in alphabetical order
   AWK=/usr/bin/nawk
   DEFAULT_FILE=/etc/default/cacao
   ECHO=echo
   GET_TEXT=/usr/bin/echo
   MANSECTION=1
   PING=ping
   RPCINFO=/usr/bin/rpcinfo
   WHICH="/bin/ksh whence"  # `which` is csh and create problems sometimes
   HEAD="${BIN}/head"
   SORT="${BIN}/sort"
   DIRNAME="${BIN}/dirname"
   ID="/usr/bin/id"
   TAIL="/usr/bin/tail"
   # Localization
   TEXTDOMAINDIR=/opt/SUNWcacao/locale
elif [ "${OS}" = "Linux" ]; then
   # In order of dependency
   BIN="/bin"
   CACAO_ROOT=/opt/sun/cacao
   LIB_DIR=${CACAO_ROOT}/private/lib
   PRIVATE_BIN_DIR=${CACAO_ROOT}/private/bin
   JAR_DIR=${CACAO_ROOT}/share/lib
   # From here: in alphabetical order
   AWK=/usr/bin/awk
   DEFAULT_FILE=/etc/opt/default/cacao
   ECHO="/bin/echo -e"
   GET_TEXT=/usr/bin/gettext
   MANSECTION=1
   PATH=/bin:/sbin:/usr/bin:/usr/sbin
   PING="ping -c 1"
   RPCINFO=/usr/sbin/rpcinfo
   WHICH="which --skip-alias"
   HEAD="/usr/bin/head"
   SORT="/bin/sort"
   DIRNAME="/usr/bin/dirname"
   ID="/usr/bin/id"
   TAIL="/usr/bin/tail"
   TEXTDOMAINDIR=/opt/sun/cacao/private/share/locale
else
   echo "Not supported on detected OS \"${OS}\"."
   exit 1
fi

ETC_DIR="/etc${CACAO_ROOT}"
LOG_DIR=/var${CACAO_ROOT}/logs
PASSWD_FILE=/etc${CACAO_ROOT}/security/password
PID_DIR=/var${CACAO_ROOT}/run
PROPERTY_FILE=${ETC_DIR}/cacao.properties
SECURITY_DIR=/etc${CACAO_ROOT}/security
VAR_DIR="/var${CACAO_ROOT}"

# snmpv3 jdmk stuffs
JDMK_SNMPV3_DEPLOYMENT_DESCRIPTOR=${ETC_DIR}/modules/com.sun.cacao.snmpv3_adaptor.xml
DEFAULT_JDMK_SNMPV3_SECURITY_FILE=${ETC_DIR}/security/snmp/jdmk.security
DEFAULT_JDMK_SNMPV3_UACL_FILE=${ETC_DIR}/security/snmp/jdmk.uacl
DEFAULT_JDMK_SNMPV3_ACL_FILE=${ETC_DIR}/security/snmp/jdmk.acl

CAT="${BIN}/cat"
CHMOD="${BIN}/chmod"
CHOWN="${BIN}/chown"
GREP="${BIN}/grep"
MKDIR="${BIN}/mkdir"
MV="${BIN}/mv"
PRINTF="${BIN}/printf"
PS="${BIN}/ps"
RM="${BIN}/rm"
SED="${BIN}/sed"
SH="${BIN}/sh"
SLEEP="${BIN}/sleep"
SU="${BIN}/su"
LOGGER="/usr/bin/logger"
LS="${BIN}/ls"
PKGINFO="/usr/bin/pkginfo"
PKGPARAM="/usr/bin/pkgparam"
PKGCHK="/usr/sbin/pkgchk"
RPM="/bin/rpm"
HOSTNAME="${BIN}/hostname"
RMDIR="${BIN}/rmdir"		# used by keygen

if [ -n "${CACAO_PROTO}" ]; then
    PROPERTY_FILE=etc/cacao.properties
    JAR_DIR="${CACAO_ROOT}/lib"
fi

# PARAMETERS for localization
TEXT_DOMAIN="cacao"
export TEXTDOMAINDIR

JAVA_FLAGS_OPT="JAVA_FLAGS"
JAVA_DEBUG_FLAGS_OPT="JAVA_DEBUG_FLAGS"
JMX_PORT_OPT="JMXMP_PORT"
SNMP_PORT_OPT="SNMP_ADAPTOR_PORT"
SNMP_TRAP_PORT_OPT="SNMP_ADAPTOR_TRAP_PORT"
RETRIES_OPT="RETRIES"
COMMAND_STREAM_ADAPTOR_OPT="COMMAND_STREAM_ADAPTOR_PORT"
ENABLE_OPT="ENABLE"
. ${LIB_DIR}/tools/messages

###############################################################################
#
# Print message according to the locale in stdout
# $1 defaultMessage
# Other parameter are parameter for the message.
#
###############################################################################
printMessage() {
    message=`${GET_TEXT} "${TEXT_DOMAIN}" "$1"`
    shift
    parameters="$*"
    printf "${message} \n" "${parameters}"
}

###############################################################################
#
# Print a message according to the locale in stderr
# $1 defaultMessage
# Other parameter are parameter for the message.
#
###############################################################################
printErrorMessage() {
    message=`${GET_TEXT} "${TEXT_DOMAIN}" "$1"`
    shift
    parameters="$*"
    printf "${message} \n" "${parameters}" >&2
}

###############################################################################
#
# Print a message according to the locale to syslog
# $1 defaultMessage
# Other parameter are parameter for the message.
#
###############################################################################
printSyslogErrorMessage() {
    message=`${GET_TEXT} "${TEXT_DOMAIN}" "$1"`
    shift
    parameters="$*"
    ${LOGGER} -p local0.err -t cacao `printMessage "${message}" "${parameters}"`

}

###############################################################################
#
# resolve_link
#
###############################################################################
resolve_link() {

   prg=$1

   if [ -h "${prg}" ]; then

   # Must cd to where the symbolic link is located as a starting point
    # to follow the link.
    cd `dirname ${prg}`

   # Resolve link to conclusion
    while [ -h "${prg}" ]
       do
   prg=`${LS} -al ${prg} | ${AWK} '{print $NF}'`
   cd `dirname ${prg}`
       done

   # Resolve to full path, in case it's relative.
    prg=`pwd`/`basename ${prg}`
   fi

   $ECHO $prg

}

########################################################
#
# Version to convert a version string in X.Y.Z-* or
# X.Y.X_NN format to XYZNN format so can be treated as a
# number.
#
# $1 = version string
# Returns numerical version
#
########################################################
versionString2Num () {

   # Minor and micro default to 0 if not specified.
   major=`$ECHO $1 | ${AWK} -F. '{print $1}'`
   minor=`$ECHO $1 | ${AWK} -F. '{print $2}'`
   if [ ! -n "$minor" ]; then
   minor="0"
   fi
   micro=`$ECHO $1 | ${AWK} -F. '{print $3}'`
   if [ ! -n "$micro" ]; then
   micro="0"
   fi

   # The micro version may further be extended to include a patch number.
   # This is typically of the form <micro>_NN, where NN is the 2-digit
   # patch number.  However it can also be of the form <micro>-XX, where
   # XX is some arbitrary non-digit sequence (eg., "rc").  This latter
   # form is typically used for internal-only release candidates or
   # development builds.
   #
   # For these internal builds, we drop the -XX and assume a patch number
   # of "00".    Otherwise, we extract that patch number.
   #
   patch="00"
   dash=`$ECHO $micro | ${GREP} "-"`
   if [ $? -eq 0 ]; then
   # Must be internal build, so drop the trailing variant.
    micro=`$ECHO $micro | ${AWK} -F- '{print $1}'`
   fi

   underscore=`$ECHO $micro | ${GREP} "_"`
   if [ $? -eq 0 ]; then
   # Extract the seperate micro and patch numbers, ignoring anything
    # after the 2-digit patch.
    patch=`$ECHO $micro | ${AWK} -F_ '{print substr($2, 1, 2)}'`
    micro=`$ECHO $micro | ${AWK} -F_ '{print $1}'`
   fi

   $ECHO "${major}${minor}${micro}${patch}"

} # versionString2Num 


########################################################
#
# Function to try to find a suitable Java2 runtime.
# If successful, set CACAO_JAVA_HOME and return 0. Otherwise,
# exit with an error message.
#
########################################################
findJava() {
    if [ ! -z "${CACAO_PROTO}" ]; then
	OS_DIR=solaris
	if [ "${OS}" = "Linux" ]; then
	    OS_DIR=linux
	fi
    else
	# Map to a number we can do a numerical comparison on.
	weWant=`versionString2Num $MIN_JAVA_VERSION`

	CACAO_JAVA_HOME=""

	if [ "${OS}" = "SunOS" ]; then
	    # We start by checking the presence of a JAVA 5 binary
	    jdk=SUNWj5rt
	    ${PKGINFO} -iq $jdk
	    if [ "$?" -eq 0 ]; then
		# No need to check the version, we KNOW this is a 1.5 release
		    j5basedir=`env LANG=C LC_ALL=C ${PKGPARAM} ${jdk} BASEDIR`
		    j5binary_home=`${LS} -d ${j5basedir}/jdk/jdk1.5.* | ${SORT} | ${TAIL} -1`
		    if [ -x "${j5binary_home}" ]; then
			    CACAO_JAVA_HOME="${j5binary_home}"
		    fi
	    fi
	    
	    if [ -z "${CACAO_JAVA_HOME}" ]; then
            # Check for a suitable Java by introspecting the SUNWj3rt package
            jdk=SUNWj3rt
	        ${PKGINFO} -iq $jdk
	        if [ "$?" -eq 0 ]; then
	            # Get version, and map to a number we can do a
	            # numerical comparison on.
	            version=`env LANG=C LC_ALL=C ${PKGPARAM} $jdk SUNW_PRODVERS \
		            | ${AWK} -F/ '{print $1}'`
	            weHave=`versionString2Num $version`

		        if [ ${weHave} -ge ${weWant} ]; then
		            j2basedir=`env LANG=C LC_ALL=C ${PKGPARAM} ${jdk} BASEDIR`
		            if [ -x "${j2basedir}/j2se/bin/java" ]; then
			            CACAO_JAVA_HOME="${j2basedir}/j2se"
		            fi
	            fi
	        fi
        fi

   	elif [ "${OS}" = "Linux" ]; then
	    result=""
        
        j5re=`${RPM} -qa | ${GREP} '^jre'`
	    if [ ! -z "${j5re}"  ]; then
		  result="${result} ${j5re}"
	    fi
	    
        j5dk=`${RPM} -qa | ${GREP} '^jdk'`
	    if [ ! -z "${j5dk}"  ]; then
		  if [ -z "${result}" ]; then
		    result="${j5dk}"
		  else
		    result="${result} ${j5dk}"
		  fi
	    fi

        j2re=`${RPM} -qa | ${GREP} '^j2re'`
	    if [ ! -z "${j2re}"  ]; then
		  if [ -z "${result}" ]; then
		    result="${j2re}"
		  else
		    result="${result} ${j2re}"
		  fi
	    fi
	    
        j2sdk=`${RPM} -qa | ${GREP} '^j2sdk'`
	    if [ ! -z "${j2sdk}"  ]; then
		  if [ -z "${result}" ]; then
		    result="${j2sdk}"
		  else
		    result="${result} ${j2sdk}"
		  fi
	    fi

	    for jdk in $result
	    do
		# Get version, and map to a number we can do a
		# numerical comparison on.
		version=`env LANG=C LC_ALL=C ${RPM} -qi $jdk \
		    | ${GREP} "^Version" | ${AWK} '{print $3}'`
		weHave=`versionString2Num $version`

		if [ ${weHave} -ge ${weWant} ]; then
		    bindir=`${RPM} -ql $jdk | ${GREP} "/bin$" | ${SORT} | ${HEAD} -1`
		    if [ -x "${bindir}/java" ]; then
			CACAO_JAVA_HOME=`${DIRNAME} $bindir`
			break
		    fi
		fi
	    done
	fi

	if [ -z "${CACAO_JAVA_HOME}" ]; then
	    printErrorMessage "${MISSING_JAVA}" "${MIN_JAVA_VERSION}"
	    printSyslogErrorMessage "${MISSING_JAVA}" "${MIN_JAVA_VERSION}"
	    exit 1
	fi
    fi
    return 0
}

########################################################
#
# Function to find NSS libs and tools. If they are found,
# NSS_LIB_HOME is set to the location of the NSS libraries
# and NSS_TOOLS_HOME to the location of NSS tools.
# Otherwise both variables are empty or non-existing.
#
########################################################
findNSS() {

    if [ "${OS}" = "SunOS" ]; then 
		# Is the SUNWtls package installed ?
		NSS_LIB_PKG="SUNWtls"
		${PKGINFO} -iq ${NSS_LIB_PKG}
		if [ $? -eq 0 ]; then
			## NSS lib package found. Locate the home of libraries.
		    nsslibdir=`env LANG=C LC_ALL=C ${PKGPARAM} ${NSS_LIB_PKG} BASEDIR`
		    if [ -f "${nsslibdir}/usr/lib/mps/secv1/libnss3.so" ]; then 
			    NSS_LIB_HOME="${nsslibdir}/usr/lib/mps/secv1"
		    fi
		fi
		
		# Is the SUNWtlsu package installed ?
		NSS_TOOLS_PKG="SUNWtlsu"
		${PKGINFO} -iq ${NSS_TOOLS_PKG}
		if [ $? -eq 0 ]; then
			## NSS Tools package found. Find where is certutil
		    nsstoolsdir=`env LANG=C LC_ALL=C ${PKGPARAM} ${NSS_TOOLS_PKG} BASEDIR`
		    if [ -x "${nsstoolsdir}/usr/sfw/bin/certutil" ]; then 
			    NSS_TOOLS_HOME="${nsstoolsdir}/usr/sfw/bin"
		    fi
		fi
				
	elif [ "${OS}" = "Linux" ]; then	
		# Is certutil available through the sun-nss-3.* package ?
		NSS_PKG=`${RPM} -qa | ${GREP} '^sun-nss-3\.' | ${HEAD} -1`
		if [ -n "${NSS_PKG}" ] ; then
		    # extract lib location from pkg info and validate
		    nsslibdir=`${RPM} -ql ${NSS_PKG} | ${GREP} lib | ${HEAD} -1`
		    if [ -f "${nsslibdir}/libnss3.so" ]; then 
			    NSS_LIB_HOME="${nsslibdir}"
		    fi
		    # extract tools location from pkg info and validate
		    nsstoolsdir=`${RPM} -ql ${NSS_PKG} | ${GREP} bin | ${HEAD} -1`
		    if [ -x "${nsstoolsdir}/certutil" ]; then 
			    NSS_TOOLS_HOME="${nsstoolsdir}"
		    fi
		fi
	fi 

    return 0
}

########################################################
#
# Function to find JDMK 5.1 or higher. If it can be 
# found, JDMK_HOME variable is set to the absolute path
# where is located the lib/ sub-directory containing
# all the JDMK jar files required by Cacao.
#
# Otherwise, exit with an error message.
#
########################################################
findJDMK() {
	weWant=`versionString2Num $MIN_JDMK_VERSION`
	
	# Solaris
	if [ "${OS}" = "SunOS" ]; then 
		# Are the SUNWjdmk-runtime and SUNWjdmk-runtime-jmx packages installed ?
		JDMKRT_PKG="SUNWjdmk-runtime"
		JMXRT_PKG="SUNWjdmk-runtime-jmx"
		${PKGINFO} -iq ${JDMKRT_PKG} && ${PKGINFO} -iq ${JMXRT_PKG}
		if [ $? -eq 0 ]; then
			## JDMK runtime packages found. Are they 5.1 ?
	        version=`env LANG=C LC_ALL=C ${PKGPARAM} ${JDMKRT_PKG} SUNW_PRODVERS`
	        JDMKRT_VERSION=`versionString2Num $version`
	        version=`env LANG=C LC_ALL=C ${PKGPARAM} ${JMXRT_PKG} SUNW_PRODVERS`
	        JMXRT_VERSION=`versionString2Num $version`

            if [ ${JDMKRT_VERSION} -eq ${JMXRT_VERSION} ]; then
		        if [ ${JDMKRT_VERSION} -ge ${weWant} ]; then
		            jdmkdir=`env LANG=C LC_ALL=C ${PKGPARAM} ${JDMKRT_PKG} BASEDIR`
		            if [ -f "${jdmkdir}/SUNWjdmk/${version}/lib/jdmkrt.jar" ]; then
			            JDMK_HOME="${jdmkdir}/SUNWjdmk/${version}"
		            fi
	            fi
            fi
		    
		fi
		
	# Linux
	elif [ "${OS}" = "Linux" ]; then	
		# Are the sun-jdmk-runtime-5.1-* and sun-jdmk-runtime-jmx-5.1-* 
		# packages installed ?
		JDMKRT_PKG=`${RPM} -qa | ${GREP} '^sun-jdmk-runtime' | ${HEAD} -1`
		JMXRT_PKG=`${RPM} -qa | ${GREP} '^sun-jdmk-runtime-jmx' | ${HEAD} -1`
		
        if [ \( -n "${JDMKRT_PKG}" \) -a \( -n "${JMXRT_PKG}" \) ]; then
		    
	        version=`env LANG=C LC_ALL=C ${RPM} -qi $JDMKRT_PKG \
		        | ${GREP} "^Version" | ${AWK} '{print $3}'`
	        JDMKRT_VERSION=`versionString2Num $version`
	        version=`env LANG=C LC_ALL=C ${RPM} -qi $JMXRT_PKG \
		        | ${GREP} "^Version" | ${AWK} '{print $3}'`
	        JMXRT_VERSION=`versionString2Num $version`

		    if [ ${JDMKRT_VERSION} -eq ${JMXRT_VERSION} ]; then
		        if [ ${JDMKRT_VERSION} -ge ${weWant} ]; then
                    jdmkdir=`${RPM} -ql ${JDMKRT_PKG} \
                        | ${GREP} "jdmk/${version}" | ${HEAD} -1`
		            if [ -f "${jdmkdir}/lib/jdmkrt.jar" ]; then
			            JDMK_HOME="${jdmkdir}"
		            fi
                fi
	        fi
		fi
	fi 

	if [ -z "${JDMK_HOME}" ]; then
	    printErrorMessage "${MISSING_JDMK}" "${MIN_JDMK_VERSION}"
	    printSyslogErrorMessage "${MISSING_JDMK}" "${MIN_JDMK_VERSION}"
	    exit 1
	fi
	
	return 0
}

######################################################################################
# use to retrieve a parameter value inside a module xml descriptor file
# $1 : xml file t parse
# $2 : param name
# if parameter entry not found and "<param-name>" not found look for parameter entry
# if we found "<param-name>" check if it is the one we want (=${PARAM})
# if we found the parameter we want , check for "</param-name>" flag
# if we found the entire parameter entry (<param-name>$PARAM</param-name>) stop looking for that and start looking
#     for parameter value entry
# if we found parameter entry look for parameter tag "<param-value>"
# if we found parameter tag "<param-value>" start copying input (all character after "<param-value>" may be our value)
# if we found parameter tag "<param-value>" , look for parameter tag "</param-value>"
# as soon as we have found "</param-value>" everything should be ok
# END : as we were doing a blind copy of everything starting at "<param-value>" tag, we may have copyed
#       xml tag also , remove them
#
######################################################################################
get_xml_property () {
    #we assume that xml file is syntaxicaly correct
    _file=$1
    _param_to_find=$2

    ${CAT} $_file | ${AWK} -v _param_name=${_param_to_find}  'BEGIN {param_value_found = 0;
                                                         param_value_tag_start=0;
                                                         param_value_candidate="";
                                                         param_found=0} {       \
        if (param_found==0 && param_name_start_pos == 0)    param_name_start_pos=index($0,"<param-name>");
        if (param_found==0 && param_name_start_pos > 0)     param_name_pos=index($0,_param_name);
	if (param_found==0 && param_name_pos > 0)           param_name_end_pos=index($0,"</param-name>");
        if (param_found==0 && param_name_end_pos > 0)       param_found=1;
        if (param_found==1 && param_value_tag_start == 0)   param_value_tag_start=index($0,"<param-value>");
        if (param_value_tag_start > 0 )                     param_value_tag_stop=index($0,"</param-value>");
        if (param_value_tag_start > 0 )                     param_value_candidate=sprintf("%s%s",param_value_candidate,$0);
        if (param_value_tag_stop > 0 && length(param_value_candidate) > 0) {param_value_found = 1 ;exit;}
   } END {
      if (param_value_found == 1) {\
       if (index(param_value_candidate,"<param-value>"))  gsub("<param-value>","",param_value_candidate);
       if (index(param_value_candidate,"</param-value>")) gsub("</param-value>","",param_value_candidate);
       print param_value_candidate;
      }
}' 2>/dev/null

}
######################################################################################
# use to  get the owner of a file
# $1 : filename
# NOTICE : file must exist
######################################################################################
get_file_owner () {
    ${LS} -l $1 | ${AWK} '{print $3}'
}

######################################################################################
# use to  get the group owner of a file
# $1 : filename
# NOTICE : file must exist
######################################################################################
get_file_group () {
    ${LS} -l $1 | ${AWK} '{print $4}'
}

######################################################################################
# use to insure that a specified user will be able to read a file
# $1 filename to check
# $2 username who must be able to read
# if owner of the file different of specified user : change owner
# if read bit not set for user : set it
# NOTICE : file must exist
######################################################################################
insure_read_access () {
    _filepath=$1
    _user=$2

    f_owner=`get_file_owner $_filepath`
    if [ "$f_owner" != "$_user" ]
    then
	${CHOWN} $_user $_filepath 2>/dev/null
	if [ $? -ne 0 ]
	then
	  return 1  
	fi
    fi

    user_can_read=`${LS} -l $_filepath | ${AWK} '{print substr($1,2,1);}'`
    if [ "$user_can_read" != "r" ]
    then
	${CHMOD} u+r $_filepath 2>/dev/null
	if [ $? -ne 0 ]
	then
	  return 1  
	fi
    fi

    return 0

}
######################################################################################
# use to insure that a specified user will be able to read a file
# $1 filename to check
# $2 username who must be able to read
# if owner of the file different of specified user : change owner
#if rw bits not set for user : set it
#NOTICE : file must exist
######################################################################################
insure_readwrite_access () {
    _filepath=$1
    _user=$2

    f_owner=`get_file_owner $_filepath`
    if [ "$f_owner" != "$_user" ]
    then
	${CHOWN} $_user $_filepath 2>/dev/null
	if [ $? -ne 0 ]
	then
	  return 1  
	fi
    fi

    user_can_rw=`${LS} -l $_filepath | ${AWK} '{print substr($1,2,2);}'`
    if [ "$user_can_read" != "rw" ]
    then
	${CHMOD} u+rw $_filepath 2>/dev/null
	if [ $? -ne 0 ]
	then
	  return 1  
	fi
    fi

    return 0

}

#######################################################################################
# use to check snmpv3 security config file
# no argument
# in order to use snmpv3 adaptor 
# we must insure that the user id used by cacao at runtime
# will be able to 
# * read/write the jdmk security file (default: /etc/opt/SUNWcacao/security/snmp/jdmk.security)
# * read/write the jdmk uacl     file (default: /etc/opt/SUNWcacao/security/snmp/jdmk.uacl)
# * read       the jdml acl      file (default: /etc/opt/SUNWcacao/security/snmp/jdmk.acl) 
#######################################################################################

check_snmp_config () {
   #first check that snmpv3 module will be deploy

   if [ ! -f ${JDMK_SNMPV3_DEPLOYMENT_DESCRIPTOR} ] 
   then
    return 0;
   fi

   #get the user which will be used 
   user_to_use=`getProperty "${PROCESS_USERNAME_KEY}"`
   if [ -z "${user_to_use}" ]; then
    user_to_use=${DEFAULT_PROCESS_USERNAME}
   fi 
    
   jdmk_acl_file_path=`get_xml_property ${JDMK_SNMPV3_DEPLOYMENT_DESCRIPTOR} "jdmk.acl.file"`
   jdmk_uacl_file_path=`get_xml_property ${JDMK_SNMPV3_DEPLOYMENT_DESCRIPTOR} "jdmk.uacl.file"`
   jdmk_security_file_path=`get_xml_property ${JDMK_SNMPV3_DEPLOYMENT_DESCRIPTOR} "jdmk.security.file"`

   #what we should do if one file is missing ?

   #to avoid triming, check now and use [ -f $var ] instead of [ -f "$var" ] later
   if [ "x$jdmk_acl_file_path" = "x" ]
   then
    printErrorMessage "${JDMK_SNMP_CONFIG_FILE_MISSING}" "jdmk.acl"
    return 1
   fi 
   if [ "x$jdmk_uacl_file_path" = "x" ]
   then
    printErrorMessage "${JDMK_SNMP_CONFIG_FILE_MISSING}" "jdmk.uacl"
    return 1
   fi 
   if [ "x$jdmk_security_file_path" = "x" ]
   then
    printErrorMessage "${JDMK_SNMP_CONFIG_FILE_MISSING}" "jdmk.security"
    return 1
   fi 
   
   #check file existence and access
  
   if [ -f ${jdmk_acl_file_path} ]
   then
    #check read access
    insure_read_access ${jdmk_acl_file_path} $user_to_use
    if [ $? -ne 0 ]
    then
	printErrorMessage "${CANNOT_SET_R_ACCESS}" ${jdmk_acl_file_path} ${user_to_use}
	return 1
    fi
   else
    printErrorMessage "${INVALID_JDMK_SNMP_SECURITY_FILE}" ${jdmk_acl_file_path}
    return 1
   fi
   
   if [ -f ${jdmk_uacl_file_path} ]
   then
    #check read/write access
    insure_readwrite_access ${jdmk_uacl_file_path} $user_to_use
    if [ $? -ne 0 ]
    then
	printErrorMessage "${CANNOT_SET_RW_ACCESS}" ${jdmk_uacl_file_path} ${user_to_use}
	return 1
    fi
   else
    printErrorMessage "${INVALID_JDMK_SNMP_SECURITY_FILE}" ${jdmk_uacl_file_path}
    return 1
   fi

   if [ -f ${jdmk_security_file_path} ]
   then
    #check read/write access
    insure_readwrite_access ${jdmk_security_file_path} $user_to_use
    if [ $? -ne 0 ]
    then
	printErrorMessage "${CANNOT_SET_RW_ACCESS}" ${jdmk_security_file_path} ${user_to_use}
	return 1
    fi
   else
    printErrorMessage "${INVALID_JDMK_SNMP_SECURITY_FILE}" ${jdmk_security_file_path}
    return 1
   fi

   
   return 0

}
