#!/bin/ksh
#
# ident "@(#)M10SunDS.ksh	1.30 02/11/26 SMI"
#
# Copyright 2001-2002 Sun Microsystems, Inc.  All rights reserved.
#

#
# MODULE NAME: SunDS
# AUTHOR     :
# DESCRIPTION: SunDS is now obsolete.  This module will only handle preserve
#	the SunDS data and remove the SunDS service
#
# The following exported variables (initialized by the master task) are 
# available (read-only) for the module:
#
# G_PROGRAM_ID    : program name
# G_MEDIA_DIR     : pathname of the install directory on the media (CD,...)
# G_PRODUCT_DIR   : pathname of the bundles directory on the media (CD,...)
# G_ADMIN_FILE    : pathname of the admin file used by pkgadd. default provided.
# G_DEBUG         : debug on/off. Possible values "yes", "no"
# G_QUICK_INSTALL : used to force a quick install (no user inputs).
#                   possible values "yes", "no"
# G_TMP_DIR       : pathname of the temporary directory 
# G_UT_PROD_NAME  : product name
# G_UT_VERSION    : product version
# G_DAEMON_LOC    : location of OS daemon scripts
# G_LOGFILE       : pathname of the log file.
# G_PID           : PID of the master task
#

#
# SunDSVersion()
#
# Description:
#    Check if version number of the SunDS currently installed matches the
#    version number required.
#
# Parameters:
#    $1 - version number
#
# Globals used:
#    (none)

SunDSVersion() {
  SDS_INSTALLED_VER="$(pkgparam SUNWsds VERSION 2>&-)"

  case "$SDS_INSTALLED_VER" in
    $1) return 0;;
    *)  return 1;;
  esac
}


#
# check_nonSR_data
#
# Description:
#    Check to see if there are any non-SunRay data in the SunDS database.
#    Anything that is not under the o=utdata subtree is considered non-SunRay
#    Data.
#    Name of the non-SunRay subtrees will be stored in the FOUND_NONSR_DATA
#    variable.
#
check_nonSR_data() {
    typeset NAMINGCONTEXT=$(ldapsearch -b "" -s base "objectclass=*" namingcontexts) 
    typeset BASE
    typeset NAMES
    typeset search_st
    typeset ANY

    #
    # The following subtrees are defined in the dsserv.conf file by default.
    # These are just sample subtrees.  We check if there are any data under these
    # subtrees before ignoring them.
    # For other subtrees not listed here, we just assume that they contain non-SunRay
    # data and no need to check for data under them.
    #
    DUMMY_SUBTREES="o=XYZ,c=US dc=XYZ,dc=COM"
 
    for NAMES in $NAMINGCONTEXT
    do
        BASE=${NAMES#*=}
        if [[ "$BASE" = "o=utdata" ]]; then
                # skip sunray data
                continue
        fi
	search_st=0
	for dummy in $DUMMY_SUBTREES
	do
	    if [[ "$BASE" = "$dummy" ]]; then
		#
		# also need to capture the output because ldapsearch returns status
		# code of 0 if the subtree exists regardless if empty or not.
		#
		# NOTE: head -2 to deal with the case the first line is blank.
		# we need only to know if there is anything under the subtree.
		#
		ANY=$(ldapsearch -b "$BASE" -s one "objectclass=*" dn 2>&- | head -2)
		search_st=$?
		if [[ $search_st -eq 0 ]]; then
		    # subtree exists, check if empty
		    [[ -z "$ANY" ]] && search_st=1
		fi
		break
	    fi
	done
	if [[ $search_st -eq 0 ]]; then
	    # data found under the subtree, save the subtree name
	    FOUND_NONSR_DATA="${FOUND_NONSR_DATA}\t${BASE}\n"
	fi
    done 
}

#
# PreserveSunDSData
#
# Description:
#    Check to see if we need to preserver/restore the SunDS data.
#    1. check if SRDS is already installed.  If so, we assume that the SunDS
#	left on the system is a private installation and/or contains private
#	data.  We should not preserve/restore its data.
#    2. check if LDAP has been configured for Sun Ray.
#
PreserveSunDSData() {

   if ProductInstalled $SRDS_PKG_LIST || \
	 ProductPartiallyInstalled $SRDS_PKG_LIST; then
      return 1
   fi

#
# Check if LDAP has been configured for Sun Ray
#
   if [[ ! -f ${UT_ETC_DIR}/utadmin.conf ]]; then
	return 1
   fi
   return 0
}

#
# UninstallSunDS()
#
# Description:
#    Unistall SunDS product
#
# Parameters:
#    (none)
#
# Globals used:
#    G_ADMIN_FILE

UninstallSunDS() {
   RemoveMsg "$SDS_PROD_NAME" "$SDS_VERSION"
   RemoveProduct $G_ADMIN_FILE $SDS_PKG_LIST
 
   return $?
}

#
# SDS_Preinstall()
#
# Description:
#    Pre-install procedure.  SunDS is no longer installed.  It will just
#    check for it's existance so that we can remove it.
#
# Parameters:
#    (none)
#
# Globals used:
#    G_UT_PROD_NAME

SDS_Preinstall() {

   _DO_INSTALL="no"

   if [[ $_SW_INSTALLED = "yes" ]]; then

      ProductMsg -n "$SDS_PROD_NAME $SDS_VERSION"
      print "installed - migrate to SRDS mandatory"
      if PreserveSunDSData; then
         AddPostInitMessage "Migrate\t [ Configuration and Data for $SRDS_PROD_NAME $SRDS_VERSION ]"
      fi

      if [[ $_SW_COMPATIBLE = "no" ]]; then
         fmt <<-!

	A different version ($SDS_INSTALLED_VER) of $SDS_PROD_NAME has been
	detected. The $G_UT_PROD_NAME Software is only compatible with
	$SDS_PROD_NAME $SDS_VERSION. You must either upgrade or remove the
	current $SDS_PROD_NAME installation before proceeding.

	Exiting...
	!
         return 2
      else
	fmt <<-!

	An installation of $SDS_PROD_NAME has been detected.

	Previous releases of $G_UT_PROD_NAME software have included this product as
	a data store for Sun Ray data. However this product is no longer
	required for that purpose and should be removed if it is not a private
	installation being utilised for a non $G_UT_PROD_NAME purpose.

	!
	# check to see if there is any non-Sunray data in the current SunDS database
	check_nonSR_data
	if [[ -n "$FOUND_NONSR_DATA" ]]; then
	    fmt <<-!
		Non-SunRay data was detected in the $SDS_PROD_NAME database under the
		following subtrees:
		!
		print $FOUND_NONSR_DATA
		fmt <<-!
		If you choose to remove the $SDS_PROD_NAME product, all the non-SunRay
		data will be removed.  If you need to save this data, you can either
		choose not to remove the $SDS_PROD_NAME or abort this upgrade and backup
		the data before rerunning the installation program.

		!
	    if ! YesOrNo "Do you want to continue" "Y"
	    then
		return 2
	    fi
	    print ""
	fi

	if YesOrNo "Do you want to remove $SDS_PROD_NAME" "Y"
	then
	    print ""
	    _DO_REMOVE="yes"
	    if [[ -n "$FOUND_NONSR_DATA" ]]; then
		AddPostInitMessage "Remove\t [ $SDS_PROD_NAME $SDS_VERSION including non-SunRay data ]"
	    else
		AddPostInitMessage "Remove\t [ $SDS_PROD_NAME $SDS_VERSION ]"
	    fi
	else
	    _SDS_CONF_SAVED_FILENAME="${LDAP_ETC_CURR_DIR}/dsserv.conf_saved_`date '+%y%m%d_%H:%S'`"
	    print "\n*****************************************************************"
	    fmt <<-!
		NOTE:

		You chose to keep the $SDS_PROD_NAME product on this server.
		While the SunRay servers within the failover group are being upgraded,
		you cannot start the $SDS_PROD_NAME.  Otherwise, there will be
		a port conflict between the $SDS_PROD_NAME and the $SRDS_PROD_NAME.
		You must transition the port number for $SRDS_PROD_NAME to the new
		default port after all the servers within the failover group have
		been upgraded before restarting the $SDS_PROD_NAME.  Please refer to
		the documentation on how to convert to the new default port.

		The $SDS_PROD_NAME configuration file will be renamed to
		$_SDS_CONF_SAVED_FILENAME.  You will need to rename this 
		configuration file back in order to start up the $SDS_PROD_NAME.

		!
	    print "*****************************************************************\n"
	fi

      fi
   fi
   if [[ $G_DEBUG = "yes" ]]; then
	echo "SDS_Preinstall:"
	echo "_DO_INSTALL=${_DO_INSTALL}"
	echo "_DO_REMOVE=${_DO_REMOVE}"
   fi
   return 0
}

#
# SDS_Preremove()
#
# Description:
#    Pre-remove procedure: ask whether Sun Directory Service has to be removed
#
# Parameters:
#    (none)
#
# Globals used:
#    (none)

SDS_Preremove() {

   _DO_REMOVE="no"

   if [[ $_SW_INSTALLED = "yes" && $_SW_COMPATIBLE = "yes" ]]; then
      if YesOrNo "Remove $SDS_PROD_NAME $SDS_VERSION" "Y"; then
         _DO_REMOVE="yes"
         AddPostInitMessage "Remove\t [ $SDS_PROD_NAME $SDS_VERSION ]"
      fi
   fi

   return 0
}

#
# DataConvert
#
# Description:
#    converts the SunDS Preserved file to SRDS format.
#
# NOTE: it's unfortunate that this conversion routine cannot be
# dynamic.  In other words, every time we add new file or directory into
# the backup file or directory list in the parameters SDS_PRESERVE_FILES
# or SDS_PRESERVE_DIRS specified at the end of the script, you must
# manually add the conversion routine to handle the new data.
#
DataConvert() {

    WLDAPDIR=/usr/tmp/LDAP_DIRS.$$
    WSRDSDIR=/usr/tmp/SRDS_DIRS.$$
    TMPFILE=${UT_VAR_DIR}/${_MODULE_NAME}.$$

    # restore LDAP_DIRS into a temporary location
    RestoreDirIn $WLDAPDIR LDAP_DIRS
    if [[ $? != 0 ]]; then
	return 2
    fi

    if [[ $G_DEBUG = "yes" ]]; then
	set -x
    fi

    #
    # convert files in etc/opt/SUNWconn/ldap/current directory
    #
    DSTDIR=$WSRDSDIR/etc/opt/SUNWut/srds/current
    mkdir -p $DSTDIR
    CURDIR=$WLDAPDIR/etc/opt/SUNWconn/ldap/current

    [[ -f ${CURDIR}/dsserv.acl.conf ]] && \
    	cp -p ${CURDIR}/dsserv.acl.conf ${DSTDIR}/utdsd.acl.conf
    [[ -f ${CURDIR}/dsserv.at.ut.conf ]] && \
    	cp -p ${CURDIR}/dsserv.at.ut.conf ${DSTDIR}/utdsd.at.ut.conf
    [[ -f ${CURDIR}/dsserv.oc.ut.conf ]] && \
    	cp -p ${CURDIR}/dsserv.oc.ut.conf ${DSTDIR}/utdsd.oc.ut.conf

    #
    # dsserv.ini conversion
    #
    typeset OLDPORT=$(grep "^LdapPort=" ${CURDIR}/dsserv.ini)
    typeset OLDPUSH=$(grep "^StartDspushd=" ${CURDIR}/dsserv.ini)
    sed -e "s/^LdapPort=7012/${OLDPORT}/" \
	-e "s/^StartDspushd=false/${OLDPUSH}/" \
	${UT_ETC_DIR}/srds/default/utdsd.ini > ${DSTDIR}/utdsd.ini

    #
    # dsserv.conf conversion
    #
    cp -p ${UT_ETC_DIR}/srds/default/utdsd.conf ${DSTDIR}/utdsd.conf
    sed -n -e "/^# SUNWut begin/,/^# SUNWut end/p" \
	${CURDIR}/dsserv.conf > ${TMPFILE}
    OLDSUFFIX=$(grep "^suffix *" ${TMPFILE})
    OLDROOTDN=$(grep "^rootdn *" ${TMPFILE})
    OLDROOTPW=$(grep "^rootpw *" ${TMPFILE})
    /bin/rm ${TMPFILE} 2> /dev/null
    sed -e "s/^suffix .*$/${OLDSUFFIX}/" \
	-e "s/^rootdn .*/${OLDROOTDN}/" \
	-e "s/^rootpw .*/${OLDROOTPW}/" \
	${OPT_DIR}/etc/template/ldap/utdsd.conf >> ${DSTDIR}/utdsd.conf
    sed -n -e "/^# SUNWutrep begin/,/^# SUNWutrep end/p" \
	${CURDIR}/dsserv.conf >> ${DSTDIR}/utdsd.conf

    #
    # convert files in var/opt/SUNWconn/ldap directory
    #
    DSTDIR=$WSRDSDIR/var/opt/SUNWut/srds
    mkdir -p $DSTDIR
    CURDIR=$WLDAPDIR/var/opt/SUNWconn/ldap

    # dbm.ut datastore
    [[ -d ${CURDIR}/dbm.ut ]] && \
    	cp -p -r ${CURDIR}/dbm.ut $DSTDIR

    # replog files
    DSTREPLOG=${DSTDIR}/replog
    mkdir -p ${DSTREPLOG}
    CURDIR=$WLDAPDIR/var/opt/SUNWconn/ldap/replog
    [[ -f ${CURDIR}/dspushd.replog ]] && \
	cp -p ${CURDIR}/dspushd.replog ${DSTREPLOG}/utpushd.replog
    [[ -f ${CURDIR}/dspulld.replog ]] \
	&& cp -p ${CURDIR}/dspulld.replog ${DSTREPLOG}/utpulld.replog
    [[ -f ${CURDIR}/dspushd.status ]] \
	&& cp -p ${CURDIR}/dspushd.status ${DSTREPLOG}/utpushd.status
    [[ -f ${CURDIR}/dspulld.status ]] \
	&& cp -p ${CURDIR}/dspulld.status ${DSTREPLOG}/utpulld.status
    cp -p ${CURDIR}/*.rej ${DSTREPLOG} 2> /dev/null

    # log files
    DSTLOG=${DSTDIR}/log
    mkdir -p ${DSTLOG}
    CURDIR=$WLDAPDIR/var/opt/SUNWconn/ldap/log
    [[ -f ${CURDIR}/dsserv.replog ]] && \
    	cp -p ${CURDIR}/dsserv.replog ${DSTLOG}/utdsd.replog

    #
    # convert files in /var/opt/SUNWut dierctory
    #
    # preferences file
    DSTDIR=${WSRDSDIR}/var/opt/SUNWut
    CURDIR=${WLDAPDIR}/var/opt/SUNWut
    [[ -d ${CURDIR}/preferences ]] && \
	cp -p -r ${CURDIR}/preferences $DSTDIR

    #
    # re-create the SRDS tar file
    #
    cp -p /usr/sbin/static/tar $WSRDSDIR
    if ! chroot $WSRDSDIR tar -cf SRDS_DIRS.tar /etc /var; then
    	/bin/rm -rf $WSRDSDIR 2> /dev/null
	return 1
    fi
    if ! compress -f ${WSRDSDIR}/SRDS_DIRS.tar; then
    	/bin/rm -rf $WSRDSDIR 2> /dev/null
	return 1
    fi

    #
    # create the new SRDS preserve directory
    #
    PREDIR=${G_UPGRADE_DIR}/preserve/M11SRDS
    mkdir -p ${PREDIR}
    mv ${WSRDSDIR}/SRDS_DIRS.tar.Z ${PREDIR}
    mkdir -p ${PREDIR}${UT_ETC_DIR}
    mkdir -p ${PREDIR}${UT_VAR_DIR}
    for file in $SDS_PRESERVE_FILES; do
	if GetPreservedFilePath "$file"; then
	    preservedfile=${_RETURN_VAL}
	    cp -p "$preservedfile" "${PREDIR}${file}"
	fi
    done

    #
    # cleanup
    #
    /bin/rm -rf $WLDAPDIR $WSRDSDIR 2> /dev/null

    return 0
}


#
# Parameter
#
# Module developers to provide the following functions:
# Module_Init, Module_Preserve, Module_Remove, Module_Install, Module_Restore
# Module_Abort, Module_Exit
#

#
# Module_Init()
#
# Description:
#   initialization of the module for installation, uninstallation
#
# Parameters:
#   (none)
#
# Globals used:
#

Module_Init() {

   exit_no=0

#
# Check if SRDS is already installed.  If so, we assume that the SunDS left
# on the system is a private installation and/or contains private data.  We
# should not remove it.
#
   if ! ProductInstalled SUNWuto || \
	 ProductInstalled $SRDS_PKG_LIST || \
	 ProductPartiallyInstalled $SRDS_PKG_LIST; then
      return 0
   fi

#
# Check if SunDS is already installed. If so, check if that version is 
# compatible with Sunray
#
   if ProductInstalled $SDS_PKG_LIST && SunDSVersion $SDS_VERSION && \
      ! ProductPartiallyInstalled $SDS_PKG_LIST; then

      _SW_INSTALLED="yes"
      _SW_COMPATIBLE="yes"

   elif ProductInstalled $SDS_PKG_LIST && ! SunDSVersion $SDS_VERSION; then

      _SW_INSTALLED="yes"
      _SW_COMPATIBLE="no"

   fi

   if IsInstallRequired; then

      SDS_Preinstall
      exit_no=$?

   elif IsUninstallRequired; then

      SDS_Preremove
      exit_no=$?

   elif IsPreserveRequired; then
      if PreserveSunDSData; then
         AddPostInitMessage "Preserve [ Sun Ray datastore for $SDS_PROD_NAME $SDS_VERSION ]"
      fi   

   fi

   return $exit_no
}

#
# Module_Preserve()
#
# Description: preserve the SunDS data.
#   
#
# Parameters:
#   (none)
#
# Globals used:
#

Module_Preserve() {

   if ! PreserveSunDSData; then
      return 0
   fi

#
# Save files
#
  SaveFiles $SDS_PRESERVE_FILES
  if [[ $? != "0" ]]; then
     return 2
  fi
 
  SaveDirectory LDAP_DIRS $SDS_PRESERVE_DIRS
  if [[ $? != "0" ]]; then
     return 2
  fi

  #
  # Check to see if the _SDS_CONF_SAVED_FILENAME is defined.  If defined,
  # this means that the administrator decided to keep the SunDS package.
  # In this case, we need to remove the all SunRay related entries in the
  # SunDS configuration files and remove all SunRay files including the
  # SunRay database.
  #
  if [[ -z "$_SDS_CONF_SAVED_FILENAME" ]]; then
     return 0
  fi

  typeset -r EDIT_FILES="dsserv.acl.conf dsserv.at.conf dsserv.oc.conf dsserv.conf"
  typeset -r DELETE_FILES="dsserv.at.ut.conf dsserv.oc.ut.conf"
  typeset File
  typeset TmpFile=${UT_VAR_DIR}/${_MODULE_NAME}.$$
  /bin/rm -f $TmpFile

  #
  # remove SunRay related entries from the configuration files
  #
  for File in $EDIT_FILES
  do
	sed -e '/^# SUNWut begin/,/^# SUNWut end/d' \
	    -e '/^# SUNWutrep begin/,/^# SUNWutrep end/d' \
	    ${LDAP_ETC_CURR_DIR}/${File} > $TmpFile
	cat $TmpFile > ${LDAP_ETC_CURR_DIR}/${File}
	rm $TmpFile
  done
  #
  # remove the SunRay related configuration files
  #
  for File in $DELETE_FILES
  do
	/bin/rm -f ${LDAP_ETC_CURR_DIR}/${File}
  done
  #
  # rename the dsserv.conf configuration file
  #
  mv ${LDAP_ETC_CURR_DIR}/dsserv.conf $_SDS_CONF_SAVED_FILENAME
  #
  # remove the SunRay database
  #
  /bin/rm -rf ${LDAP_VAR_DIR}/ldap/dbm.ut
  return 0
}

#
# Module_Remove()
#
# Description:
#    Remove SunDS
#
# Parameters:
#   (none)
#
# Globals used:
#

Module_Remove() {

   UninstallSunDS

   #
   # need to manually remove the database because preremove script does not
   # remove it
   #
   /bin/rm -fr ${LDAP_ETC_DIR}/ldap 2> /dev/null
   /bin/rm -fr ${LDAP_VAR_DIR}/ldap 2> /dev/null
   /bin/rm -f /etc/opt/licenses/sunds.lic,* 2> /dev/null

   return $?
}

#
# Module_Install()
#
# Description:
#    SunDS is now obsolete.  We will no longer install the SunDS.  It's now
#    replaced by SRDS.  See M11SRDS module.
#
# Parameters:
#   (none)
#
# Globals used:
#

Module_Install() {

   return 0
}

#
# Module_Restore()
#
# Description:
#    SunDS is now obsolete.  If SunDS preserved data is found, we need to
#    convert to the new SRDS format.  This routine will be used to the 
#    conversion.
#
# Parameters:
#   (none)
#
# Globals used:
#

Module_Restore() {

   #
   # check if the SunDS data is preserved.
   #
   if ! IsModuleDataPreserved; then
	return 0
   fi
   echo "Converting SunDS configuration/data to SRDS configuration/data."
   # convert the data to SRDS format
   DataConvert
   if [[ $? != 0 ]]; then
	return 2
   fi

   return 0

}

#
# Module_Abort()
#
# Description:
#    Abort procedure
#
# Parameters:
#   (none)
#
# Globals used:
#

Module_Abort() {

   return 0

}

#
# Module_Exit()
#
# Description:
#    Exit procedure (normal termination)
#
# Parameters:
#   (none)
#
# Globals used:
#

Module_Exit() {

   return 0

}

#
# END
#

#
# MAIN STARTS HERE
#

trap "exit 2" HUP INT QUIT TERM

#
# include libraries
#

. ${G_MEDIA_DIR}/support_lib/iu_lib
. ${G_MEDIA_DIR}/support_lib/module_lib
. ${G_MEDIA_DIR}/support_lib/upgrade_lib

export _EVENT=$1
export _MODULE_NAME=$(basename $0)
export _VARS_LIST=""
export _EXIT_CODE=0
export _RETURN_VAL=0
export _VAR_STORAGE_FILE="${G_TMP_DIR}/.${G_PROGRAM_ID}.${_MODULE_NAME#???}"

DeclareModuleVar _DO_INSTALL="no"
DeclareModuleVar _DO_REMOVE="no"
DeclareModuleVar _SW_INSTALLED="no"
DeclareModuleVar _SW_COMPATIBLE="yes"
DeclareModuleVar _SAVE_CONF_FILE="false"

DeclareModuleVar _SDS_CONF_SAVED_FILENAME=""

#
# BEGIN: Developers module variables definition here
#

DeclareModuleVar SDS_INSTALLED_VER

export SDS_PROD_NAME="Sun Directory Service"
export SDS_VERSION="3.1"
export SRDS_PROD_NAME="Sun Ray Data Store"
export SRDS_VERSION="1.0"
export SDS_PKG_LIST="SUNWsds SUNWsdsc"
export SRDS_PKG_LIST="SUNWutdso"

export OPT_DIR="/opt/SUNWut"
export UT_VAR_DIR="/var/opt/SUNWut"
export UT_ETC_DIR="/etc/opt/SUNWut"
export LDAP_VAR_DIR="/var/opt/SUNWconn"
export LDAP_ETC_DIR="/etc/opt/SUNWconn"
export LDAP_ETC_CURR_DIR="${LDAP_ETC_DIR}/ldap/current"

export SDS_PRESERVE_DIRS="${UT_VAR_DIR}/preferences \
                          ${LDAP_ETC_CURR_DIR} \
                          ${LDAP_VAR_DIR}/ldap/dbm.ut \
                          ${LDAP_VAR_DIR}/ldap/replog/dspushd.replog \
                          ${LDAP_VAR_DIR}/ldap/replog/dspulld.replog \
                          ${LDAP_VAR_DIR}/ldap/replog/dspushd.status \
                          ${LDAP_VAR_DIR}/ldap/replog/dspulld.status \
                          ${LDAP_VAR_DIR}/ldap/replog/*.rej \
                          ${LDAP_VAR_DIR}/ldap/log/dsserv.replog \
                         "

export SDS_PRESERVE_FILES="/etc/opt/SUNWut/utadmin.pw \
                           ${UT_ETC_DIR}/utadmin.conf \
                           ${UT_VAR_DIR}/log/admin_log \
                          "
FOUND_NONSR_DATA=""
#
# END
#

#
# FRAMEWORK CODE 
#

. ${G_MEDIA_DIR}/support_lib/framework_lib
