#!/bin/sh
#
# Copyright 2001-2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# directoryserver S1DS52
#
#ident	"@(#)$RCSfile: directoryserver,v $	$Revision: 1.1.6.7 $ - $Date: 2004/03/31 14:11:32 $"

sync_cds_usage () {
	echo "Usage: ${DSCMD}"
	echo "	   sync-cds [5.2] [-f {absolute path of credential's file}] [-l {logfile absolute path}]"
}

#########################################
# getBuildNumber52
#
# set buildNumber52 variable
# on sparc:
# RTM 5.2 buildNumber: 2003.143.0020 
# OR1 5.2 buildNumber: unchanged (i-e: 2003.143.0020)
#
# on i386:
# RTM 5.2 buildNumber: 2003.143.0143
# OR1 5.2 buildNumber: unchanged (i-e : 2003.143.0143)
#
##########################################
getBuildNumber52 () 
{
	buildNumber52=""
	if [ `uname -p` = "sparc" ]; then
		buildNumber52="2003.143.0020"
	else
		if [ `uname -p` = "i386" ]; then
			buildNumber52="2003.143.0143"
		fi
	fi
}


#########################################
# Platform-specific code 
# The following functions must be defined:
#     pkg_print_instances
#     pkg_check_exist
#     pkg_add_basedirs
#     pkg_check_uniq
#     pkg_get_basedir
#     get_j2se_dir
#     init_pkg_check
#     init_uninstall_pkg_check
#     platform_specific_check
#     init
#########################################



#########################################
# pkg_print_instances
#
# $1 pkg name
#
##########################################
pkg_print_instances () {
    pkg=$1
    instances=`pkginfo "${pkg}.*" | awk '{ print $2; }'`
    for n in $instances; do
	revision=`pkginfo -x $n | tail -1 | awk '{ print $2 }'`
	basedir=`pkginfo -r $n`
	echo "$n\n\t$revision\t$basedir"
    done
}

#########################################
# pkg_check_exist() 
#
# Check $1 package is installed
##########################################
pkg_check_exist() {
    num=`pkginfo -r "$1" 2>/dev/null | sort | uniq | wc -l`
    return $num
}

#########################################
# pkg_add_basedirs
#
# Add to $basedirs basedirs of $1.* packages
##########################################
pkg_add_basedirs() {
    instances=`pkginfo "$1.*" | awk '{ print $2; }'`
    for n in $instances; do
	basedir=`pkginfo -r $n`
	if [ -z "$basedirs" ]; then
	    basedirs="$basedir\n"
	else
	    basedirs="$basedirs$basedir\n"
	fi
    done
}

#########################################
# pkg_check_uniq 
##########################################
pkg_check_uniq () {
    pkg=$1
    num=`pkginfo -r "${pkg}.*" 2>/dev/null | wc -l`
    if [ $num -ne 1 ]; then
        echo "WARNING: Package ${pkg} has multiple instances:"
        pkg_print_instances ${pkg}
        echo "WARNING: only ${pkg} is used by Directory Server 5.2"
    fi
}


#########################################
# pkg_get_basedir
##########################################
pkg_get_basedir () {
    pkg=$1
    num=`pkginfo -r "${pkg}" 2>/dev/null | sort | uniq | wc -l`
    if [ $num -eq 0 ]; then
#		echo "ERROR: The following package is not installed: ${pkg}"
		return 1
    fi
    BASEDIR=`pkginfo -r "${pkg}" | head -1`
    return 0
}

#########################################
# get_j2se_dir 
#
# Set J2SE_DIR
##########################################
get_j2se_dir() {
    if [ $IS_ORION_J2SE -eq 0 ] ; then
	pkg_get_basedir SUNWj3rt	
	J2SE_DIR="${BASEDIR}/j2se"
    else
	J2SE_DIR=${ORION_J2SE_DIR}
    fi
}

#########################################
# init_pkg_check 
#
# Initialize pkgs to check at any time 
# except uninstall
##########################################
init_pkg_check () {    

	# those packages need to have the same basedir
    PKG_32BIT="
	SUNWasvu 
	SUNWdsvcp 
	SUNWdsvpl 
	SUNWdsvu 
    "
    # heap allocator packages only on S8
    if [ `uname -r` = "5.8" ]; then
	PKG_32BIT="${PKG_32BIT} SUNWdsvh"
    fi

	# those packages are not enforced to have the same basedir
    if [ $IS_ORION_J2SE -eq 0 ] ; then
	pkg_32extra="SUNWzlib
	SUNWicu
	SUNWpr 
	SUNWtls 
	SUNWsasl
	SUNWldk
	SUNWjss
	SUNWj3rt
	SUNWdsvr 
	"
    else
	pkg_32extra="SUNWzlib
	SUNWicu
	SUNWpr 
	SUNWtls 
	SUNWsasl
	SUNWldk
	SUNWjss
	SUNWdsvr 
	"
    fi
	
	# to know if we check for 64 bits packages, just check
	# the presence of SUNWdsvx
    USE_64=0
    PKG_64BIT=""
    pkg_64extra=""
	if [ -n "`isainfo -v|grep 64-bit`" ]
	then
		pkginfo -r "SUNWdsvx" >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			USE_64=1
			PKG_64BIT="
			SUNWdsvx 
			"

			# heap allocator packages only on S8
			if [ `uname -r` = "5.8" ]; then
			PKG_64BIT="${PKG_64BIT} SUNWdsvhx"
			fi

			# those packages are not enforced to have the same basedir
			if [ `uname -r` != "5.10" ]; then
				pkg_64extra="SUNWzlibx
					SUNWicux
					SUNWprx 
					SUNWtlsx
					SUNWsaslx
					SUNWldkx
					"
			fi
			# SUNWgssx package is required for solaris 8 and 9
			if [ `uname -r` = "5.8" ] || [ `uname -r` = "5.9" ]; then
				pkg_64extra="${pkg_64extra} SUNWgssx"
			fi
		fi
	fi
}

#########################################
# init_uninstall_pkg_check
#
# Initialize pkgs to check at unsinstall
##########################################
init_uninstall_pkg_check() {
    PKG_32BIT="
            SUNWdsvu
        "
    pkg_32extra=""
    if [ $IS_ORION_J2SE -eq 0 ] ; then
	pkg_32extra=$pkg_32extra"
            SUNWj3rt
        "
    fi
    USE_64=0
    PKG_64BIT=""
    pkg_64extra=""
}


#########################################
# pkg_check_sasl (Solaris specific)
##########################################
pkg_check_sasl () {

	if [ `uname -r` = "5.8" ]; then

		if  [ `uname -p` = "sparc" ]; then
			min_patch=115328-01
		else
			min_patch=115329-01
		fi
	elif [ `uname -r` = "5.9" ]; then
			if  [ `uname -p` = "sparc" ]; then
				min_patch=115342-01
			else
				min_patch=115343-01
			fi
	else # S10
		return 0
	fi

	pkg="SUNWsasl"
	current_patch=`showrev -p|grep $pkg|awk '{ print $2; }'`
	if [ "x$current_patch" != x ]; then
		security_check_ret=`echo "$current_patch $min_patch" | awk '{ if ( $1 >= $2 ) print 0 ; else print 1;}'`
		if [ $security_check_ret -eq 1 ]; then
			echo "ERROR: Need package $pkg $version with minimum patch $min_patch"
			return 1
		fi
	fi

	return 0
}

#########################################
# security_check_all (Solaris specific)
#
# check that security packages are
# the correct ones
#
# need nss(x) 332 + patch 11404[5|6]-02
# need tls(x) 412 + patch 11404[5|6]-02
#
##########################################
security_check_all () {

    security_check_all_ret=0;
    min_patch=0

	# minimum version when no patch
	tls_min="3.3.4"
	nspr_min="4.1.4"

    if [ `uname -r` = "5.8" ]; then

        if  [ `uname -p` = "sparc" ]; then
            min_patch=114045-02
            tls="3.3.2"
            nspr="4.1.2"
        else
            min_patch=114046-02
            tls="3.3.3"
            nspr="4.1.3"
        fi
	elif [ `uname -r` = "5.9" ]; then	
			if  [ `uname -p` = "sparc" ]; then
			 	min_patch=114049-02
				tls="3.3.2"
				nspr="4.1.2"
			else
			 	min_patch=114050-02
				tls="3.3.3"
				nspr="4.1.3"
			fi
    else # S10
        tls="3.3.4"
        nspr="4.1.4"
    fi
 
    security_check SUNWtls $tls $min_patch $tls_min
    if [ $? -ne 0 ]; then
        security_check_all_ret=1
    fi

    security_check SUNWpr $nspr $min_patch $nspr_min
    if [ $? -ne 0 ]; then
        security_check_all_ret=1
    fi

	if [ -n "`isainfo -v|grep 64-bit`" ]
	then
		pkginfo -r "SUNWdsvx" >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			if [ `uname -r` != "5.10" ]; then
				security_check SUNWtlsx $tls $min_patch $tls_min
				if [ $? -ne 0 ]; then
					security_check_all_ret=1
				fi
				security_check SUNWprx $nspr $min_patch $nspr_min
				if [ $? -ne 0 ]; then
					security_check_all_ret=1
				fi
			fi
		fi
	fi
    return $security_check_all_ret
}

security_check () {

    pkg=$1
    min_version=$2
    min_patch=$3
    version_nopatch=$4
    security_check_ret=0

    if [ $min_patch -ne 0 ]; then
		security_check_patch $pkg $min_version $min_patch
		if [ $? -eq 1 ]; then
			security_check_version $pkg $version_nopatch
			if [ $? -eq 1 ]; then
				echo "ERROR: Need package $pkg $min_version with minimum patch $min_patch OR $pkg with minimum version $version_nopatch"
				security_check_ret=1
			fi
		fi
    else #S10
		security_check_version $pkg $min_version $min_patch
		if [ $? -eq 1 ]; then
			echo "ERROR: Need package $pkg with minimum revision $min_version"
			security_check_ret=1
		fi
    fi

    return $security_check_ret;
}  
   
#########################################
# security_check_version (Solaris specific)
#########################################

security_check_version ()
{
	pkg=$1
	version=$2

	current_version=`pkginfo -x $pkg | tail -1 | awk '{ print $2 }' | cut -f1 -d','`
	if [ "x$current_version" = x ]; then
		return 1
	fi
	major_current_version=`echo $current_version | cut -f1 -d"."`
	major_version=`echo "$version" | cut -f1 -d"."`

	minor_current_version=`echo "$current_version" | cut -f2 -d"."`
	minor_version=`echo "$version" | cut -f2 -d"."`

	micro_current_version=`echo "$current_version" | cut -f3 -d"."`
	micro_version=`echo "$version" | cut -f3 -d"."`

	if [ "x$major_current_version" = x -o "x$major_current_version" = x ]; then
		return 1
	else
		if [ "$major_current_version" -lt "$major_version" ]; then
			return 1
		fi
	fi

	if [ "x$minor_current_version" = x -o "x$minor_current_version" = x ]; then
		return 1
	else
		if [ "$minor_current_version" -lt "$minor_version" ]; then
			return 1
		fi
	fi

	if [ "x$micro_current_version" = x -a "x$micro_current_version" = x ]; then
		return 0
	elif [ "x$micro_current_version" = x -a "x$micro_current_version" != x ]; then
		return 1
	elif [ "x$micro_current_version" != x -a "x$micro_current_version" = x ]; then
		return 0
	elif [ "x$micro_current_version" != x -a "x$micro_current_version" != x ]; then
		if [ "$micro_current_version" -lt "$micro_version" ]; then
			return 1
		fi
	fi

	return 0
}

#########################################
# security_check_patch (Solaris specific)
#########################################
security_check_patch ()
{
    pkg=$1
    version=$2
    min_patch=$3
    security_check_ret=0

	pkginfo -x $pkg | tail -1 | awk '{ print $2 }' | cut -f1 -d','|grep -w $version >/dev/null
	if [ $? -ne 0 ]; then
		return 1
	fi

	current_patch=`showrev -p|grep $pkg|awk '{ print $2; }'`
	if [ "x$current_patch" != x ]; then
			for i in `echo $current_patch`
			do
				security_check_ret=`echo "$i $min_patch" | awk '{ if ( $1 >= $2 ) print 0 ; else print 1;}'`
				if [ $security_check_ret -eq 0 ]; then
					break
				fi
			done
			if [ $security_check_ret -eq 1 ]; then
					return 1
			fi
	else
		return 1
	fi
	return 0
}

#########################################
# platform_specific_check
#
# Perform specific checks
##########################################
platform_specific_check() {
    res=0
# Checks are now performed by Orion installer
#    pkg_check_sasl
#    if [ $? -eq 0 ] ; then
#	res=1
#    fi
#    security_check_all
#    if [ $? -eq 0 ] ; then
#	res=1
#    fi
    return $res
}

#########################################
# clean_ha
#
# in HA context, if first node has been unconfigured successfully, 
# still need to do some clean up on the second node
##########################################
clean_ha() {

    FAIL=0
    if [ ! -f $MPS_SR/setup/uninstall_Sun_ONE_Directory_Distribution.class -a -f $DS_CONF_DIR/certmap.conf ]; then
	echo "Finishing unconfiguration of Directory Server 5.2 for this cluster node." 
	echo "Removing remaining files...\n"
	if [ ! -f $DS_SETUP_PATH/uninstall_*.class ]; then
		# no more SERVERROOT directory
		# remove local serverroot.conf file
	    unlink $AS_CONF_DIR/$SERVERROOT_CONF_FILE 1> /dev/null 2>&1
	    if [ $? -ne 0 -a $? -ne 255 ]; then
		echo "Cannot remove $AS_CONF_DIR/$SERVERROOT_CONF_FILE. Try manually.\n"
		FAIL=1
	    fi
	fi
	# remove transversal link
	unlink $DS_CONF_DIR/certmap.conf 1> /dev/null 2>&1
	if [ $? -ne 0 -a $? -ne 255 ]; then
	    echo "Cannot remove $DS_CONF_DIR/certmap.conf. Try manually.\n"
	    FAIL=1
	fi
	if [ `uname -r` = "5.8" ]; then  
	    unlink $DSV_USRDIR/nsPerl5.005_03/lib/sun4-solaris 1> /dev/null 2>&1
	    if [ $? -ne 0 -a $? -ne 255 ]; then
		echo "Cannot remove $DSV_USRDIR/nsPerl5.005_03/lib/sun4-solaris. Try manually.\n"
		FAIL=1
	    fi
	else 
	    if  [ `uname -p` = "sparc" ]; then
		unlink $DSV_USRDIR/nsPerl5.006_01/lib/sun4-solaris-64int 1> /dev/null 2>&1
		if [ $? -ne 0 -a $? -ne 255 ]; then
		    echo "Cannot remove $DSV_USRDIR/nsPerl5.006_01/lib/sun4-solaris-64int. Try manually.\n"
		    FAIL=1
		fi
	    else
		unlink $DSV_USRDIR/nsPerl5.006_01/lib/i86pc-solaris-64int 1> /dev/null 2>&1
		if [ $? -ne 0 -a $? -ne 255 ]; then
		    echo "Cannot remove $DSV_USRDIR/nsPerl5.006_01/lib/i86pc-solaris-64int. Try manually.\n"
		    FAIL=1
		fi
	    fi
	fi
    fi
    return $FAIL
}
#########################################
# init
#
#     Must define the following variables
#
#     DS_BASEDIR
#     DSV_USRDIR
#     MPS_SR
#     JAVA_LIBPATH
#     AS_SETUP_PATH
#     DS_SETUP_PATH
#     DS_SETUP_CLASS
#     DS_UNINSTALL_CLASS
#     AS_SBINDIR
#     DS_SBINDIR
#     DS_COMMON_BINDIR
#     WRAPPER
#     JAVA
#
#########################################
init() {
    AS_BASEDIR=/
    pkg_get_basedir SUNWasvu
    AS_BASEDIR=$BASEDIR
    DS_BASEDIR=/
    pkg_get_basedir SUNWdsvu
    DS_BASEDIR=$BASEDIR

    ASV_USRDIR=/usr
    ASV_ETCDIR=/etc/mps/admin/v5.2
    DSV_USRDIR=/usr/ds/v5.2
    WRAPPER=/usr/sbin/directoryserver

    if [ "$AS_BASEDIR" != "/" ]; then
	ASV_USRDIR=${AS_BASEDIR}/${ASV_USRDIR}
	ASV_ETCDIR=${AS_BASEDIR}/${ASV_ETCDIR}
    fi
    if [ "$DS_BASEDIR" != "/" ]; then
	DSV_USRDIR=${DS_BASEDIR}/${DSV_USRDIR}
	WRAPPER=${DS_BASEDIR}${WRAPPER}
    fi

    # Where to find conf files
    AS_CONF_DIR=$ASV_ETCDIR/shared/config
    DEFAULT_SERVERROOT=${DS_BASEDIR}/var/../var/mps/serverroot/
    MPS_SR=$DEFAULT_SERVERROOT
    SERVERROOT_CONF_FILE=serverroot.conf
    if [ -f $AS_CONF_DIR/$SERVERROOT_CONF_FILE ]; then
	MPS_SR=`cat $AS_CONF_DIR/$SERVERROOT_CONF_FILE`
    fi

    # For installer
    JAVA_LIBPATH=$AS_BASEDIR/usr/lib/mps/admin/setup
    AS_SETUP_PATH=$MPS_SR/setup
    DS_SETUP_PATH=$DS_BASEDIR/usr/ds/v5.2/setup/
    DS_SETUP_CLASS=DirectoryServerSetup
    DS_UNINSTALL_CLASS=uninstall_Sun_ONE_Directory_Distribution

    # Where to find shell scripts
    AS_SBINDIR=$ASV_USRDIR/sbin
    DS_SBINDIR=$DSV_USRDIR/sbin

    # Where to find common commands
    DS_COMMON_BINDIR=$DSV_USRDIR/bin/slapd/server

    get_j2se_dir
    JAVA=$J2SE_DIR/bin/java
}


msg_not_configured() {
    pkginfo SUNWscu 1>/dev/null 2>&1
    if [ $? -eq 0 ]
    then
	echo "If Directory Server 5.2 has already been configured, then run the command on the active node of the cluster"
	echo "else"
    fi
    echo "Directory Server 5.2 is not configured."
    echo "Use:"
    echo "    '$WRAPPER -useversion 5.2 configure' to configure Directory Server 5.2."
}


msg_exist_51() {
    # Note to explain
    # suppress the message if directoryserver is called during the boot time
    $WRAPPER -listversions | grep "5\.1" 1> /dev/null 2>&1 > /dev/null
    if [ $? -eq 0 -a $BOOT -eq 0 ]; then
	echo ""
	echo "***********************************************"
	echo ""
	echo " This script deals with version 5.2 of Directory Server."
	echo ""
	echo " Use $WRAPPER -useversion 5.1 to manage Directory Server 5.1."
	echo ""
	echo "***********************************************"
	echo ""
    fi
}
ORION_J2SE_DIR="/usr/jdk/entsys-j2se"

#########################################
# usage
# print usage message
# input: $1 - 1: exit 1
#             0: do not exit
#########################################
usage () {
	echo "Usage: ${DSCMD}"
	echo "	   help [ subcommand ]"
	echo "Usage: ${DSCMD}"
	echo "	   configure [ -f <configuration file> ]"
	echo "Usage: ${DSCMD}"
	echo "	   unconfigure [ -f <configuration file> ]"
	echo "Usage: ${DSCMD} [ { -s|-server } server-instance ]" 
	echo "	   { start | stop | restart }"
	echo "Usage: ${DSCMD}" 
	echo "	   { start-admin | stop-admin | restart-admin | startconsole }"
	echo "Usage: ${DSCMD} { -s|-server } server-instance"
	echo "	   { monitor | saveconfig | restoreconfig | db2index-task |"
	echo "	     ldif2db-task | ldif2db | ldif2ldap |  vlvindex |"
	echo "	     db2ldif | db2ldif-task | db2bak | db2bak-task |"
	echo "	     bak2db | bak2db-task | suffix2instance |"
	echo "	     account-status | account-activate | account-inactivate }"
	echo "	      { options-and-arguments ...}"
	echo "Usage: ${DSCMD}"
	echo "	   { nativetoascii | admin_ip | ldif | pwdhash | idsktune |"
	echo "	     mmldif } { options-and-arguments ...}"
	echo "Usage: ${DSCMD}"
	echo "	   { sagt | magt } {options-and-arguments ...}"
	echo "	where options-and-arguments depend on the specific subcommand"
	sync_cds_usage
	[ $1 -eq 1 ] && exit 1
}

#########################################
# get_bindpasswd
# get bind password when option (echo OFF)
#
# modify global variable: bind_passwd
#########################################
get_bindpasswd()
{
	# Handle signals, so that echo can be turned back on if Ctrl-C.
	trap "/usr/bin/stty echo; exit" 1 2 3 6 15

	/usr/bin/stty -echo     # Turn echo OFF

	# Endless loop that continues until passwd and re-entered passwd
	# match.
	bind_passwd=""
	first_try=yes

	while [ "$bind_passwd" = "" ]
	do
		if [ ${first_try} = no ]
		then
			echo ""
		fi

		bind_passwd=""  

		echo "Enter bind password: \c"
		read bind_passwd
	done

	/usr/bin/stty echo      # Turn echo ON

	# Removed signal handler
	trap 1 2 3 6 15

	echo ""
}

#########################################
# scan_passwd
# scan its arguments to find '-w -'.
#       if found, call get_bindpasswd and replace
#       '-w -' by '-j <temp_file>'
#
# modify global variable: new_arg
# use global variable: TMP_PASSWD_FILE and bind_passwd
#########################################
scan_passwd () 
{
	init_arg=$@
	> $TMP_PASSWD_FILE
	chmod 700 $TMP_PASSWD_FILE
	got_w=no
	for i in "$@"
	do
        case $i in
        -w)
                got_w=yes
                ;;
        *)
                if [ $got_w = yes ]
                then
                        got_w=no
                        if [ "$i" = "-" ]
                        then
                                get_bindpasswd
                                echo $bind_passwd > $TMP_PASSWD_FILE
                                new_arg="$new_arg -j $TMP_PASSWD_FILE"
                        else
                                new_arg="$new_arg -w '$i'"
                        fi
                else
                        new_arg="$new_arg '$i'"
                fi
                ;;
        esac
	done
}

#########################################
# clean_passwd
# remove the temporay file used for passwd
#
# use global variable: TMP_PASSWD_FILE
#########################################
clean_passwd () {
      rm -f $TMP_PASSWD_FILE
}

#########################################
# subcommand_usage 
# print subcommand usage message
# input: $1 - type of the subcommand
# 	 $2 - directory of the subcommand
#########################################
subcommand_usage () {
COMMAND=$1 # subcommand
DIR=$2

if [ -z "$DIR" ] ; then
	case "$COMMAND" in
	db2index-task | \
	ldif2db-task | \
	db2ldif-task | \
	db2bak-task | \
	bak2db-task | \
	ldif2db | \
	vlvindex | \
	db2ldif | \
	suffix2instance | \
	account-status | \
	account-activate | \
	account-inactivate | \
	mmldif | \
	pwdhash )
		echo "Usage: $COMMAND"
		echo "   For a more detailed usage message please configure your"
		echo "   Directory Server first, using:"
		echo "   $WRAPPER -useversion 5.2 configure"
		exit 1
		;;
	*)
		;;
	esac
fi
case "$COMMAND" in

help )
	usage 1
	;;
unconfigure | \
configure )
	echo "Usage: $COMMAND [ -f <configuration file> ]"
	;;
start | \
stop | \
restart | \
monitor | \
saveconfig | \
restoreconfig )
	echo "Usage: $COMMAND"
	;;
db2index-task )
	$DIR/db2index.pl
	;;
ldif2db-task )
	$DIR/ldif2db.pl
	;;
db2ldif-task )
	$DIR/db2ldif.pl
	;;
db2bak-task )
	$DIR/db2bak.pl
	;;
bak2db-task )
	$DIR/bak2db.pl
	;; 
ldif2db | \
vlvindex | \
db2ldif | \
suffix2instance ) 
	$DIR/$COMMAND
	;;
account-status ) 
	$DIR/ns-accountstatus.pl
	;;
account-activate ) 
	$DIR/ns-activate.pl
	;;
account-inactivate )
	$DIR/ns-inactivate.pl
	;;
ldif2ldap )
	echo "Usage: $COMMAND -D <rootDN> -w <password> -f <filename>"
	;;
bak2db )
	echo "Usage: $COMMAND <backupdir>"
	;; 
db2bak )
	echo "Usage: $COMMAND [backupdir]"
	;;
start-admin )
	$AS_SBINDIR/mpsadmserver help start
	;;
stop-admin )
	$AS_SBINDIR/mpsadmserver help stop
	;;
restart-admin )
	$AS_SBINDIR/mpsadmserver help restart
	;;
startconsole)
	$AS_SBINDIR/mpsadmserver $COMMAND -h
	;;
admin_ip | \
sagt | \
magt )
	$AS_SBINDIR/mpsadmserver help $COMMAND
	;;
ldif | \
pwdhash )
	$DS_COMMON_BINDIR/$COMMAND
        ;;
mmldif )
	$DS_COMMON_BINDIR/$COMMAND -h
	;; 
idsktune ) 
	$DS_COMMON_BINDIR/$COMMAND --help 2> /dev/null
        ;;
sync-cds )
	sync_cds_usage	
	;;
* )
	echo "${DSCMD}: Invalid subcommand: $COMMAND"
	echo 
	usage 0
	;;
esac
exit 1
}
##########################################
# is_root
#
# return: 1 - TRUE
#         0 - FALSE
##########################################
is_root () {
	ID=`/usr/bin/id | cut -f1 -d' '`
	if [ "$ID" = "uid=0(root)" ] || [ "$ID" = "uid=0" ]; then
		return 1
	else
		return 0
	fi
}
#########################################
# exec_var_subcommand
#
# input: $1 - directory of the subcommand
#        $2 - type of the subcommand
#        $3..N - the parameters of the subcommand
# return: 0 - Success
#         1 - Fail
##########################################
exec_var_subcommand () {

DIR=$1
COMMAND=$2 # subcommand

# Skip dir and subcommand.
# The $@ become the parameters for
# the subcommand
shift; shift

case "$COMMAND" in
start )
	$DIR/start-slapd
	;;
stop )
	$DIR/stop-slapd
	;;
restart )
	$DIR/restart-slapd
	;;
monitor )
	$DIR/$COMMAND "$@"
	;;
ldif2db-task )
	scan_passwd "$@"
	eval $DIR/ldif2db.pl "$new_arg"
	clean_passwd
	;;
db2ldif-task )
	scan_passwd "$@"
	eval $DIR/db2ldif.pl "$new_arg"
	clean_passwd
	;;
db2bak-task )
	scan_passwd "$@"
	eval $DIR/db2bak.pl "$new_arg"
	clean_passwd
	;;
bak2db-task )
	scan_passwd "$@"
	eval $DIR/bak2db.pl "$new_arg"
	clean_passwd
	;;
db2index-task )
	scan_passwd "$@"
	eval $DIR/db2index.pl "$new_arg"
	clean_passwd
	;;
saveconfig | \
restoreconfig | \
ldif2db | \
db2ldif | \
vlvindex | \
db2bak | \
suffix2instance )
	$DIR/$COMMAND "$@"
	;;
bak2db )
	if [ $# -ne 1 ]; then
	  echo "Usage: ${DSCMD} -s server-instance $COMMAND <backupdir>"
	  return 1
	fi

	$DIR/$COMMAND "$@"
	;;
ldif2ldap )
	if [ $# -ne 6 ]; then
	  echo "Usage: ${DSCMD} -s server-instance $COMMAND -D <rootDN> -w <password> -f <filename>"
	  return 1
	fi

	$DIR/$COMMAND "$@"
	;;
account-inactivate )
	$DIR/ns-inactivate.pl "$@"
	;;
account-activate )
	$DIR/ns-activate.pl "$@"
	;;
account-status )
	$DIR/ns-accountstatus.pl "$@"
	;;
* )
	echo "${DSCMD}: exec_subcommand: Invalid subcommand: $COMMAND"
	echo 
	usage 0
	return 1
	;;
esac

return $?
}

#########################################
# exec_admserv_subcommand
#
# input: $1 - directory of the subcommand
#        $2 - type of the subcommand
#        $3..N - the parameters of the subcommand
# return: 0 - Success
#         1 - Fail
##########################################
exec_admserv_subcommand () {

COMMAND=$1 # subcommand

# Skip dir and subcommand.
# The $@ become the parameters for
# the subcommand

case "$COMMAND" in
start-admin )
	$AS_SBINDIR/mpsadmserver start
	;;
stop-admin )
	$AS_SBINDIR/mpsadmserver stop
	;;
restart-admin )
	$AS_SBINDIR/mpsadmserver restart
	;;
startconsole | \
admin_ip | \
sagt | \
magt )
	$AS_SBINDIR/mpsadmserver "$@"
	;;
* )
	echo "${DSCMD}: exec_admserv_subcommand: Invalid subcommand: $COMMAND"
	echo 
	usage 0
	return 1
	;;
esac

return $?
}

#########################################
# parse_var_subcommands
#
# input: $@ - the parameters list
#             (-s <instance> is stripped off
#              if there is any)
#	       
# return: 0 - Success
#         1 - Fail
##########################################
parse_var_subcommands () {

# start, stop and restart call this subroutine
# iterate the "$MPS_SR/slapd-*"
RC=0
for di in $DIR; do
	exec_var_subcommand "$di" "$@"
	[ $? -ne 0 ] && RC=1
done

return $RC
}

##########################################
# exec_usr_subcommand
#
# input: parameters of /usr/sbin/directoryserver
# return: the return code of the subcommand
##########################################
exec_usr_subcommand () {

COMMAND=$1 # subcommand

# Skip subcommand.
# The $@ become the parameters for
# the subcommand
shift

case "$COMMAND" in
ldif | \
pwdhash | \
idsktune | \
mmldif  )
	$DS_COMMON_BINDIR/$COMMAND "$@"
	;;

* )
	echo "${DSCMD}: exec_usr_command: Invalid subcommand: $COMMAND"
	echo
	usage 0
	return 1
esac

return $?
}
##########################################
# exec_new_configure_subcommand
#
##########################################
exec_new_configure_subcommand () {

# make package links if not get id
if [ "(" $# -eq 2 ")" -a "(" "$1" = "-get" ")" ]; then
    echo "No links creation." >> /dev/null
fi

OPTIONS=
# Handle silent install (-f configfile)
if [ "(" $# -eq 2 ")" -a "(" "$1" = "-f" ")" ]; then
    statefile=$2
    # Make sure we have an absolute path to the file before we cd 
    if [ ! "(" `echo $statefile | cut -c1` = "/" ")" ]; then
	statefile=`pwd`/$statefile
    fi
    OPTIONS="-nodisplay -noconsole -state $statefile"
else
    OPTIONS=$@
fi
cd $DSV_USRDIR
${JAVA} -cp ./setup -Djava.library.path=$JAVA_LIBPATH $DS_SETUP_CLASS $OPTIONS
return $?
}

##########################################
# exec_configure_subcommand
#
##########################################
exec_configure_subcommand () {

is_root
IS_ROOT=$?
if [ $IS_ROOT -eq 0 ]; then
  echo "${DSCMD} $1: must run as root"
  return 1
fi

JAVA_CONFIG_CLASS=$DS_SETUP_PATH/$DS_SETUP_CLASS.class

shift # skip "configure" in $1

# check JRE
java_check

if [ -f "${JAVA_CONFIG_CLASS}" ]; then
    exec_new_configure_subcommand "$@"
    return $?
else
    echo "Cannot find ${JAVA_CONFIG_CLASS}"
    return 1
fi
}

##########################################
# exec_new_unconfigure_subcommand
#
##########################################
exec_new_unconfigure_subcommand () {

OPTIONS=
# Handle silent uninstall (-f configfile)
if [ "(" $# -eq 2 ")" -a "(" "$1" = "-f" ")" ]; then
    statefile=$2
    # Make sure we have an absolute path to the file before we cd 
    if [ ! "(" `echo $statefile | cut -c1` = "/" ")" ]; then
	statefile=`pwd`/$statefile
    fi
    OPTIONS="-nodisplay -noconsole -state $statefile"
else
    OPTIONS=$@
fi

clean_ha
if [ $? -ne 0 ] ; then
    return res
fi

check_instance

# to be able to run uninstall with success
rm -f $DS_SETUP_PATH/$DS_UNINSTALL_CLASS.class
ln -s $AS_SETUP_PATH/$DS_UNINSTALL_CLASS.class $DS_SETUP_PATH/$DS_UNINSTALL_CLASS.class

cd $DSV_USRDIR
$JAVA -cp ./setup -Djava.library.path=$JAVA_LIBPATH $DS_UNINSTALL_CLASS $OPTIONS
rm -f $DS_SETUP_PATH/$DS_UNINSTALL_CLASS.class
return $?
}


##########################################
# exec_unconfigure_subcommand
#
##########################################
exec_unconfigure_subcommand () {

is_root
IS_ROOT=$?
if [ $IS_ROOT -eq 0 ]; then
  echo "${DSCMD} $1: must run as root"
  return 1
fi

shift # skip "unconfigure" in $1
exec_new_unconfigure_subcommand "$@"
return $?
}

#########################################
# exec_synccds_subcommand
#
# input: "$@" of the directoryserver
# return: 0 - success
#         None zero - Fail
#########################################
exec_synccds_subcommand () {

	OPTIONS="-r $MPS_SR "
	back_to_52="no"

	# check if '5.2' option has been specified

	shift
	if [ $# -eq 1 ] || [ $# -eq 3 ] || [ $# -eq 5 ]; then
		if [ $1 = "5.2" ] && [ `uname -s` = "SunOS" ]; then
			back_to_52="yes"
			OPTIONS="$OPTIONS -v 5.2 -j ds52.jar -n \"Sun ONE Directory Server\""
			getBuildNumber52
			if [ "x$buildNumber52" != "x" ]; then
				OPTIONS="$OPTIONS -b $buildNumber52"
			fi
			shift
		else
			echo "Invalid option: $1"
			subcommand_usage sync-cds
			exit 1
		fi
	else
		OPTIONS="$OPTIONS -v 5.2_Patch_2 -j ds522.jar -n \"Sun Java(TM) System Directory Server\""
		buildNumber="2004.107.0405"
		if [ "x$buildNumber" != "x" ]; then
			OPTIONS="$OPTIONS -b $buildNumber"
		fi
	fi

	# Get the ISIE available in the adm.conf file
	ADM_CONF=${MPS_SR}/admin-serv/config/adm.conf
	if [ -f "${ADM_CONF}" ]; then
		ISIE_SUFFIX=`cat ${ADM_CONF} | grep "^isie:" | cut -f2- -d","`
		ISIEDN="cn=Sun ONE Directory Server, ${ISIE_SUFFIX}"
		OPTIONS="$OPTIONS -i \"$ISIEDN\""
	else
		echo "	ERROR:"
		echo "		Updating the Configuration Directory Server requires the Administration"
		echo "		Server to be configured"
		echo "		Administration Server is not configured on this machine."
		echo "		Cannot update the Configuration Directory Server."
		exit 1 
	fi

	if [ ! -h ${MPS_SR}/shared/bin/sync-product-cds ];then
		echo "To run the sync-cds directive, you need to install the "
		echo "Java Enterprise System Administration Server 5.2 patch "
		if [ `uname -p` = "sparc" ]; then
			echo "115610-08 (or later)"
		else
			echo "115611-08 (or later)"
		fi
		exit 1
	fi

	# read the options
	credential_file=""
	log_file=""
	while getopts f:l: LOPT
	do
		case $LOPT in
		f)	
			if [ "x${credential_file}" = "x" ];then 
				OPTIONS="$OPTIONS -$LOPT $OPTARG"
				credential_file=$OPTARG
			else
				echo "Option already set: $LOPT"
				subcommand_usage sync-cds
				exit 1
			fi
			;;
		l)
			if [ "x${log_file}" = "x" ];then
				OPTIONS="$OPTIONS -$LOPT $OPTARG"
				log_file=$OPTARG
			else
				echo "Option already set: $LOPT"
				subcommand_usage sync-cds
				exit 1
			fi
			;;
		\?)    
			echo "Unknown option: $LOPT" 
			subcommand_usage sync-cds
			exit 1
             	 	;;
		esac
	done

	# run the command to sync the admin
	cd ${MPS_SR}/shared/bin/
	eval ./sync-product-cds $OPTIONS		
	sync_directory_cds_status=$?
 
	return $?
}

#########################################
# file_link
#
# $1 configure or unconfigure
# $2 dst
# $3 src
#
##########################################
file_link () {
    case "$1" in
    configure )
	if [ ! -h $2 ]; then
	    if [ ! -d `dirname $2` ]; then
		echo "Directory `dirname $2` does not exist"
		exit 1
	    fi
	    if [ ! -w `dirname $2` ]; then
		echo "Cannot write to `dirname $2`"
		exit 1
	    fi
	    if [ ! -r "$3" ]; then
		echo "Cannot read $3"
		return 1
	    fi
	    ln -s $3 $2
	    return $?
	fi
	;;
    unconfigure )
	if [ -h $2 ]; then
	    rm $2
	    return $?
	fi
	;;
    esac
}

#########################################
# java_check
#
# Check for good JRE
#
# S8U4 is the first S8 release to bundle
# the minimum required by setupsdk5
#
##########################################
java_check () {
    if [ $IS_ORION_J2SE -eq 0 ] ; then
	${J2SE_DIR}/bin/java -fullversion 2>&1| egrep "(1.4.[1-9]|1.5.[0-9])" >/dev/null
	if [ $? -ne 0 ]; then
	    echo "WARNING: Need a JRE 1.4.1 or later; ${J2SE_DIR}/bin/java is:"
	    ${J2SE_DIR}/bin/java -fullversion 2>&1
	    echo
	fi
    fi
}

#########################################
# pkg_check
#
# check that required packages are
# correctly installed
##########################################
pkg_check() {

    if [ "x"$1 = "xuninstall" ] ; then
	init_uninstall_pkg_check
    else
	init_pkg_check
    fi

    rc=0
    basedirs=""
    missing=""
    for pkg in ${PKG_32BIT}; do
	pkg_check_exist "${pkg}"
	if [ $? -eq 0 ]; then
	    missing="$missing$pkg "
	    continue
	fi
	pkg_add_basedirs $pkg
    done

    for pkg in ${pkg_32extra}; do
	pkg_check_exist "${pkg}"
	if [ $? -eq 0 ]; then
	    missing="$missing$pkg "
	    continue
	fi
	done

    # check for missing required packages
    if [ -n "$missing" ]; then
	echo "ERROR: The following packages are not installed:"
	echo $missing
	echo
	rc=1
    fi

	if [ $USE_64 -eq 1 ]; then
		missing=""
		present=""
		for pkg in ${PKG_64BIT}; do
		pkg_check_exist "${pkg}"
		if [ $? -eq 0 ]; then
			missing="$missing$pkg "
			continue
		fi
		present="$present$pkg "
		pkg_add_basedirs $pkg
		done
		
		for pkg in ${pkg_64extra}; do
		pkg_check_exist "${pkg}"
		if [ $? -eq 0 ]; then
			missing="$missing$pkg "
		else
			present="$present$pkg "
		fi
		done

		# check for partial installation of 64-bit packages
		if [ -n "$missing" -a -n "$present" ]; then
		echo "ERROR: The following 64-bit packages are not installed:"
		echo $missing
		echo
		rc=1
		fi
	fi

    # check for unique basedir
    num=`printf "$basedirs" | sort | uniq | wc -l`
    if [ -z "$basedirs" -o  $num -ne 1 ]; then
	echo "ERROR: The installed packages do not have a unique basedir."
	echo
	rc=1
    fi

	if [ $rc -eq 0 ]; then
		full_list="${PKG_32BIT} ${pkg_32extra} ${PKG_64BIT} ${pkg_64extra}"
		for pkg in ${full_list}; do
			pkg_check_uniq ${pkg}
		done
	fi
	platform_specific_check
	if [ $? -ne 0 ]; then
	    rc=1
 	fi

    return $rc
}


#########################################
# check_instance 
#
# Check if the instance exists
#
# $1 : instance to check.
#      if $1="", checks that at least 1 instance exists
#
# Display available instance if $1 does not exists
##########################################
check_instance() {
	instance_list=`ls -d ${MPS_SR}/slapd-* 2>/dev/null`
	if [ "x${instance_list}" = x ]
	then
		msg_not_configured
		exit 1
	fi
	if [ -n "$1" ] ; then
	    if [ ! -d "$MPS_SR/slapd-$SERVER_INSTANCE" ]  ; then
		echo "The server \"$SERVER_INSTANCE\" does not exist."
		echo Available servers: `ls -d ${MPS_SR}/slapd-* | sed "s|$MPS_SR/slapd-||g"`
		exit 1
	    fi
	fi
}


#########################################
# is_orion_j2se
#
# Check if the JVM to use is the "Orion JVM"
#
# Set IS_ORION_J2SE variable to:
#     1 if we must use "Orion JVM"
#     0 otherwise
##########################################
is_orion_j2se() {
    IS_ORION_J2SE=0
    if [ -x ${ORION_J2SE_DIR}/bin/java ] ; then
	IS_ORION_J2SE=1
    fi
}

#########################################
# main 
##########################################

SERVER_INSTANCE=""
DSCMD=`basename $0`
BOOT=0

TMPDIR="/tmp/directoryserver.$$"
if mkdir -m 700 ${TMPDIR}
then
    # Cleanup on exit.
    trap 'rm -rf ${TMPDIR}' 0
else
    echo "ERROR: unable to create a safe temporary directory."
    exit 1
fi

TMP_PASSWD_FILE=${TMPDIR}/passdir.$$
new_arg=""

is_orion_j2se

# check packages are installed correctly
# no need to check for unconfigure
if [ "x$1" != x ]; then
    if [ $1 != "unconfigure" -a $1 != "uninstall" ]; then
	pkg_check install
	if [ $? -ne 0 ]; then
	    exit 1
	fi
    else 
	pkg_check uninstall
	if [ $? -ne 0 ]; then
	    exit 1
	fi
    fi
else
	usage 1
fi

echo

init

ARGS="$@"
while true
do
    case "$1" in
		-s | \
		-server )
		shift
		SERVER_INSTANCE="$1"
		;;
		-b )
		# the option is passed in during the boot time
		BOOT=1
		;;
    * )
		break
		;;
    esac
    if [ -z "$2" ]; then
		echo
		usage 1
    fi
    shift
done

msg_exist_51

if [ -z "$SERVER_INSTANCE" ]; then
    DIR=""
    for di in $MPS_SR/slapd-*
    do
		[ -d "$di" ]  && DIR="$DIR $di"
    done
else
    DIR="$MPS_SR/slapd-$SERVER_INSTANCE"
fi

LD_LIBRARY_PATH=$MPS_SR/lib:$LD_LIBRARY_PATH; export LD_LIBRARY_PATH

case "$1" in
start-admin | \
stop-admin | \
restart-admin | \
startconsole | \
admin_ip | \
sagt | \
magt )
	exec_admserv_subcommand "$@"
	exit $?
	;;
nativetoascii | \
NativeToAscii )
	echo "NativeToAscii no more supported. Please use iconv(1)." 
	exit 1;
	;;
setup | \
configure )
	exec_configure_subcommand "$@"
	exit $?
	;;
uninstall | \
unconfigure )
	exec_unconfigure_subcommand "$@"
	exit $?
	;;
start | \
stop  | \
restart )
	check_instance "$SERVER_INSTANCE"
	parse_var_subcommands "$@"
	exit $?
	;;
monitor | \
saveconfig | \
restoreconfig | \
ldif2db | \
ldif2db-task | \
ldif2ldap | \
db2index-task | \
db2ldif | \
db2ldif-task | \
vlvindex | \
db2bak | \
db2bak-task | \
bak2db | \
bak2db-task | \
account-inactivate | \
account-activate | \
account-status | \
suffix2instance )
	if [ -z "$SERVER_INSTANCE" ]; then
			usage 1
	fi
	check_instance "$SERVER_INSTANCE"
	exec_var_subcommand "$MPS_SR/slapd-$SERVER_INSTANCE" "$@"
	exit $?
    ;;
ldif  | \
pwdhash  | \
idsktune  | \
mmldif )
	exec_usr_subcommand "$@"
	exit $?
	;;
sync-cds )
	exec_synccds_subcommand "$@"
	exit $?
	;;
help )
	shift
	if [ $# -ne 0 ] ; then
		COMMAND="$1"
		HDIR=""
		for di in $MPS_SR/slapd-*
		do
			[ -d "$di" ]  && HDIR="$di"
		done
		subcommand_usage "$COMMAND" "$HDIR"
	else
		usage 1
	fi
	;;
* )
	usage 1
	;;
esac
