#!/bin/sh 

# PROPRIETARY AND CONFIDENTIAL
# Copyright 1999-2004 Sun Microsystems, Inc.  All rights reserved
# 
# This script is run after the entire package has been installed.
#
# This script does additional processing after the entire package is
# installed, such as editing configuration files, adding files not
# done by the package add, etc.


# maintain consistency between these and the schema definition
IM_OC_OID="sunIMUser-oid"
PRESENCE_OC_OID="sunPresenceUser-oid"
IM_OC="sunIMUser"
PRESENCE_OC="sunPresenceUser"
PROP_FILE="/etc/opt/SUNWam/config/AMConfig.properties"

#################################################################################
# Exit codes for installation scripts 
#################################################################################

e_ok=0	       # script completed successfully.
e_fatal=1      # stop installation on this exit
e_warning=2    # Installation will go on. 
e_int=3        # Interrupted. Stop installation
e_reboot=10    # User must reboot after installation of all selected packages
               # To be added to one of the single-digit exit code above
e_rebootnow=20 # User must reboot right after installation of current package
               # To be added to one of the single-digit exit code above
# Trap interrupt
trap `exit $e_int` 15

MYNAME=`basename $0`
EC=${e_ok}

. PASSFILE

CAT=/bin/cat
GREP=/bin/grep
EGREP=/bin/egrep
MV=/bin/mv
RM=/bin/rm
LN=/bin/ln
SED=/bin/sed
CP=/bin/cp
LDAPSEARCH=/usr/bin/ldapsearch
LDAPMODIFY=/usr/bin/ldapmodify
LDAPDELETE=/usr/bin/ldapdelete
OS="`uname -s`"
if [ "$OS" = "Linux" ]; then
  # use simple authentication on Linux
  LDAP_OSFLAGS="-x"
else
  LDAP_OSFLAGS=""
fi

#############################################################
# Assign IMService to all users of default org
#############################################################
AssignService() {

  USERDN_RESULTS="/tmp/im-userDNResults.txt"
  ASSIGN_SERVICE_LDIF="/tmp/im-assignService.ldif"
  cp /dev/null ${ASSIGN_SERVICE_LDIF}

  $LDAPSEARCH ${LDAP_OSFLAGS} -h ${DS_HOST} -p ${DS_PORT} -b "$PEOPLE_DN" -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" "objectclass=iplanet-am-managed-person" -s "one" "dn" > $USERDN_RESULTS
  if [ "$OS" = "Linux" ]; then
    grep '^dn:' $USERDN_RESULTS | sed -e 's/^dn: //' > ${USERDN_RESULTS}.tmp
    mv ${USERDN_RESULTS}.tmp $USERDN_RESULTS
  fi

  file_length=`wc -l $USERDN_RESULTS | cut -c1-8`
  file_length=`expr $file_length + 0`

  count=1
  recordcount=0

  while [ $count -le $file_length ]; do
    line=`head -$count $USERDN_RESULTS | tail -1`
    if [ "$line" != "" ] && [ "$line" != "version: 1" ]; then
      $CAT >> ${ASSIGN_SERVICE_LDIF} << EOF
dn: $line
changetype: modify
add: objectclass
objectclass: ${IM_OC}
objectclass: ${PRESENCE_OC}

EOF
      recordcount=`expr $recordcount + 1`
    fi
    count=`expr $count + 1`
    if [ $recordcount -eq 500 ]; then
      $LDAPMODIFY ${LDAP_OSFLAGS} -c -h ${DS_HOST} -p ${DS_PORT} -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" -f $ASSIGN_SERVICE_LDIF
      $RM ${ASSIGN_SERVICE_LDIF}
      recordcount=0
    fi
  done

  if [ $recordcount -ne 0 ]; then
    $LDAPMODIFY ${LDAP_OSFLAGS} -c -h ${DS_HOST} -p ${DS_PORT} -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" -f ${ASSIGN_SERVICE_LDIF}
    # $RM ${ASSIGN_SERVICE_LDIF}
  fi

  $RM $USERDN_RESULTS
}

#OLD_LD_LIBRARY_PATH=$LD_LIBRARY_PATH

if [ "$OS" = "Linux" ]
then
  # Collect Linux versions of IM_BASEDIR, AM_BASEDIR, and JAVA_HOME here
  IM_BASEDIR=`rpm -q --qf "%{INSTPREFIXES}" sun-im-ident`
  if [ "$IM_BASEDIR" = "(none)" ]; then
    IM_BASEDIR=`rpm -q --qf "%{DIRNAMES}" sun-im-ident`
    IM_BASEDIR=`dirname $IM_BASEDIR`
  fi
  rpm -q SUNWamsdk > /dev/null 2>&1
  EC=$?
  if [ $EC -eq 0 ] ; then
    # try the old name
    AM_BASEDIR=`rpm -q --qf "%{INSTPREFIXES}" SUNWamsdk`
    if [ "$AM_BASEDIR" = "(none)" ]; then
      AM_BASEDIR=`rpm -q --qf "%{DIRNAMES}" SUNWamsdk`
      AM_BASEDIR=`dirname $AM_BASEDIR`
    fi
  else
    # use the new IS SDK name
    AM_BASEDIR=`rpm -q --qf "%{INSTPREFIXES}" sun-identity-sdk`
    if [ "$AM_BASEDIR" = "(none)" ]; then
      AM_BASEDIR=`rpm -q --qf "%{DIRNAMES}" sun-identity-sdk`
      AM_BASEDIR=`dirname $AM_BASEDIR`
    fi
  fi
  JAVA_HOME=`grep "jdk.path" $PROP_FILE|cut -f2 -d=`
  PROD_DIR=${IM_BASEDIR}/im
else
  IM_BASEDIR=`pkgparam -v SUNWiimid|grep "^BASEDIR="|cut -f2 -d= | sed -e s/\'//g''`
  AM_BASEDIR=`pkgparam -v SUNWamsdk|grep "^BASEDIR="|cut -f2 -d= | sed -e s/\'//g''`
  JAVA_HOME=`pkgparam -v SUNWamsdk |grep "^JDK_BASE_DIR=" | cut -f2 -d = |sed -e s/\'//g''`
  PROD_DIR=${IM_BASEDIR}/SUNWiim
  if [ ! -r $PROP_FILE ]; then
    # Try falling back to IS6.1 location
    PROP_FILE=${AM_BASEDIR}/SUNWam/lib/AMConfig.properties
  fi
fi
AM_HOME=${AM_BASEDIR}/SUNWam
USING_JDK14=

if [ "$OS" = "Linux" ]; then
  MPS_JAR_PATH=/usr/share/lib/mps/secv1
else
  MPS_JAR_PATH=/usr/share/lib/mps
fi
MPS_LIB_PATH=/usr/lib/mps:${PROD_DIR}/lib
JAXP_HOME=/usr/share/lib

JSS_JAR=${MPS_JAR_PATH}/jss3.jar
if [ ! -r $JSS_JAR ]; then
    # For point-product installer, try falling back to IS location
    JSS_JAR=${AM_BASEDIR}/SUNWam/lib/jss3.jar
fi
SDK_JARS=${AM_HOME}/lib/am_sdk.jar:${AM_HOME}/lib/am_services.jar:${AM_HOME}/lib/jaas.jar
AM_DIRS=${AM_HOME}/lib:${AM_HOME}/locale:${AM_HOME}/config
JAXP_JARS=${JAXP_HOME}/jaxp-api.jar:${JAXP_HOME}/xalan.jar:${JAXP_HOME}/xercesImpl.jar:${JAXP_HOME}/sax.jar:${JAXP_HOME}/dom.jar 
SERVLET_JARS=${AM_HOME}/lib/servlet.jar:${AM_HOME}/lib/preference_servlet.jar
LOGGING_JARS=${AM_HOME}/lib/am_logging.jar
LDAPJDK_JARS=${PROD_DIR}/lib/ldapjdk.jar:${PROD_DIR}/lib/ldapsp.jar:${PROD_DIR}/lib/ldapfilt.jar

JAVA_CLASSPATH=${AM_DIRS}:${SDK_JARS}:${JSS_JAR}:${SERVLET_JARS}:${LOGGING_JARS}:${JAXP_JARS}:${PROD_DIR}/lib/imidentity.jar:${LDAPJDK_JARS}:/etc/opt/SUNWam/config
JAVA_CMD="${JAVA_HOME}/bin/java -Xms64m -Xmx256m -classpath ${JAVA_CLASSPATH}"

if [ -z "$LD_LIBRARY_PATH" ] ; then
    LD_LIBRARY_PATH="${MPS_LIB_PATH}"
else 
    LD_LIBRARY_PATH="${MPS_LIB_PATH}:$LD_LIBRARY_PATH"
fi
export LD_LIBRARY_PATH


# get credentials for the directory administrator (sets ADMIN_DN and PASSPHRASE)
FILE=/tmp/imcred.$$
${JAVA_CMD} -D"com.iplanet.coreservices.configpath=/etc/opt/SUNWam/config/ums" com.sun.im.identity.util.GetCred > $FILE || exit ${e_fatal}
. $FILE
$RM $FILE

#DS_DIRMGR_PASSWORD=`echo $DS_DIRMGR_PASSWORD | sed -e s/\"\'\"/__APOSTROPHE__/g | sed -e s/\'//g | sed -e s/__APOSTROPHE__/\'/g`
#PASSPHRASE=`echo $PASSPHRASE | sed -e s/\"\'\"/__APOSTROPHE__/g | sed -e s/\'//g | sed -e s/__APOSTROPHE__/\'/g`


AMADMIN="${AM_BASEDIR}/SUNWam/bin/amadmin"

ROOT_DN=`$GREP "^com.iplanet.am.rootsuffix=" $PROP_FILE | $SED -e "s/com.iplanet.am.rootsuffix=//"`
ORG_DN=`$GREP "^com.iplanet.am.defaultOrg=" $PROP_FILE | $SED -e "s/com.iplanet.am.defaultOrg=//"`

if [ "$ORG_DN" != "$ROOT_DN" ]; then
  ORG_DN="$ORG_DN,$ROOT_DN"
fi
SCHEMA_DN="cn=schema"

# check if sunIM and sunPresence service exist and registered already
SERVICE_EXIST=0;
echo "Checking for IM and Presence Services..."
FILE="/tmp/im_check.xml"
RESULT_FILE="/tmp/im_checkResult"
echo "Generating $FILE ."
$RM -f $FILE
$RM -f $RESULT_FILE
$SED -e "s/ORG_DN/${ORG_DN}/g" ${PROD_DIR}/lib/imServiceCheckTemplate.xml > $FILE
$AMADMIN --runasdn "$ADMIN_DN" --password "${PASSPHRASE}" --data $FILE > $RESULT_FILE
$EGREP "SunIM$|SunPresence$" $RESULT_FILE
if [ $? -eq 0 ]; then
  SERVICE_EXIST=1;
fi
echo "Done."
echo
  

# remove SunIM and SunPresence services
if [ $SERVICE_EXIST -eq 1 ]; then

  echo "Removing SunIM and SunPresence Services..."
  $AMADMIN --runasdn "$ADMIN_DN" --password "${PASSPHRASE}" --deleteservice SunIM SunPresence 
  EC=$?
  if [ $EC -ne 0 ] ; then
    echo "Failed to remove services - error $EC"
    #exit $EC
  else
    echo "Success."
  fi
  echo

fi

# do some aditional cleanup just in case
#$LDAPDELETE -h ${DS_HOST} -p ${DS_PORT} -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" ou=1.0,ou=SunPresence,ou=services,o=internet
#$LDAPDELETE -h ${DS_HOST} -p ${DS_PORT} -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" ou=1.0,ou=SunIM,ou=services,o=internet
#$LDAPDELETE -h ${DS_HOST} -p ${DS_PORT} -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" ou=SunPresence,ou=services,o=internet
#$LDAPDELETE -h ${DS_HOST} -p ${DS_PORT} -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" ou=SunIM,ou=services,o=internet

# remove sunIM and sunPresence object classes.
echo "Removing existing IM and Presence services LDAP schema ..."
${JAVA_CMD} com.sun.im.identity.util.RemoveObjectClass -a -O ${IM_OC_OID} -h ${DS_HOST} -p ${DS_PORT} -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" -b "$SCHEMA_DN" 
${JAVA_CMD} com.sun.im.identity.util.RemoveObjectClass -a -O ${PRESENCE_OC_OID} -h ${DS_HOST} -p ${DS_PORT} -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" -b "$SCHEMA_DN" 
EC=$?
if [ $EC -ne 0 ] ; then
  echo "Failed to remove existing IM and Presence LDAP schema - error $EC"
  exit $EC
else
  echo "Success."
fi
echo

# add service ldap schema
echo "Adding IM and Presence services LDAP schema ..."
$LDAPMODIFY ${LDAP_OSFLAGS} -h ${DS_HOST} -p ${DS_PORT} -D "${DS_DIRMGR_DN}" -w "${DS_DIRMGR_PASSWORD}" -f ${PROD_DIR}/lib/imService.ldif
EC=$?
if [ $EC -ne 0 ] ; then
  echo "Failed to add IM and presence schema - error $EC"
  exit $EC
else
  echo "IM and Presence services LDAP schema added successfully."
fi
echo

echo "Importing IM and Presence Services Identity Server Schema..."
AMADMIN_OUTFILE="/tmp/im-amadmin.log"
$AMADMIN --runasdn "$ADMIN_DN" --password "${PASSPHRASE}" --schema ${PROD_DIR}/lib/imService.xml > $AMADMIN_OUTFILE 2>&1
EC=$?
if [ $EC -ne 0 ] ; then
  grep 'Service already exists' $AMADMIN_OUTFILE > /dev/null 2>&1
  if [ $? -ne 0 ]; then
    echo "Failed to import IM and presence schema - error $EC"
    rm $AMADMIN_OUTFILE
    exit $EC
  else
    echo "Service already exists."
  fi
else
  echo "Success."
fi
rm $AMADMIN_OUTFILE
echo

if [ $SERVICE_EXIST -eq 0 ]; then
  echo "Adding IM and Presence requests..."
  FILE="/tmp/im_requests.xml"
  echo "Generating $FILE ."
  $RM -f $FILE
  $SED -e "s/ORG_DN/${ORG_DN}/g" ${PROD_DIR}/lib/imServiceRequestTemplate.xml > $FILE
  echo "Importing $FILE to Identity Server."
  $AMADMIN --runasdn "$ADMIN_DN" --password "${PASSPHRASE}" --data $FILE
  if [ $EC -ne 0 ] ; then
    echo "Failed to add IM and presence data - error $EC"
  else
    echo "Success."
  fi
  echo
fi

echo "Copying property file to ${AM_BASEDIR}/SUNWam/locale ..."
$CP ${PROD_DIR}/lib/imService.properties ${AM_BASEDIR}/SUNWam/locale
$CP ${PROD_DIR}/lib/imService_*.properties ${AM_BASEDIR}/SUNWam/locale
$CP ${PROD_DIR}/lib/imService.properties ${AM_BASEDIR}/SUNWam/locale/imService_en.properties
echo "Done."
echo

if [ "${ASSIGN_SERVICE}" = "y" ]; then
  echo "Assigning IM and Presence services to existing users ..."
  PEOPLE_DN="ou=People,$ORG_DN"
  AssignService
  echo "Done."
  echo
fi

grep -v DS_DIRMGR_PASSWORD PASSFILE > PASSFILE.tmp
mv PASSFILE.tmp PASSFILE
chmod 600 PASSFILE

EC=${e_ok}

exit ${EC}
