#!/bin/sh
#
# Copyright 2004 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# directoryserver S1DS52
#
#ident	"@(#)$RCSfile: directoryserver,v $	$Revision: 1.1.6.13 $ - $Date: 2004/10/26 13:03:48 $"

#########################################
#
# usage_specific
#	In addition to the common usage
#
#########################################
sync_cds_usage () 
{
	echo "Usage: ${DSCMD}"
	echo "	   sync-cds [-f {absolute path of credential's file}] [-l {logfile absolute path}]"

}

getBuildNumber52 () {
	buildNumber52=""
} 


if [ "x"$VERBOSE != "x" ] ; then
    set -x
fi

debug() {
    if [ "x"$VERBOSE != "x" ] ; then
	echo $1
    fi
}

#########################################
# Platform-specific code 
# The following functions must be defined:
#     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
#########################################

#########################################
# pkg_print_instances
#
# $1 pkg name
#
##########################################
pkg_print_instances () {
    pkg=$1
    instances=`rpm -q ${pkg}`
    for n in $instances; do
	pkg_get_basedir $n
	printf "\t"$n"\t"$BASEDIR"\n"
    done
    return 0
}

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

#########################################
# pkg_add_basedirs
#
# Add to $basedirs basedirs of $1.* packages
##########################################
pkg_add_basedirs() {
    debug "pkg_add_basedirs"
    instances=`rpm -q $1`
    for n in $instances; do
	pkg_get_basedir $n
	if [ -z "$basedirs" ]; then
	    basedirs=$BASEDIR"\n"
	else
	    basedirs="$basedirs$BASEDIR\n"
	fi
    done
    return 0
}

#########################################
# pkg_check_uniq 
#
# Check that only one pkg $1 is installed
##########################################
pkg_check_uniq () {
    debug "pkg_check_uniq"
    pkg=$1
    num=`rpm -q "${pkg}" 2>/dev/null | wc -l`
    if [ $num -ne 1 ]; then
	first_instance=`rpm -q ${pkg} | head -1`
        echo "WARNING: Package ${pkg} has multiple instances:"
        pkg_print_instances ${pkg}
        echo "WARNING: only ${first_instance=} is used by Directory Server 5.2"
    fi
}


#########################################
# pkg_get_basedir
#
# Get basedir of package $1
##########################################
pkg_get_basedir () {
    debug "pkg_get_basedir" $1
    pkg=$1
    pkg_check_exist $1
    if [ $? -eq 0 ]; then
#	echo "ERROR: The following package is not installed: ${pkg}"
	return 1
    fi
    BASEDIR=`rpm -q --queryformat '%{INSTPREFIXES}' "${pkg}" | head -1`
    if [ "$BASEDIR" = "(none)" ] ; then
	BASEDIR="/"
    fi
    return 0
}

#########################################
# pkg_get_java_dir
#
# evaluate if a rpm java package is
# installed and if the path to java
# is all right
#########################################

pkg_javadir () {
 jdkpkg=$1
 J2SE_DIR=""

 pkg_check_exist $jdkpkg
 if [ $? -ne 0 ]; then
   JREDIR=`rpm -ql $jdkpkg  | grep '/jre$'`
   J2SE_DIR=`dirname $JREDIR`
   is_java_path_right $J2SE_DIR
   if [ $? -ne 0 ]; then
	J2SE_DIR=""
   fi
 fi
}

#########################################
# pkg_jredir
#
# evaluate if the particular case of
# jre is installed and find the path
# to java binary
#########################################

pkg_jredir () {
 jdkpkg=$1
 J2SE_DIR=""
 pkg_get_basedir $jdkpkg
 if [ $? -eq 0 ]; then
   JREDIR=`rpm -ql $jdkpkg  | grep 'bin/java$'`
   J2SE_DIR=`dirname $JREDIR`
   J2SE_DIR=`dirname $J2SE_DIR`
 fi
}

#########################################


#########################################
# get_j2se_dir 
#
# Set J2SE_DIR
##########################################
get_j2se_dir() {
    debug "get_j2se_dir"
    if [ $IS_ORION_J2SE -eq 0 ] ; then

        # Try jdk1.5
        pkg_javadir jdk 
        
        # Try jre1.5
        if [ "X"$J2SE_DIR = "X" ]; then
           pkg_jredir jre
        fi

        # Try jdk1.4
        if [ "X"$J2SE_DIR = "X" ]; then
          pkg_javadir j2sdk
        fi

        # Try jre1.4
        if [ "X"$J2SE_DIR = "X" ]; then
           pkg_jredir j2re
        fi

        if [ "X"$J2SE_DIR = "X" ]; then
          return 1
        fi
    else
	J2SE_DIR=${ORION_J2SE_DIR}
    fi
    return 0
}


#########################################
# init_pkg_check 
#
# Initialize pkgs to check at any time 
# except uninstall
##########################################
init_pkg_check () {    
    debug "init_pkg_check"
 
 	# those packages need to have the same basedir
     PKG_32BIT="
 	sun-admin-server
     "
 	# those packages are not enforced to have the same basedir
 	pkg_32extra="
 	sun-icu
 	sun-nss
 	sun-nspr
 	sun-sasl
 	sun-ldapcsdk
 	"
# 	zlib
# 	jss
    
    USE_64=0
    PKG_64BIT=""
    pkg_64extra=""
}

#########################################
# init_uninstall_pkg_check
#
# Initialize pkgs to check at uninstall
##########################################
init_uninstall_pkg_check() {
    debug "init_uninstall_pkg_check"
    PKG_32BIT="
            sun-directory-server
        "
    pkg_32extra=""
    if [ $IS_ORION_J2SE -eq 0 ] ; then
        pkg_check_exist jdk
        if [ $? -ne 0 ]; then
	  pkg_32extra=$pkg_32extra"
              jdk
          "
        else
          pkg_check_exist j2sdk
          if [ $? -ne 0 ]; then
	    pkg_32extra=$pkg_32extra"
                j2sdk
            "
          fi
        fi
    fi
    USE_64=0
    PKG_64BIT=""
    pkg_64extra=""
}



#########################################
# platform_specific_check
#
# Perform specific checks
##########################################
platform_specific_check() {
    debug "platform_specific_check"
    return 0
}


#########################################
# 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() {
    debug "clean_ha"
    return 0
}
#########################################
# 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() {
    debug "init"
    AS_BASEDIR=/
    pkg_get_basedir sun-admin-server
    AS_BASEDIR=$BASEDIR
    DS_BASEDIR=/
    pkg_get_basedir sun-directory-server
    DS_BASEDIR=$BASEDIR

    DSV_USRDIR=/directory-server/5.2
    DSV_ETCDIR=/directory-server/5.2/etc
    WRAPPER=/sbin/directoryserver

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

    # Where to find conf files
    SERVERROOT_CONF_FILE=serverroot.conf
    AS_CONF_DIR=${AS_BASEDIR}/admin-server/5.2/shared/config
    DEFAULT_SERVERROOT=${AS_BASEDIR}/serverroot/
    MPS_SR=$DEFAULT_SERVERROOT
    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/admin-server/5.2/setup
    AS_SETUP_PATH=$MPS_SR/setup
    DS_SETUP_PATH=$DS_BASEDIR/directory-server/5.2/setup/
    DS_SETUP_CLASS=DirectoryServerSetup
    DS_UNINSTALL_CLASS=uninstall_Sun_ONE_Directory_Distribution

    # Where to find shell scripts
    AS_SBINDIR=$AS_BASEDIR/admin-server/5.2/sbin
    DS_SBINDIR=$DS_BASEDIR/directory-server/5.2/sbin

    # Where to find common commands
    DS_COMMON_BINDIR=$DS_BASEDIR/directory-server/5.2/bin/slapd/server

    get_j2se_dir
    if [ $? -eq 0 ] ; then
      JAVA=$J2SE_DIR/bin/java
    else
      return 1
    fi

    return 0
}

msg_not_configured() {
    echo "Directory Server 5.2 is not configured."
    echo "Use:"
    echo "    '$WRAPPER -u 5.2 configure' to configure Directory Server 5.2."
}

msg_exist_51() {
    return
}

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

cd $DSV_USRDIR
$JAVA -cp ./setup:$AS_SETUP_PATH -Djava.library.path=$JAVA_LIBPATH $DS_UNINSTALL_CLASS $OPTIONS

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"

	# JDM Trace
	[ "$VERBOSE2" != "" ] && echo "==> exec_synccds_subcommand"

	# 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_4 -j ds524.jar -g ds524.jar -n \"Sun Java(TM) System Directory Server\""
		buildNumber="2005.230.0415"
		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/
	[ "$VERBOSE2" != "" ] && set -x
	eval ./sync-product-cds $OPTIONS
	sync_directory_cds_status=$?
	[ "$VERBOSE2" != "" ] && set -
 
	return $sync_directory_cds_status
}

#########################################
# 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_java_path_right
#
# check $jpath/bin/java && $jpath/jre
# exists for a possible java_home path
#
##########################################

is_java_path_right () {
  jpath=$1

  if [ -x $jpath/bin/java ] && [ -d $jpath/jre ]; then
    return 0
  fi

  return 1
}


#########################################
# 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
    is_java_path_right ${ORION_J2SE_DIR}
    if [ $? -eq 0 ]; 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
if [ $? -ne 0 ]; then
  echo "ERROR: unable to find java binary"
  exit 1
fi

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
