#!/bin/ksh -p
#
# ident "@(#)utconfig.ksh	1.126 02/12/16 SMI"
#
# Copyright 1999-2002 Sun Microsystems, Inc.  All rights reserved.
#

unset JAVA_HOME
unset CLASSPATH
PATH="/usr/sbin:/usr/bin"
PROGRAM_ID=$(basename $0)
THIS_HOST=$(uname -n)

# For Debug output uncomment the next 2 lines 
#PS4='[$LINENO]+ '
#set -x

ETC_OPT_UT="/etc/opt/SUNWut"
VAR_OPT_UT="/var/opt/SUNWut"
UT_HTTP_BIN="/opt/SUNWut/http/bin"
UT_HTTP_ETC="$ETC_OPT_UT/http"
UT_HTTP_VAR="$VAR_OPT_UT/http"
UT_SRDS_ETC="$ETC_OPT_UT/srds"

TMP_DIR_PATH="${VAR_OPT_UT}/tmp"
TMP_PROGID=${TMP_DIR_PATH}/$PROGRAM_ID.$$

trap "rm -rf ${TMP_PROGID}.*; stty echo </dev/tty; exit 1" HUP INT QUIT TERM

TMP_FILE="${TMP_PROGID}.tmp"
TMP_CONF_FILE="${TMP_PROGID}.conf"
TMP_INSERT_FILE="${TMP_PROGID}.insert"
TMP_REP_FILE="${TMP_PROGID}.rep"

BEFORE="before.$PROGRAM_ID"
DBM_FILES_PATH="${VAR_OPT_UT}/ndbm"
SMARTCARD_FILES_PATH="${ETC_OPT_UT}/smartcard"
AUTHPROPS="${ETC_OPT_UT}/auth.props"
UTADMIN_GROUP="utadmin"
HTTP_CFG=$UT_HTTP_ETC/utadmin.httpd.conf

# This file is created by the command /opt/SUNWbb/bin/bbmkuser 
USER_CONF=/var/opt/SUNWbb/users.conf

# Kiosk.conf file
KIOSK_CONF_TEMPLATE=/var/opt/SUNWut/kiosk/kiosk.conf.template
KIOSK_CONF=/var/opt/SUNWut/kiosk/kiosk.conf


Usage() {
  print -u2 "Usage: $PROGRAM_ID $PROGRAM_OPTS"
  exit 1
}

CheckUidIsZero() {
  case "$(id)" in
    'uid=0('*) return 0;;  # uid is zero
    *)         Fatal "must be run as UID 0 (root)";;
  esac
}

CleanupAndExit() {
  rm -rf ${TMP_PROGID}.*
  exit $1
}

Fatal() {
  print -u2 "$PROGRAM_ID: fatal, $1"
  exit 1
}

Note() {
  print -u2 "$PROGRAM_ID: note, $1"
  return 0
}

UTInstalled() {
  pkginfo -q SUNWuta
  return $?
}

LdapClientInstalled() {
  pkginfo -q $LCL_PACKAGE
  return $?
}

LdapClientInstallPartial() {
  pkginfo -p | grep $LCL_PACKAGE >/dev/null 2>&1
  return $?  
}

SRDSInstalled() {
  pkginfo -q $SRDS_PACKAGE
  return $?
}

SRDSInstallPartial() {
  pkginfo -p | grep $SRDS_PACKAGE >/dev/null 2>&1
  return $?  
}

SRDSVersion() {
  INSTALLED_VERSION="$(pkgparam $SRDS_PACKAGE SUNW_PRODVERS 2>&-)"
  #
  # above var is global, used in calling func error msg

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

UTPasswordExists() {
   [[ -r ${ETC_OPT_UT}/utadmin.pw ]] && return 0 || return 1
}


SetUTFilePerms() {
  if [[ -z $1 ]]; then
    Fatal "configuration file parameter not specified"
  elif [[ ! -f $1 ]]; then
    Fatal "$1 is not a file"
  fi
  chmod 660 $1
  chgrp utadmin $1
}


PreviousUTDataStore() {

   if [[ -d $VAR_OPT_LDAP_DBM_UT ]]; then
       return 0	    
   else
       return 1
   fi
}

EncryptPasswd() {
  typeset STATUS=0

  print "$1" | /opt/SUNWut/srds/lib/utencode
  return $STATUS
}

PleaseTryAgain() {
  print "\nError: $1, please try again."
  return $?
}


IsValidAlphanumeric()
{
   (($# == 1 && ${#1} <= 24)) || return 1

   param=$(echo $1 | tr ' ' '\000')
   [[ $param == [a-zA-Z0-9]+([_a-zA-Z0-9-]) && $1 != *- ]]
}

IsValidInteger()
{
   (($# == 1 && ${#1} <= 24)) || return 1

   param=$(echo $1 | tr ' ' '\000')
   [[ $param == +([0-9]) ]]
}

IsValidCAMUserPrefix()
{
   (($# == 1 && ${#1} <= 4)) || return 1

   param=$(echo $1 | tr ' ' '\000')
   [[ $param == *([a-zA-Z0-9])[a-zA-Z]*([a-zA-Z0-9]) ]]
}

SetPASSWD() {
  typeset STATUS=0
  typeset ERROR_CODE=0
  typeset ENTRY REPLY1 REPLY2

  while true; do
    case $ERROR_CODE in
      1) PleaseTryAgain "entries must be at least 5 characters in length";;
      2) PleaseTryAgain "entry contains invalid characters";;
      3) PleaseTryAgain "entries were not the same";;
    esac

    for ENTRY in "Enter" "Re-enter"; do
      print -n "$ENTRY $1 password: "
      stty -echo
      read -r
      stty echo
      print ""
      case "$ENTRY" in
        Enter) REPLY1="$REPLY";;
        *)     REPLY2="$REPLY";;
      esac
    done

    # use "utpw -V" to validate length and char set of entry
    #
    print "$REPLY1" |$UTA_BASEDIR/sbin/utpw -V
    case $? in
      0) ;; 
      1) ERROR_CODE=1; continue;;
      2) ERROR_CODE=2; continue;;
      *) print -n "Password validation, utpw failed with unknown exit status"; continue;;
    esac
    if [[ "$REPLY1" != "$REPLY2" ]]; then
      ERROR_CODE=3
      continue
    fi

    PASSWD="$REPLY1"
    break
  done

  return $STATUS
}

PromptForParameters() {
  typeset STATUS=0
  SKIP_SWS=false
  SWS_ALREADY_CFG=false

  if $FORCE; then
    if [[ -z "$PASSWD" ]]; then
      Fatal "PASSWD file does not exist"
    elif [[ $(expr "$PASSWD" : '.*') -lt 5 ]]; then
      Fatal "PASSWD must be at least 5 characters in length"
    fi
  else
    fmt <<-!

	This script automates the configuration of the $UT_PROD_NAME
	software and related software products.  Before proceeding, you
	should have read the $UT_PROD_NAME $UT_VERSION Installation
	Guide and filled out the Configuration Worksheet.  This script
	will prompt you for the values you filled out on the Worksheet.
	For your convenience, default values (where applicable) are
	shown in brackets. 
	!

    if ! ReplyIsYes "\nContinue"; then
      CleanupAndExit 0
    fi
  fi

  ROOTNAME="${ROOTENTRY#o=}"
  ROOTNAME="${ROOTNAME%%,*}"

  SKIP_SRDS=false

  if ! $FORCE ; then
     if PreviousUTDataStore; then
              SKIP_SRDS=true
     else
        SetPASSWD "Sun Ray admin"
     fi
  else
        SKIP_SRDS=true
  fi

  case "$PASSWD" in
    *\\*) UTPASSWD="$(print "$PASSWD" |sed 's:\\:\\\\:g')";; # escape backslashs
    *)    UTPASSWD="$PASSWD";;
  esac

  ROOTDN="cn=admin,$ROOTENTRY"

  ROOTPW="$PASSWD"
  CRYPTD_ROOTPW="$(EncryptPasswd "$ROOTPW")"

  if [[ $? != 0 ]]; then
    Fatal "internal error, could not encrypt password '$ROOTPW'"
  fi
  case "$CRYPTD_ROOTPW" in
    "") Fatal "internal error, encrypted password is empty";;
  esac

  # Only prompt SRAS if not autoconfigure
  if ! $FORCE; then
    #Retrieve current webserver settings
    SWSInfo
  
    if $SWS_ALREADY_CFG ; then
       if ! $FORCE && ReplyIsYes "\nPrevious Sun Ray Admin Server instance" \
         "found.\n" "Do you wish to preserve it?" ; then
  	SKIP_SWS=true
          UT_INST_SITE=$UT_HTTP_VAR/$UT_INST/websites/default_site
          HTTPCFGFILE=$UT_HTTP_ETC/$UT_INST.httpd.conf
  	# XXX need to add code to support older http server upgrade
       elif ! $FORCE ; then
  	InitSWSVars
  	SWSInfo
          UnconfigSWS
	  CreateUTTempDir
          SetupCgiTokens
       fi
    fi
        
    if ! $SKIP_SWS && SRASInstalled && SRASVersion $SRAS_VERSION ; then
      if $FORCE || ReplyIsYes "\nConfigure $SRAS_PROD_NAME $SRAS_VERSION"; then
        CONFIG_SWS=true
      fi
  
      if $CONFIG_SWS; then
        if ! $FORCE; then
          InitSWSVars

	# Instance is now fixed to DEFAULT_UT_INST
	UT_INST="$DEFAULT_UT_INST"
  
  	# Enquire user for Webserver port ; re-query if port is already
  	# in use.
  
          PORT_OK=false
  	while ! $PORT_OK
  	do
             print -n "Enter $UT_ADMIN_WEB_S port number [$DEFAULT_UT_PORT]: "
             read -r
             case "$REPLY" in
               "") UT_PORT="$DEFAULT_UT_PORT";;
               *)  UT_PORT="$REPLY";;
             esac
  
             netstat -na | grep LISTEN | grep -w "$UT_PORT" >> /dev/null
  
             if [[ $? -eq 0 ]]; then
                 print "Port specified already in use. Please re-enter"
                 continue
             fi
  
  	   ( (( UT_PORT+=0)) ) 2>/dev/null 
  	   if [[ $? -eq 0 ]]; then
  		PORT_OK=true
  	   else
  		print "Port specified must be numeric. Please re-enter"
  	   fi
  	done
          print ""
      
          SetCGI_USER
  	
  	ConfigRemoteAdmin
  
  
        fi
        UT_INST_SITE=$UT_HTTP_VAR/$UT_INST/websites/default_site
        HTTPCFGFILE=$UT_HTTP_ETC/$UT_INST.httpd.conf
      fi
    fi
  fi

  InitKioskVars

  if ! $FORCE; then
        PromptForKioskParameters
  fi

  return $STATUS
}

SubstituteMacros() {
  sed "
    s
@(ROOTENTRY)
$ROOTENTRY
g
    s
@(ROOTNAME)
$ROOTNAME
g
    s
@(HOSTNAME)
$HOSTNAME
g
    s
@(THIS_HOST)
$THIS_HOST
g
    s
@(LDAP_PORT)
$LDAP_PORT
g
    s
@(UTPASSWD)
$UTPASSWD
g
    s
@(VERSIONENTRY)
$VERSIONENTRY
g
    s
,o=v[1-9][^,]*,
,o=v$VERSIONENTRY,
g
    s
@(ROOTDN)
$ROOTDN
g
    s
{sunds}NOTSET
$CRYPTD_ROOTPW
g
    s
@(HTTPCFGFILE)
$HTTPCFGFILE
g
    s
@(HTTPPORT)
$UT_PORT
g
    s
@(SSLENABLE)
$SSLENABLE
g
  " $1

  return $?
}

InsertFile(){
    grep '^# SUNWutrep begin' $1 >/dev/null 2>&1
    if [[ $? -eq 0 ]]; then
	# Replication block exists, insert before SUNWutrep block
	ed - $1 <<-EOE 2>/dev/null 1>&2
	/^# SUNWutrep begin/
	-
	.r $2
	w
	q
	EOE
    else
	# Replication block not defined, append at the end of the file
	cat $2 >> $1
    fi
}

#
#  Restores SRDS configuration files from the default directory:
#	/etc/opt/SUNWut/srds/default
#
RestoreSRDSConf() {
    for confile in utdsd.acl.conf utdsd.at.conf utdsd.conf utdsd.oc.conf utdsd.ini
    do
    	cp ${SRDS_LDAP_DEFAULT}/${confile} ${SRDS_LDAP_CURRENT}/${confile}
    done
    LDAP_PORT=$(get_ldap_port)
}

#
#  Sync up the SRDS port number in the /etc/inet/services file
#
SyncEtcServices() {
    grep "^utdsd[ 	][ 	]*${LDAP_PORT}/" /etc/inet/services >/dev/null 2>&1
    if [[ $? -ne 0 ]]; then
    	TMP_SERVICES_FILE="${TMP_DIR_PATH}/services.SUNWut.prototype"
	# need to update the SRDS port number
	sed -e "s/^\(utdsd[	 ][	 ]*\)[0-9][0-9]*\(\/.*\)$/\1${LDAP_PORT}\2/" \
		${UTO_BASEDIR}/lib/prototype/services.SUNWut.prototype \
		> $TMP_SERVICES_FILE
	${UTO_BASEDIR}/lib/utrepair -a -d ${TMP_DIR_PATH} /etc/inet/services
	rm $TMP_SERVICES_FILE 2> /dev/null
    fi
}

AppendAndCopySchema() {
  typeset STATUS=0
  typeset CONF_FILE="$SRDS_LDAP_CURRENT/$1"

  CreateBeforeFile $CONF_FILE

  DeleteUTEntry $CONF_FILE >$TMP_CONF_FILE

  # append Sun Ray entry on tmp file
  #
  cat $UT_TEMPLATE_LDAP/$1 >>$TMP_CONF_FILE

  ReplaceFile $CONF_FILE $TMP_CONF_FILE

  cp $UT_TEMPLATE_LDAP/$2 $SRDS_LDAP_CURRENT/$2
  
  return $STATUS
}

UnappendAndRmSchema() {
  typeset STATUS=0
  typeset CONF_FILE="$SRDS_LDAP_CURRENT/$1"

  DeleteUTEntry $CONF_FILE >$TMP_CONF_FILE

  ReplaceFile $CONF_FILE $TMP_CONF_FILE

  rm -f $SRDS_LDAP_CURRENT/$2

  DestroyBeforeFile $CONF_FILE
  
  return $STATUS
}

UpdateSchema() {
  typeset STATUS=0

  print "\nUpdating $SRDS_PROD_NAME schema ..."

  AppendAndCopySchema utdsd.oc.conf utdsd.oc.ut.conf
  AppendAndCopySchema utdsd.at.conf utdsd.at.ut.conf

  return $STATUS
}

DowndateSchema() {
  typeset STATUS=0

  print "\nRemoving Sun Ray related portions of $SRDS_PROD_NAME schema ..."

  UnappendAndRmSchema utdsd.oc.conf utdsd.oc.ut.conf
  UnappendAndRmSchema utdsd.at.conf utdsd.at.ut.conf

  return $STATUS
}

UpdateAcls() {
  typeset STATUS=0
  typeset CONF_FILE="$SRDS_LDAP_CURRENT/utdsd.acl.conf"

  print "\nUpdating $SRDS_PROD_NAME ACL's ..."

  CreateBeforeFile $CONF_FILE

  DeleteUTEntry $CONF_FILE >$TMP_CONF_FILE

  sed '/^access /,$d' $TMP_CONF_FILE >$TMP_INSERT_FILE
  #
  # delete from the first "access" line to the last line

  SubstituteMacros $UT_TEMPLATE_LDAP/utdsd.acl.conf >>$TMP_INSERT_FILE

  sed -n '/^access /,$p' $TMP_CONF_FILE >>$TMP_INSERT_FILE
  #
  # only print from the first "access" line to the last line

  ReplaceFile $CONF_FILE $TMP_INSERT_FILE
  
  return $STATUS
}

DowndateAcls() {
  typeset STATUS=0
  typeset CONF_FILE="$SRDS_LDAP_CURRENT/utdsd.acl.conf"

  if ! $FORCE ; then
     print "\nRemoving Sun Ray related portions of $SRDS_PROD_NAME ACL's ..."
  fi

  DeleteUTEntry $CONF_FILE >$TMP_CONF_FILE
  ReplaceFile $CONF_FILE $TMP_CONF_FILE
  DestroyBeforeFile $CONF_FILE
  
  return $STATUS
}

CreateDatastoreConfig() {
  typeset STATUS=0

  print "\nCreating $SRDS_PROD_NAME Datastore ..."

  CreateBeforeFile $DS_CONF_FILE

  DeleteUTEntry $DS_CONF_FILE >$TMP_CONF_FILE
  SubstituteMacros $UT_TEMPLATE_LDAP/utdsd.conf >${TMP_CONF_FILE}_1

  InsertFile $TMP_CONF_FILE ${TMP_CONF_FILE}_1
  /bin/rm -f ${TMP_CONF_FILE}_1 2>/dev/null 1>&2
  ReplaceFile $DS_CONF_FILE $TMP_CONF_FILE
  SetUTFilePerms $DS_CONF_FILE

  mkdir -p $VAR_OPT_LDAP_DBM_UT

#
# when configuring SRDS during the upgrade, make sure that replog file
# are more recent than the configuration file (utdsd.conf). Otherwise,
# this file will be deleted when restarting SundDS services.
  if [[ $SRDS_UPGRADE_FLAG = "YES" && \
        -s ${VAR_OPT_LDAP_REPLOG}/utpushd.replog ]]; then
     touch ${VAR_OPT_LDAP_REPLOG}/utpushd.replog
  fi
  
  return $STATUS
}

DestroyDatastoreConfig() {
  typeset STATUS=0

  if ! $FORCE ; then
     print "\nRemoving $SRDS_PROD_NAME Datastore ..."
  fi

  DeleteUTEntry $DS_CONF_FILE >$TMP_CONF_FILE

  ReplaceFile $DS_CONF_FILE $TMP_CONF_FILE
  chmod 660 $DS_CONF_FILE

  DestroyBeforeFile $DS_CONF_FILE
  
  return $STATUS
}

RestartSRDS() {
  typeset STATUS=0

  print "\nRestarting $SRDS_PROD_NAME ..."

  /etc/init.d/utds stop
  /etc/init.d/utds start
  
  return $STATUS
}


# remove "Corona" name from the utmodel attribute
CoronaNameChange()
{
	SUBTREE="utname=desktops,utname=${HOSTNAME},o=v1,${ROOTENTRY}"
	ldapsearch -p $LDAP_PORT -b "$SUBTREE" "utmodel=corona*" dn | while read dn
	do
		if [ -z $dn ]
		then
			continue
		fi
		/usr/bin/ldapmodify -p $LDAP_PORT -D "$ROOTDN" \
				-w $ROOTPW <<-! 2>/dev/null 1>&2
		dn: $dn
		changetype: modify
		delete: utmodel

		!
	done
}

CheckPolicyString()
{

	POLICYSTR=$(/opt/SUNWut/sbin/utglpolicy \
	    | sed -n 's,^/opt/SUNWut/sbin/utpolicy,,p' \
	    2>/dev/null)
	if [ ! -z $POLICYSTR ]
	then
		/opt/SUNWut/sbin/utglpolicy $POLICYSTR > /dev/null 2>&1
	fi
}


LoadDatastore()
{

  typeset STATUS=0
  typeset -i newLdapEntries=0
  typeset S="ldapadd -p $LDAP_PORT -D $ROOTDN"

  TMP_MODS_FILE="${VAR_OPT_UT}/tmp/ldap.mods.tmp"

  # Break up ldap.mods into chunks and search before adding
  # each defined LDAP base entry.

  if ! $FORCE ; then
     print "\nLoading $SRDS_PROD_NAME ..."
     print "\nExecuting '$S' ..."
  fi

  while read ldifLine
  do
     ENTRY_EXISTS=""
     if [[ -z $ldifLine && -f $TMP_MODS_FILE ]]
     then
	 # Pull out the DN value for each base entry

         DN_VALUE=$(SubstituteMacros $TMP_MODS_FILE |\
         nawk ' $1~"dn:" { print $2}' | sed -e 's/ 	//g' )

	 if [[ -z $DN_VALUE ]]; then
	    rm -f $TMP_MODS_FILE
	    continue
         fi

	 # Search for existing base entry
         ENTRY_EXISTS=$(/usr/bin/ldapsearch -p $LDAP_PORT \
                         -b $DN_VALUE -s base 'objectclass=*' 2>/dev/null) 

	 if [[ -z $ENTRY_EXISTS ]]; then
            SubstituteMacros $TMP_MODS_FILE |
            /usr/bin/ldapadd -p $LDAP_PORT -D "$ROOTDN" -w $ROOTPW
            (( newLdapEntries +=1 ))
	 else
	     rm -f $TMP_MODS_FILE
	     continue
	 fi

	 rm -f $TMP_MODS_FILE
     else
         echo $ldifLine >> $TMP_MODS_FILE
     fi

  done < $MODS_FILE

  if [[ $newLdapEntries -gt 0 ]]; then
    print "\nAdded $newLdapEntries new LDAP entries." 
  fi

  return $STATUS
}


UnloadDatastore() {
  typeset STATUS=0

  print "\nUnloading $SRDS_PROD_NAME Datastore ..."

  rm -rf $VAR_OPT_LDAP_DBM_UT
  
  return $STATUS
}


ConfigUtadmin() {
  typeset STATUS=0
  typeset CONF_FILE="utadmin.conf"
  typeset PW_FILE="utadmin.pw"
  typeset FILE MODE

  print "\nCreating $UT_PROD_NAME Configuration ..."

  for FILE in $CONF_FILE $PW_FILE; do
    case "$FILE" in
      $PW_FILE) 
		if ! $SKIP_SRDS ; then
		   print "$UTPASSWD" | $UTA_BASEDIR/sbin/utpw -f >/dev/null 2>&1
		fi  ;;
      *)        SubstituteMacros $ETC_OPT_UT/$FILE.template >$ETC_OPT_UT/$FILE;;
    esac

    case "$FILE" in
      $PW_FILE) chown root:$UTADMIN_GROUP $ETC_OPT_UT/$FILE;;
      *) chown root:sys $ETC_OPT_UT/$FILE;;
    esac

    case "$FILE" in
      $PW_FILE) MODE="660";;
      *)        MODE="644";;
    esac
    chmod $MODE $ETC_OPT_UT/$FILE
  done

  return $STATUS
}

PromptForKioskParameters() {

	if [[ -e $USER_CONF ]]
       	then
		UT_KIOSK=yes
        	if ReplyIsYes "\nPrevious Controlled Access Mode configuration exists.\nDo you wish to preserve it?"
              	then
                    	return
            	else
                  	CONF_CHANGED=true
              	fi
     	else
		if ! ReplyIsNo "\nConfigure Controlled Access Mode?"; then
          		CONF_CHANGED=true
			UT_KIOSK=yes
		else
			return
		fi
     	fi

	print ""
                
      	UT_PREFIX_OK=false
                
     	while ! $UT_PREFIX_OK
     	do
		print -n "Enter user prefix [$DEFAULT_UT_PREFIX]: "
              	read -r
            	case "$REPLY" in
            		"") UT_PREFIX="$DEFAULT_UT_PREFIX"
               		    UT_PREFIX_OK=true;;
              		*)
                    		if IsValidCAMUserPrefix $REPLY ; then
                         		UT_PREFIX_OK=true 
                             		UT_PREFIX="$REPLY"
                      		else
                           		print -n "User prefix must be alphanumeric and no more than four characters"
                             		print -n "\nRe-"
                      		fi
                                          
                	;;
             	esac
    	done
                
	print ""

    	UT_IDSTART_OK=false
                
     	while ! $UT_IDSTART_OK
      	do
		print -n "Enter userID range start [$DEFAULT_UT_IDSTART]: "
             	read -r
             	case "$REPLY" in
                  	"") UT_IDSTART="$DEFAULT_UT_IDSTART"
                            UT_IDSTART_OK=true;;
                       	*)
                     		if IsValidInteger $REPLY && (( $REPLY > 100 )); then
                       			UT_IDSTART_OK=true 
                                      	UT_IDSTART="$REPLY"
                            	else
                                    	print -n "UserID's must start after 100 and must be an integer"
                                     	print -n "\nRe-"
                              	fi
                     	;;
           	esac
      	done

	print ""
                
   	UT_IDCOUNT_OK=false
                
     	while ! $UT_IDCOUNT_OK
      	do
		print -n "Enter number of users [$DEFAULT_UT_IDCOUNT]: "
              	read -r
              	case "$REPLY" in
             		"") UT_IDCOUNT="$DEFAULT_UT_IDCOUNT"
                    	    UT_IDCOUNT_OK=true;;
             		*)
               			if IsValidInteger $REPLY && (( $REPLY >= 1 )); then
                                    	UT_IDCOUNT_OK=true 
                                     	UT_IDCOUNT="$REPLY"
                             	else
                                  	print -n "Number of users must be an integer greater than 0"
                                    	print -n "\nRe-"
                            	fi
                   	;;
             	esac
     	done

	print ""
}

ConfigKiosk() {		
	cp $KIOSK_CONF_TEMPLATE $KIOSK_CONF
	/etc/init.d/bbinit  start
	/etc/init.d/bbutdev start
	/opt/SUNWut/lib/create_files
	/var/opt/SUNWut/kiosk/browserprefs
	RemoveKioskConfig
	CreateKioskConfig
}

CreateKioskConfig() {
	RemoveStaleUsers
	STATUS=$?

	if [[ $STATUS = 0 ]]; then
		 print "\nAdding new Controlled Access Mode configuration ...\n"
         	/opt/SUNWbb/bin/bbmkuser -c $UT_PREFIX $UT_IDSTART $UT_IDCOUNT
		RET=$?
		if [[ $RET != 0 ]]; then
			PrintKioskAddErrorMsg
		fi
	fi
}

RemoveKioskConfig() {

	print "\nChecking for previous Controlled Access Mode configuration ...\n"
      	/opt/SUNWbb/bin/bbmkuser -d
	RemoveStaleUsers
}

RemoveStaleUsers() {
	typeset STATUS=1

	stale_users=`/opt/SUNWbb/bin/bbmkuser -t 2> /dev/null`
	if [[ $? = 0 ]]; then
		return 0
	fi
	/opt/SUNWbb/bin/bbmkuser -r
	if [[ $? != 0 ]]; then
		PrintKioskRemoveErrorMsg
	else
       		STATUS=0
       	fi
        
	return $STATUS
}

PrintKioskAddErrorMsg() {
cat <<-!

	Controlled Acccess Mode configuration failed!  Please remove all 
	users with the comment field 'ControlledAccessUser' from the 
	/etc/passwd file and run utconfig to create a Controlled Access 
	Mode configuration.
	!
}

PrintKioskRemoveErrorMsg() {
cat <<-!
 
	Removal of Controlled Access Mode configuration has failed!
	Please remove all users with the comment field 'ControlledAccessUser'
	from the /etc/passwd file before attempting to configure
	Controlled Access Mode again. 
	!
}

UnconfigKiosk() {
  RemoveKioskConfig
  rm -rf /var/opt/SUNWut/kiosk/config/*
  cat /dev/null > /var/opt/SUNWut/kiosk/preferences
  cat /dev/null > /var/opt/SUNWut/kiosk/useapps
  cat /dev/null > /var/opt/SUNWut/kiosk/availapps
  rm -f $KIOSK_CONF
}	

UnconfigUtadmin() {
  typeset STATUS=0
  typeset CONF_FILE="utadmin.conf"
  typeset PW_FILE="utadmin.pw"

  print "\nRemoving $UT_PROD_NAME Configuration ..."

  for FILE in $CONF_FILE $PW_FILE; do
    rm -f $ETC_OPT_UT/$FILE
  done

  return $STATUS
}

ConfigSRDS() {
  typeset STATUS=0

  UpdateSchema
  UpdateAcls

  CreateDatastoreConfig
  touch ${UT_SRDS_ETC}/current/utdsd.run
  SyncEtcServices

  RestartSRDS

  LoadDatastore

  return $STATUS
}


UnconfigSRDSConf() {

  DestroyDatastoreConfig
  DowndateAcls
  DowndateSchema
}


UnconfigSRDS() {
  typeset STATUS=0

  /etc/init.d/utds stop

  UnloadDatastore
  UnconfigSRDSConf
  /bin/rm ${UT_SRDS_ETC}/current/utdsd.run 2> /dev/null

  /etc/init.d/utds start

  return $STATUS
}

# Import XConfig preferences from flat-file legacy config files into LDAP 

ImportUTPrefs() {

   UT_PREF_DIR=/var/opt/SUNWut/preferences
   typeset STATUS=0
   if [[ ! -d $UT_PREF_DIR ]]; then
	return
   fi

   PREF=$(find $UT_PREF_DIR ! -name "DEFAULT" -a -type f -print)

   # For each preference file build up the utxconfig command
   # invocation to import the preferences into LDAP

   print "Importing XConfig settings into LDAP"

   for cfg in $PREF
   do
      tokenID=$(basename $cfg)
      dirpath=$(dirname $cfg)
      tokenType=$(basename $dirpath)
      importPrefCmd="${UTO_BASEDIR}/bin/utxconfig -t \
	${tokenType}.${tokenID} -c ${cfg}"

      eval $importPrefCmd

      if [[ $? -ne 0 ]]; then
         STATUS=1 
      fi
   done

   # Handle the special case, DEFAULT file

   if [[ -f ${UT_PREF_DIR}/DEFAULT ]]; then
      ${UTO_BASEDIR}/bin/utxconfig -a -c ${UT_PREF_DIR}/DEFAULT
      if [[ $? -ne 0 ]]; then
         STATUS=1 
      fi
   fi

   # Summary report on any utxconfig failures encountered.
   if [[ $STATUS -ne 0 ]]; then
      print "Some problems encountered while attempting to add utxconfig preferences into LDAP"
   fi
}

RemoveOldBackupFiles() {

  # Remove backup files generated during running of utconfig.

  GMSIGFILEPATH=`eval get_current_gmSignaturefile`

  [[ -f ${GMSIGFILEPATH}.bak ]] && rm -f ${GMSIGFILEPATH}.bak
  [[ -f "$AUTHPROPS.bak" ]] && rm -f $AUTHPROPS.bak
}

ConfigDbm() {
  if [[ ! -d $DBM_FILES_PATH ]]; then
    mkdir -m 755 -p $DBM_FILES_PATH
  fi
  chgrp $UTADMIN_GROUP $DBM_FILES_PATH

  if [[ ! -f $DBM_FILES_PATH/dstatus.dir ]]; then
    cat /dev/null > $DBM_FILES_PATH/dstatus.dir
  fi
  chgrp $UTADMIN_GROUP $DBM_FILES_PATH/dstatus.dir
  chmod 664 $DBM_FILES_PATH/dstatus.dir

  if [[ ! -f $DBM_FILES_PATH/dstatus.pag ]]; then
    cat /dev/null > $DBM_FILES_PATH/dstatus.pag
  fi
  chgrp $UTADMIN_GROUP $DBM_FILES_PATH/dstatus.pag
  chmod 664 $DBM_FILES_PATH/dstatus.pag

  if [[ ! -f $DBM_FILES_PATH/ustatus.dir ]]; then
    cat /dev/null > $DBM_FILES_PATH/ustatus.dir
  fi
  chgrp $UTADMIN_GROUP $DBM_FILES_PATH/ustatus.dir
  chmod 664 $DBM_FILES_PATH/ustatus.dir

  if [[ ! -f $DBM_FILES_PATH/ustatus.pag ]]; then
    cat /dev/null > $DBM_FILES_PATH/ustatus.pag
  fi
  chgrp $UTADMIN_GROUP $DBM_FILES_PATH/ustatus.pag
  chmod 664 $DBM_FILES_PATH/ustatus.pag

}

ConfigLog() {

  # Configure admin log. New with Sun Ray 1.1 

  typeset TMPFILE_LOG=${TMP_FILE}.log
  typeset UTO_LIB=${UTO_BASEDIR}/lib

  ${UTO_LIB}/utlog -a \
	-s all -f local1.info -d ${VAR_OPT_UT}/log/admin_log -z;

  if [[ $? -ne 0 ]]; then
	print "Problem encountered while attempting to enable admin syslog."
	return 1
  fi

  # Update log rotation task.
  (
     crontab -l root 2>/dev/null 
     print "33 3 * * * $UTO_LIB/utlog -c -d ${VAR_OPT_UT}/log/admin_log 2>/dev/null 1>/dev/null";
  ) > $TMPFILE_LOG

 crontab $TMPFILE_LOG
 rm -f $TMPFILE_LOG 2>/dev/null;

}

UnconfigGroup() {
  GMSIGFILEPATH=`eval get_current_gmSignaturefile`

  rm -f $GMSIGFILEPATH
  touch $GMSIGFILEPATH
  chmod 600 $GMSIGFILEPATH

} 

UnconfigDbm() {
  if [[ -d $DBM_FILES_PATH ]]; then
    rm -rf $DBM_FILES_PATH
  fi

  if [[ -f $DBM_FILES_PATH/dstatus.dir ]]; then
    rm -f $DBM_FILES_PATH/dstatus.dir
  fi

  if [[ -f $DBM_FILES_PATH/dstatus.pag ]]; then
    rm -f $DBM_FILES_PATH/dstatus.pag
  fi

  if [[ -f $DBM_FILES_PATH/ustatus.dir ]]; then
    rm -f $DBM_FILES_PATH/ustatus.dir
  fi

  if [[ -f $DBM_FILES_PATH/ustatus.pag ]]; then
    rm -f $DBM_FILES_PATH/ustatus.pag
  fi

}

ConfigSmartCard() {

  if [[ -d $SMARTCARD_FILES_PATH ]]; then
      chgrp $UTADMIN_GROUP $SMARTCARD_FILES_PATH
  else
      Note "Smartcard config file directory doesn't exist"
  fi

  if [[ -f $SMARTCARD_FILES_PATH/probe_order.conf ]]; then
     chgrp $UTADMIN_GROUP $SMARTCARD_FILES_PATH/probe_order.conf
  else
      Note "Smartcard config probe order configuration file doesn't exist"
  fi
}

ConfigGroup() {
  if [[ "$UT_GROUP" == "yes" ]]; then
	# all group members must have the same signature 
        groupsig_MSG
        $UTO_BASEDIR/sbin/utgroupsig
  else
	# group of one needs a unique signature
	generate_groupsig
  fi  
}

# Defaults to Yes
ReplyIsYes() {
  while true; do
    print -n "$* ([y]/n)? "
    read
    case "$REPLY" in
      "" | [yY]*) return 0;;
      [nN]*)      return 1;;
    esac
  done
}

# Defaults to No
ReplyIsNo() {
  while true; do
    print -n "$* (y/[n])? "
    read
    case "$REPLY" in
      "" | [nN]*) return 0;;
      [yY]*)	  return 1;;
    esac
  done
}


InitKioskVars() {
	DEFAULT_UT_PREFIX="utcu"
	DEFAULT_UT_IDSTART="150000"
	DEFAULT_UT_IDCOUNT="25"
	UT_KIOSK=no		# UT_KIOSK tells you if CAM is configured, un-configured, or preserved
	CONF_CHANGED=false	# CONF_CHANGED tells you if CAM configuration has been changed.

	return 0
}	

# XXX REview the SWS bits that might be necessary for 
# non-upgrade auto configure.
DoAutoConfig() {
  FORCE=true

  # Extract password
  UTPasswordExists && PASSWD=$(cat ${ETC_OPT_UT}/utadmin.pw 2>&- | 
    tr [a-z][A-Z] [n-z][a-m][N-Z][A-M])

  CreateUTTempDir

  PromptForParameters 

  # Normally done as part of SRAS config.
  # However it may be needed in SunDs silent config.
  ConfigUtadmin

  if [[ ! -f "${VAR_OPT_UT}/log/admin_log" && -f /var/dhcp/dhcptab ]]; then
       ConfigLog
  fi
 
  # This section of code applies to administration upgrade.
  # Preserve existing password before unlocking datastore with temporary pw

  # Set upgrade flag
  SRDS_UPGRADE_FLAG="YES"

  SAVED_CRYPTDPW=$(nawk '/^# SUNWut begin/ {found=1}\
     found==1 && $1=="rootpw" {print $2}' $DS_CONF_FILE)
  
  # A temporary password is required to gain privilege to
  # unlock datastore during upgrade.
  ROOTPW="UpgradePW"
  CRYPTD_ROOTPW="$(EncryptPasswd "$ROOTPW")"


  # Strip away 'ut' specific SRDS configuration
  UnconfigSRDSConf 
  # Configure the schema + LDAP base entries
  ConfigSRDS
  ConfigDbm
  # check for utpolicy string in the LDAP policystring attribute.
  # This is added to fix a 1.1 bug which is carried forward during
  # the upgrade.
  CheckPolicyString
  CoronaNameChange

  # shutdown SRDS for the remaining operations
  /etc/init.d/utds stop

  # Re-index the utgroupid and utgrouptype attributes.
  # This is needed because these 2 attributes were mis-indexed in 1.x.
  # We only re-index if the database files for both utgroupid and
  # utgrouptype do not exist.
  if [ ! -f ${VAR_OPT_LDAP_DBM_UT}/utgroupid.dbb -o \
	! -f ${VAR_OPT_LDAP_DBM_UT}/utgrouptype.dbb ]; then
     /opt/SUNWut/srds/lib/utidxgen -a utGroupId utGroupType
  fi

  # To revert to orginal rootPW we need to reconfigure utdsd.conf

  CRYPTD_ROOTPW="$SAVED_CRYPTDPW"
  DestroyDatastoreConfig

  CreateDatastoreConfig

  ConfigSmartCard

  if [[ ! -s "${ETC_OPT_UT}/gmSignature" ]]; then
    UT_GROUP=no
    ConfigGroup
  fi

  /etc/init.d/utds start

  ImportUTPrefs

  # end of the upgrade, reset the flag.
  SRDS_UPGRADE_FLAG="NO"

  return 0
}

DoConfig() {
  typeset STATUS=0

  CONFIG_SWS=false

  print "\nConfiguration of $UT_PROD_NAME Software"

  CreateUTTempDir

  PromptForParameters

  if ReplyIsNo "\nConfigure this server for a failover group?"; then
    UT_GROUP=no
  else
    UT_GROUP=yes
  fi

  print "\nAbout to configure the following software products:"

  cat <<-!

	$SRDS_PROD_NAME $SRDS_VERSION
	    Hostname: $THIS_HOST
	    $UT_ROOT_S entry: $ROOTENTRY
	    $UT_ROOT_S name: $ROOTNAME
	    Sun Ray $ROOTNAME admin password: (not shown)
	    $SRDS_ROOTDN_S: $ROOTDN
	!
   
  if $CONFIG_SWS; then
    cat <<-!

	$SRAS_PROD_NAME $SRAS_VERSION
	    $UT_ADMIN_WEB_S instance name: $UT_INST
	    $UT_ADMIN_WEB_S port number: $UT_PORT
	    Remote server administration: $REMOTE_ENABLE_S
	    Secure Socket Layer: $SSL_ENABLE_S
	    CGI username: $CGI_USER
	!
  fi

  print "\n$UT_PROD_NAME $UT_VERSION"
  print "    Failover group: $UT_GROUP"
  print "    Controlled Access Mode: $UT_KIOSK"

  if $CONF_CHANGED;then   
    cat <<-!

	Controlled Access Mode Configuration
	    User prefix: $UT_PREFIX
	    First userID number: $UT_IDSTART
	    Number of users: $UT_IDCOUNT
	!
  fi

  if ! $FORCE && ! ReplyIsYes "\nContinue"; then
    CleanupAndExit 0
  fi

  if ! $SKIP_SRDS ; then
     RestoreSRDSConf
     ConfigSRDS
  fi

  ConfigUtadmin

  if $CONFIG_SWS; then
    ConfigSWS
  fi

  ConfigDbm
  ConfigSmartCard

  ConfigGroup

  RestartSRDS

  if [[ $SSL_ENABLE_S == Enabled ]]; then
    ssl_enabled_MSG
  fi

  # Determine current auth policy settings
  CURR_POLICY=$(/opt/SUNWut/sbin/utpolicy | nawk '/^#/ {next} {print}')
 
  # Determine if failover group enabled.
  GROUP_POLICY_SET=$(echo $CURR_POLICY | grep "\-g")

  if [[ "$UT_GROUP" == "yes" && -z $GROUP_POLICY_SET ]] ;then
    eval "/opt/SUNWut/sbin/utpolicy $CURR_POLICY -g >/dev/null 2>&1"
  else 
    eval "/opt/SUNWut/sbin/utpolicy $CURR_POLICY >/dev/null 2>&1"
  fi

  POLICY=$(/opt/SUNWut/sbin/utpolicy | nawk '/^#/ {next} {print}')

  /opt/SUNWut/lib/utgenpolicy $POLICY >/dev/null 2>&1

  if $CONF_CHANGED;then
      ConfigKiosk
  fi

  /opt/SUNWut/sbin/utkiosk -i kiosk

  utpolicy_MSG

  print "\nConfiguration of $UT_PROD_NAME has completed.  Please check"
  print "the log file, $LOGFILE, for errors."
  
  return $STATUS
}

DoUnconfig() {
  typeset STATUS=0

  UNCONFIG_SWS=false
  SWS_ALREADY_CFG=false

  print "\nUn-configuration of $UT_PROD_NAME Software"

  if grep '^pu.._replica' $DS_CONF_FILE >/dev/null 2>&1
  then      
    Fatal "LDAP Replication is enabled. You must firstly disable using utreplica -u"
  fi

  InitSWSVars
  # Determine Webserver config files.
  SWSInfo

  if SRASInstalled && SRASVersion $SRAS_VERSION && $SWS_ALREADY_CFG; then
      UNCONFIG_SWS=true
      DELETE_CGI_USER=true
  fi

  print "\nAbout to un-configure the following software products:"

  print "\n$SRDS_PROD_NAME $SRDS_VERSION"

  if $UNCONFIG_SWS; then
    print "$SRAS_PROD_NAME $SRAS_VERSION"
  fi

  print "$UT_PROD_NAME $UT_VERSION"

  if ! $FORCE && ! ReplyIsYes "\nContinue"; then
    CleanupAndExit 0
  fi

  UnconfigGroup

  $UTO_BASEDIR/lib/utgenpolicy -a -g -z both -t clear > /dev/null 2>&1 

  UnconfigDbm
  UnconfigUtadmin
  if $UNCONFIG_SWS; then
    UnconfigSWS
  fi

  if PreviousUTDataStore ; then
      UnconfigSRDS
  fi

  RemoveOldBackupFiles

  utpolicy_MSG

  UnconfigKiosk

  print "\nUn-configuration of $UT_PROD_NAME has completed.  Please check"
  print "the log file, $LOGFILE, for errors."
  
  return $STATUS
}


get_current_gmSignaturefile(){
	typeset gmSignatureFile=""
	gmSignatureFile=$(sed -n '
		s/^[ 	]*//
		s/[ 	]*$//
		s/#.*$//
		s/[ 	][ 	]*=[ 	][ 	]*/=/
		s/^gmSignatureFile=\(.*\)$/\1/p
		' $AUTHPROPS)
	# a reasonable default just in case	
	print ${gmSignatureFile:-"$ETC_OPT_UT/gmSignature"}
}


generate_groupsig() {
	typeset GMSIGFILEPATH=""
	typeset UMASK_ORIG=$(umask)
	# set umask to create with correct permissions
	umask $UMASK_ROOT

	GMSIGFILEPATH=`eval get_current_gmSignaturefile`
	
	# We're going to create a unique new gmSignature
	# save it if there is one there already
	if [[ -s ${GMSIGFILEPATH:-} ]]; then
	   mv $GMSIGFILEPATH $GMSIGFILEPATH.bak
	   print "\nSaving $GMSIGFILEPATH to $GMSIGFILEPATH.bak"
	fi
	
	# make signature  unique
	echo 'gmSignature automatically generated'    > $GMSIGFILEPATH 
	echo $THIS_HOST  `date` `hostid`   >> $GMSIGFILEPATH 

	# generate a unique signature 
	if [[ -s /dev/random ]]; then
		DEVICE=/dev/random
		OFFSET=1
		SEEK=skip
	else
	# we don't have /dev/random so we'll get the bits
	# out of swap offset by the free space 
		DEVICE=`swap -l | nawk ' NR==2 { print $1 }' `
		BLOCKS=`swap -l | nawk ' NR==2 { print $4 }'`
		OFFSET=`swap -l | nawk ' NR==2 { print $5 }'` 
		# if swap is unused then use blocks%proc_id as offset
		[[ $BLOCKS = $OFFSET ]] && (( (OFFSET%=$$) ))
		SEEK=iseek
	fi

	dd if=$DEVICE bs=1k count=1 $SEEK=$OFFSET >> $GMSIGFILEPATH 2> /dev/null
	#make doubly sure that ownership and perms are correct
	chown root:root $GMSIGFILEPATH
	chmod 400 $GMSIGFILEPATH
	umask $UMASK_ORIG
	print "\nUnique \"$GMSIGFILEPATH\" has been generated."
}


# function used by utpolicy to change an auth.props entry takes 
# "key=value" argument -- modified to make the change in place
editAuthProps() {
	typeset kv=${1}
	typeset key=${kv%=*}
	if [[ ! -w $(dirname $AUTHPROPS) ]]
	then
		print -u2 Cannot update $AUTHPROPS
		return 1
	fi
	[[ -f "$AUTHPROPS.bak" ]] && rm -f $AUTHPROPS.bak
	[[ -f "$AUTHPROPS" ]] && cp -p $AUTHPROPS $AUTHPROPS.bak
	chmod 644 $AUTHPROPS
	# the "-" after ed tells ed that this is not interactive
	ed - $AUTHPROPS <<-! 2>/dev/null 1>&2
	g/^$key.*/s//$kv/
	.
	w
	q
	!
	return $?
}


#
# function to get the LDAP port number from the utdsd.ini file
#
get_ldap_port() {
	sed -n -e 's/^LdapPort=//p' ${SRDS_LDAP_CURRENT}/utdsd.ini
}

#
# Messages
#
groupsig_MSG(){
cat <<-!

You have chosen to configure this server for a failover group.

All servers in a failover group must share a unique signature, 
which is a string of 8 or more characters where at least two 
characters are letters and at least one is not.
 
!
}

utpolicy_MSG(){
cat <<-!
***********************************************************
The current policy has been modified.  You must restart the 
authentication manager to activate the changes. 
***********************************************************

!
}


#
# main {
#

# UMASKS
UMASK_ROOT=066
UMASK_WORLD=022

umask $UMASK_WORLD

OPTSTR=":ufs:"
PROGRAM_OPTS="[-u]"

MODE="configure"
FORCE=false

while getopts $OPTSTR OPT; do
  case "$OPT" in
    u) MODE="unconfigure";;
    f) FORCE=true;;
    s) if [ "$OPTARG" == "silent" ]; then
         MODE="autoconfigure"
       fi;;
   \?) Usage;;
  esac
done
shift $(($OPTIND - 1))

if (( $# != 0 )); then
  Usage
fi

CheckUidIsZero

# Source the SRAS library.
. /opt/SUNWut/lib/support_lib/sras_config

UT_PROD_NAME="Sun Ray server"
UT_VERSION="2.0"

if ! UTInstalled; then
  Fatal "$UT_PROD_NAME is not installed on this host"
fi

UTA_BASEDIR="$(pkginfo -r SUNWuta)/SUNWut"
UTO_BASEDIR="$(pkginfo -r SUNWuto)/SUNWut"
UT_TEMPLATE_LDAP="$UTA_BASEDIR/etc/template/ldap"

SRDS_PROD_NAME="Sun Ray Data Store"
SRDS_VERSION="1.0"
SRDS_PACKAGE="SUNWutdso"

if ! SRDSInstalled; then
  Fatal "$SRDS_PROD_NAME is not installed on this host"
elif ! SRDSVersion $SRDS_VERSION; then
  Fatal "version $SRDS_VERSION of $SRDS_PROD_NAME is not installed on this host"
elif SRDSInstallPartial; then
  Fatal "$SRDS_PROD_NAME version $SRDS_VERSION is only partially installed"
fi

SRDS_BASEDIR="$(pkginfo -r $SRDS_PACKAGE)"

LCL_PROD_NAME="LDAP Client Libraries"
LCL_PACKAGE="SUNWlldap"

if ! LdapClientInstalled; then
  Fatal "$LCL_PROD_NAME is not installed on this host"
elif LdapClientInstallPartial; then
  Fatal "$LCL_PROD_NAME is only partially installed"
fi

UT_ROOT_S="Sun Ray root"
DEFAULT_ROOTENTRY="o=utdata"

ROOTENTRY=""
ROOTNAME=""
ROOTPW=""
CRYPTD_ROOTPW=""
SDS_ROOTDN_S="SunDS 'rootdn'"
DEFAULT_ROOTDN=""   # gets assigned later, constructed with $ROOTENTRY
ROOTDN=""
UTPASSWD=""
VERSIONENTRY="1"


UTCONF_FILE=${ETC_OPT_UT}/"utadmin.conf"
MODS_FILE="$UT_TEMPLATE_LDAP/ldap.mods"
VAR_OPT_LDAP_DBM_UT="/var/opt/SUNWut/srds/dbm.ut"
VAR_OPT_LDAP_REPLOG="/var/opt/SUNWut/srds/replog"
SRDS_UPGRADE_FLAG="NO"

SRDS_LDAP_DEFAULT="/etc/opt/SUNWut/srds/default"
SRDS_LDAP_CURRENT="/etc/opt/SUNWut/srds/current"
SRDS_LDAP_HTML="$SRDS_BASEDIR/SUNWut/srds/html"
DS_CONF_FILE="$SRDS_LDAP_CURRENT/utdsd.conf"

LDAP_PORT=$(get_ldap_port)

SRAS_PROD_NAME="Sun Ray Admin Server"
SRAS_VERSION="2.0"

EN_DOC_DIR="/opt/SUNWut/doc/en/html"
JA_DOC_DIR="/opt/SUNWut/doc/ja/html"

LOCAL_EN_DOC_DIR="lib/locale/en_US/docdir"
LOCAL_FR_DOC_DIR="lib/locale/fr/docdir"
LOCAL_JA_DOC_DIR="lib/locale/ja/docdir"
LOCAL_ZH_DOC_DIR="lib/locale/zh/docdir"

LOGFILE="/var/adm/log/${PROGRAM_ID}.$(date '+%Y_%m_%d_%H:%M:%S').log"

print "# Script: ${PROGRAM_ID}\tVersion: 2.0_37.b,REV=2002.12.19.07.46\n" > $LOGFILE



 # When upgrading an existing directory the hostname
 # used to re-build the relavent SRDS files should
 # be derived from the original hostname embedded in
 # the LDAP directory and *not* obtained from uname


if [[ -f $UTCONF_FILE ]]; then
   DSHOST=$(nawk -F= '$1~"admin.subtree" {print $3}' $UTCONF_FILE|\
    nawk -F, '{print $1}')
   if [[ -n $DSHOST ]]; then
	HOSTNAME="$DSHOST"
   fi
else
   HOSTNAME=$(uname -n)
fi

#  When upgrade from 1.1, should preserve the suffix, which could be
#  customized during 1.1 utconfig.

if [[ -f $DS_CONF_FILE ]]; then
   ROOTENTRY=$(nawk '/^# SUNWut begin/ {found=1}\
	found==1 && $1=="suffix" {print $2}' $DS_CONF_FILE | sed 's/\"//g')
fi
if [[ -z $ROOTENTRY ]]; then
   ROOTENTRY="$DEFAULT_ROOTENTRY"
fi

case "$MODE" in
  configure)   	   DoConfig     2>&1 |tee -a $LOGFILE;;
  autoconfigure)   DoAutoConfig ;; # No explicit logfile in silent mode.
  unconfigure)     DoUnconfig   2>&1 |tee -a $LOGFILE;;
esac

CleanupAndExit 0

# }
