#! /bin/ksh

# Global variables
#------------------

# Minimum java version needed to run this script
MIN_JAVA_VERSION="1.4"

# Where we are
EXEC_DIR=`dirname $0`
MFWK_ROOT=${EXEC_DIR}/..

# OS
OS=`uname -s`

# OS dependant variables
if [ "${OS}" = "SunOS" ]
then
  WHICH="/bin/ksh whence"
  GREP="/usr/bin/grep" 
  PKGINFO="/usr/bin/pkginfo"
  SED="/usr/bin/sed"
  PKGCHK="/usr/sbin/pkgchk"
  ECHO="echo"
  CUT="/usr/bin/cut"
  LS="/usr/bin/ls"
elif [ "${OS}" = "Linux" ]
then
  WHICH="which --skip-alias"
  GREP="/bin/grep"
  RPM="/bin/rpm"
  ECHO="/bin/echo -e"
  CUT="/bin/cut"
  LS="/bin/ls"
else
  echo "Not supported operating system: ${OS}"
  exit 1
fi

# Utility functions
#-------------------

# javaVersion2Num
# Convert a java version number to a number.
#
# Java version is of the form: Major.Minor.Micro
#                              Major.Minor.Micro_Patch
#                          or  Major.Minor.Micro-release
#                          or  Major.Minor.Micro_Patch-release
# where
#   Major is a number (1 for now)
#   Minor is a number (2,3,4,5 for ex)
#   Micro is a number (2,3,4 for ex)
#   Patch is a 2-digit number (02, 03 for ex.)
#   release is a 2-letter sequence used for internal builds
#
# Ex: 
#    1.2.2, 1.4.2_03, 1.4.2_rc, 1.5.0_01-ea
#
javaVersion2Num() {
  version=$1
  major=`echo $version | cut -d. -f1`
  [ -z $major ] && major=0
  minor=`echo $version | cut -d. -f2`
  [ -z $minor ] && minor=0

  # If it is an internal build. let remove the release field as we don't need it
  dash=`echo $version | grep "-"`
  if [ $? -eq 0 ]
  then
    version=`echo $version |cut -d'-' -f1`
  fi

  # BugId 6174357
  # We assume that there is no patch number, and this is not an internal build
  patch="00"
  micro=`echo $version | cut -d. -f3`

  # Let check if there is a patch number
  underscore=`echo $version | grep "_"`
  if [ $? -eq 0 ]
  then
    # there is a patch number. Let extract it
    micro=`echo $version | cut -d. -f3 | cut -d_ -f1`
    patch=`echo $version | cut -d. -f3 |  cut -d_ -f2`
  fi

  # paranoid checks
  [ -z $micro ] && micro=0
  [ -z $patch ] && patch="00"

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


# Find a suitable java executable
JAVA_LOC=""

min_version=`javaVersion2Num $MIN_JAVA_VERSION`
# Is $JAVA_HOME set ?
if [ -n "${JAVA_HOME}" ]
then
   echo "JAVA_HOME=${JAVA_HOME}"
   JAVA_LOC="${JAVA_LOC} ${JAVA_HOME}/bin/java"
fi
# Let add also the java in the path
JAVA_PATH=`${WHICH} java 2>&1`
if [ $? -eq 0 ]
then
  JAVA_LOC="${JAVA_LOC} ${JAVA_PATH}"
fi
# Let add standard location
if [ "${OS}" = "SunOS" ]
then
  # Bugid 6174357
  # JAVA_LOC="${JAVA_LOC}  /usr/j2se/bin/java /usr/jdk/jdk1.5.0/bin/java"
  JAVA_LOC="${JAVA_LOC}  /usr/j2se/bin/java"

  # let find all the versions installed in /usr/jdk if any
  if [ -d /usr/jdk ]
  then
    ${LS} /usr/jdk/ | while read jdir
    do
      if [ -x /usr/jdk/${jdir}/bin/java ]
      then
        JAVA_LOC="${JAVA_LOC} ${jdir}/bin/java"
      fi
    done
  fi
fi

if  [ "${OS}" = "Linux" ]
then
  # Bugid 6174357
  # Bugid 6176806
  # let find all the versions installed in /usr/java/ if any
  if [ -d /usr/java ]
  then
    USRJAVA=`ls /usr/java 2>/dev/null | awk '{printf("/usr/java/%s/bin/java ",$0)}'`
    JAVA_LOC="$USRJAVA $JAVA_LOC"
  fi
fi

# Let use the first one which meets the version requirement.
for j in ${JAVA_LOC}
do
  if [ -x $j ]
  then
    VERSION=`$j -version 2>&1 | grep "java version"`
    VERSION=`echo $VERSION | cut -d\" -f2`
    java_version=`javaVersion2Num $VERSION`
    if [ $java_version -ge $min_version ]
    then
      JAVA=$j
      break
    fi
  fi
done

# If JAVA is not set, let's try by looking in pkginfo database
if [ -z ${JAVA} ]
then
  if [ "${OS}" = "SunOS" ]
  then
    # Let try to find the java by looking in pkginfo database
    jdk=SUNWj3rt
    ${PKGINFO} $jdk >/dev/null 2>&1
    if [ "$?" -eq 0 ]
    then
      j2basedir=`env LANG=C LC_ALL=C pkgparam ${jdk} BASEDIR`
      VERSION=`${j2basedir}/j2se/bin/java -version 2>&1 | grep "java version"`
      VERSION=`echo $VERSION | cut -d\" -f2`
      java_version=`javaVersion2Num $VERSION`
      if [ $java_version -ge $min_version ]
      then
        JAVA=${j2basedir}/j2se/bin/java
      fi
    fi
  fi
# Bugid 5062621
#   if [ "${OS}" = "Linux" ]
#   then
#     # Let try to find the java by looking in rpm database
#     jres=`${RPM} -qa | grep j2re`
#     jdks=`${RPM} -qa | grep j2sdk`
#     for l in "$jres $jdks"
#     do
#       bindir=`${RPM} -ql $l | grep "/bin$" | sort | head -1`
#       VERSION=`${bindir}/java -version 2>&1 | grep "java version"`
#       VERSION=`echo $VERSION | cut -d\" -f2`
#       java_version=`javaVersion2Num $VERSION`
#       if [ $java_version -ge $min_version ]
#       then
#         JAVA=$bindir/java
#         break
#       fi
#     done
#   fi 
fi

if [ ! -n "${JAVA}" ]
then
  # We are not able to find a suitabe java runtime
  $ECHO "No suitable Java runtime found."
  $ECHO "Please set the JAVA_HOME environment variable and retry."
  exit 1
fi

KEYTOOL=`dirname $JAVA`/keytool

# Find location of NSS
if [ "${OS}" = "SunOS" ]
then    
  NSS_PKG=`${PKGINFO} -i | ${GREP} SUNWtlsu | ${SED} -e 's@^.*\(SUNWtlsu.\{0,1\}\).*$@\1@'`
  if [ -n "${NSS_PKG}" ]
  then # NSS Tools package found. Find where is certutil
    # THIS WILL NOT WORK ON S10 OPTERON, IT WILL HAVE TO BE FIXED.
    CERTUTIL=`${PKGCHK} -l ${NSS_PKG} | ${GREP} certutil | ${SED} -e 's@^Pathname: @@' | grep -v amd64`
  fi
elif [ "${OS}" = "Linux" ]
then
  if [ -x /opt/sun/private/bin/certutil ]
  then
    CERTUTIL=/opt/sun/private/bin/certutil
    # Bugid 6176829
    LD_LIBRARY_PATH=/opt/sun/private/lib
    export LD_LIBRARY_PATH
  fi
  # Bugid 5062621    
  # Is certutil available through the sun-nss-3.* package ?
  #CERTUTIL_PKG=`${RPM} -qa | grep '^sun-nss-3\.' | head -1`
  #if [ ! -z "$CERTUTIL_PKG" ]
  #then
  #   CERTUTIL=`${RPM} -ql $CERTUTIL_PKG | ${GREP} certutil`
  #fi
fi

if [ -z "$CERTUTIL" ]
then
  $ECHO "Cannot find certutil command"
  exit 1
fi

# Needed for password generation
if [ "${OS}" = "SunOS" ]
then
  CLASSPATH=${MFWK_ROOT}/lib/mfwk_sdk.jar
elif [ "${OS}" = "Linux" ]
then
  CLASSPATH=${MFWK_ROOT}/share/lib/mfwk_sdk.jar
fi

# Keytool/NSS
ALGO="RSA"
KEYSIZE=1024
SIGALGO="MD5withRSA"
VALIDITY=7300
VALIDITY_MONTH=240
DNAME="CN=mwfk_ca, OU=mfwk_agent, O=Sun Microsystems, L=Grenoble, ST=France, C=FR"
CA_DNAME="CN=`hostname`, OU=mfwk_agent, O=Sun Microsystems, L=Grenoble, ST=France, C=FR"
STORETYPE="jks"

# Paths
if [ "${OS}" = "SunOS" ]
then
  SECURITY_DIR=${SECURITY_DIR:-/etc/opt/SUNWmfwk/security}
fi

if [ "${OS}" = "Linux" ]
then
  SECURITY_DIR=${SECURITY_DIR:-/etc/opt/sun/mfwk/security}
fi

AGENT_KEYSTORE=${SECURITY_DIR}/keystore
AGENT_TRUSTSTORE=${SECURITY_DIR}/truststore
AGENT_PASS_FILE=${SECURITY_DIR}/passwd
AGENT_PRIV_ALIAS=mfwk_agent
AGENT_TRUST_PASS="mfwktrust"

GEN_PASS_CLASS="com.sun.mfwk.security.password.MfPassword"
GEN_SEED_CLASS="com.sun.mfwk.security.genkey.MfRandom"
MFWK_TMP_SEED=/tmp/mfwk.seed

TMP_OUT=/tmp/mfwkcmd.out
