#!/bin/ksh -p
#
# ident "@(#)autoconfig.ksh	1.7 02/07/22 SMI"
#
# Copyright 1999-2001 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"

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=/etc/http/utadmin.httpd.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 $?
}

EnglishDocsInstalled() {
  pkginfo -q SUNWeutdo
  return $?
}

JapaneseDocsInstalled() {
  pkginfo -q SUNWjutdo
  return $?
}

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

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

SunDSInstalled() {
  pkginfo -q $SDS_PACKAGE
  return $?
}

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

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

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

SWSInstalled() {
  pkginfo -q SUNWhttp
  return $?
}

SSLInstalled() {
  pkginfo -q SUNWutss SUNWutssd
  return $?
}

SWSVersion() {
  INSTALLED_VERSION="$(pkgparam SUNWhttp VERSION 2>&-)"

  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
}

SWSInfo() {
 
  # Determine SunRay admin specific webserver master
  # configuration filename.

  typeset WEB_PATH=""
  typeset WEB_CFG=""
  typeset tmp_remote=""

  # Determine webserver master configuration filename
   if [[ -f $UTCONF_FILE ]]; then
      HTTP_CFG=$(nawk -F= '$1~"admin.http.cfile" {print $2}' $UTCONF_FILE)
      HTTP_CFG=$(echo $HTTP_CFG | sed -e 's/    //g')
   fi


  # Match this with running webserver instances

  if [[ -n $HTTP_CFG && -f $HTTP_CFG ]]; then
    UT_PORT=$(nawk '$1~"port" { print $2 }' $HTTP_CFG)
    SSLENABLE=$(nawk '$1~"ssl_enable" { print $2 }' $HTTP_CFG)

     UTADMIN_MATCH=$(htserver list |\
           nawk -F: -v CFG="$HTTP_CFG" \
          '$1~"Config file" && CFG~substr($2,3) { print $2 }')

     # Now grab the admin Webserver instance name
     if [[ -n $UTADMIN_MATCH ]]; then
         SWS_ALREADY_CFG=true
         UT_INST=$(basename $UTADMIN_MATCH)
         UT_INST=${UT_INST%.httpd.conf}
     fi

     # Find the preferences file for the 'ut' webserver instance
     # and grab the CGI username.

     WEB_PATH=$(nawk '$1=="site_path" { print $2}' $HTTP_CFG)
     WEB_CFG=$(nawk '$1=="site_config" { print $2}' $HTTP_CFG)

     WEB_CFG=$(echo $WEB_CFG | sed -e 's/"//g')

     if [[ -f ${WEB_PATH}/${WEB_CFG} ]]; then
         CGI_USER=$(nawk '$1=="cgi_user" { print $2 }' ${WEB_PATH}/${WEB_CFG})
     fi

     # Grab the current remote admin

     sect_begin="# SUNWut begin"
     sect_end="# SUNWut end"
     search_string="host \*"

     tmp_remote=$(nawk '
	BEGIN {
		inSection = 0
	}

	/^'"$sect_begin"'/ {
		inSection = 1
		next
	}

	/^'"$sect_end"'/ {
		inSection = 0
        	next
        }

	/'"$search_string"'/ && inSection {
        	print $1
	}
        ' ${WEB_PATH}/conf/access.conf)

     [[ -n "$tmp_remote" ]] && REMOTE_ENABLE=$tmp_remote
  fi

}


EncryptPasswd() {
  typeset STATUS=0
  typeset JAVA=""

  if [[ -d "/usr/java1.1" ]]; then
    JAVA="/usr/java1.1"
  else
    JAVA="/usr/java"
  fi
  typeset JRE="$JAVA/bin/jre"
  typeset CLASS="COM.Sun.sunsoft.ldaps.sims.server.LDACommandManager"

  export CLASSPATH="$SDS_LDAP_HTML/lib:$SDS_LDAP_HTML:$JAVA/lib/classes.zip"
  export LD_LIBRARY_PATH="$SDS_LDAP_HTML/lib"

  print "$1" |
  $JRE -Dbasedir=$SDS_BASEDIR -classpath $CLASSPATH $CLASS

  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 != *- ]]
}


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
}

SetCGI_USER() {
  typeset STATUS=0
  typeset USERNAME_OK=false

  while ! $USERNAME_OK
  do
      print -n "Enter CGI username [$DEFAULT_CGI_USER]: "
      read -r
      case "$REPLY" in
        "") CGI_USER="$DEFAULT_CGI_USER"
            USERNAME_OK=true ;;

        *)  CGI_USER="$REPLY"
            if IsValidAlphanumeric $CGI_USER ; then
                USERNAME_OK=true
            else
		print -n "CGI Username must be alpanumeric."
            fi ;;
      esac
      print ""
  done

}

SetUT_INST() {
  typeset STATUS=0

  DEFAULT_UT_INST="utadmin"

  UT_INST_OK=false

  print -n "\n"
  while ! $UT_INST_OK
  do
     print -n "Enter $UT_ADMIN_WEB_S instance name [$DEFAULT_UT_INST]: "
     read -r
     case "$REPLY" in
        "") UT_INST="$DEFAULT_UT_INST"
            UT_INST_OK=true ;;
        *)
            if IsValidAlphanumeric $REPLY ; then
                 UT_INST_OK=true
                 UT_INST="$REPLY"
            else
		print -n "$UT_ADMIN_WEB_S instance name must be alphanumeric"
                print -n "\nRe-"
            fi

            ;;
     esac
  done


  print ""

  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 Administrator's
	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_SDS=false

  if ! $FORCE ; then
     if PreviousUTDataStore; then
              SKIP_SDS=true
     else
        SetPASSWD "UT admin"
     fi
  else
        SKIP_SDS=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

  #Retrieve current webserver settings
  SWSInfo

  if $SWS_ALREADY_CFG ; then
     if ! $FORCE && ReplyIsYes "\nPrevious Sun Ray Web Server instance found.\n" \
		"Do you wish to preserve it?" ; then
	SKIP_SWS=true
        UT_INST_SITE=/var/http/$UT_INST/websites/default_site
        HTTPCFGFILE=/etc/http/$UT_INST.httpd.conf
     elif ! $FORCE ; then
	InitSWSVars
	SWSInfo
        UnconfigSWS
        CreateUTTempDir
        SetupCgiTokens
     fi
  fi
      
  if ! $SKIP_SWS && SWSInstalled && SWSVersion $SWS_VERSION ; then
    if $FORCE || ReplyIsYes "\nConfigure $SWS_PROD_NAME $SWS_VERSION"; then
      CONFIG_SWS=true
    fi

    if $CONFIG_SWS; then
      if ! $FORCE; then
        InitSWSVars
	SetUT_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=/var/http/$UT_INST/websites/default_site
      HTTPCFGFILE=/etc/http/$UT_INST.httpd.conf
    fi
  fi

  return $STATUS
}

SubstituteMacros() {
  sed "
    s
@(ROOTENTRY)
$ROOTENTRY
g
    s
@(ROOTNAME)
$ROOTNAME
g
    s
@(HOSTNAME)
$HOSTNAME
g
    s
@(THIS_HOST)
$THIS_HOST
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 $?
}

CreateBeforeFile() {
  if [[ ! -r $1.$BEFORE ]]; then
    cp $1 $1.$BEFORE
  fi
  return $?
}

DestroyBeforeFile() {
  rm -f $1.$BEFORE
  return $?
}

CreateBeforeDir() {
  if [[ ! -d $1.$BEFORE ]]; then
    mv $1 $1.$BEFORE
  fi
  return $?
}

DeleteUTEntry() {
  sed '
    /^# SUNWut begin/,/^# SUNWut end/d
  ' $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
}

ReplaceFile() {
  typeset STATUS=0

  mv $1 $1.$$
  mv $2 $1
  rm $1.$$
  
  return $STATUS
}

AppendAndCopySchema() {
  typeset STATUS=0
  typeset CONF_FILE="$SDS_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 $SDS_LDAP_CURRENT/$2
  
  return $STATUS
}

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

  DeleteUTEntry $CONF_FILE >$TMP_CONF_FILE

  ReplaceFile $CONF_FILE $TMP_CONF_FILE

  rm -f $SDS_LDAP_CURRENT/$2

  DestroyBeforeFile $CONF_FILE
  
  return $STATUS
}

UpdateSchema() {
  typeset STATUS=0

  print "\nUpdating $SDS_PROD_NAME schema ..."

  AppendAndCopySchema dsserv.oc.conf dsserv.oc.ut.conf
  AppendAndCopySchema dsserv.at.conf dsserv.at.ut.conf

  return $STATUS
}

DowndateSchema() {
  typeset STATUS=0

  print "\nRemoving SunRay related portions of  $SDS_PROD_NAME schema ..."

  UnappendAndRmSchema dsserv.oc.conf dsserv.oc.ut.conf
  UnappendAndRmSchema dsserv.at.conf dsserv.at.ut.conf

  return $STATUS
}

UpdateAcls() {
  typeset STATUS=0
  typeset CONF_FILE="$SDS_LDAP_CURRENT/dsserv.acl.conf"

  print "\nUpdating $SDS_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/dsserv.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="$SDS_LDAP_CURRENT/dsserv.acl.conf"

  if ! $FORCE ; then
     print "\nRemoving SunRay related portions of $SDS_PROD_NAME ACL's ..."
  fi

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

CreateDatastore() {
  typeset STATUS=0

  print "\nCreating $SDS_PROD_NAME Datastore ..."

  CreateBeforeFile $DS_CONF_FILE

  DeleteUTEntry $DS_CONF_FILE >$TMP_CONF_FILE
  SubstituteMacros $UT_TEMPLATE_LDAP/dsserv.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 SunDS during the upgrade, make sure that replog file
# are more recent than the configuration file (dsserv.conf). Otherwise,
# this file will be deleted when restarting SundDS services.
  if [[ $SDS_UPGRADE_FLAG = "YES" && \
        -s ${VAR_OPT_LDAP_REPLOG}/dspushd.replog ]]; then
     touch ${VAR_OPT_LDAP_REPLOG}/dspushd.replog
  fi
  
  return $STATUS
}

DestroyDatastore() {
  typeset STATUS=0

  if ! $FORCE ; then
     print "\nRemoving $SDS_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
}

RestartSunDS() {
  typeset STATUS=0

  print "\nRestarting $SDS_PROD_NAME ..."

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


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 -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 $SDS_PROD_NAME Datastore ..."
     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=$($SDS_BASEDIR/SUNWconn/bin/ldapsearch \
                         -b $DN_VALUE -s base 'objectclass=*' 2>/dev/null) 

	 if [[ -z $ENTRY_EXISTS ]]; then
            SubstituteMacros $TMP_MODS_FILE |
            ${SDS_BASEDIR}/SUNWconn/bin/ldapadd -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 $SDS_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_SDS ; then
		   print "$UTPASSWD" | $UTA_BASEDIR/sbin/utpw -f 
		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
}

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
}

ConfigSunDS() {
  typeset STATUS=0

  UpdateSchema
  UpdateAcls

  CreateDatastore

  RestartSunDS

  LoadDatastore

  return $STATUS
}


UnconfigSunDSConf() {

  DestroyDatastore
  DowndateAcls
  DowndateSchema
}


UnconfigSunDS() {
  typeset STATUS=0

  /etc/init.d/dsserv stop

  UnloadDatastore
  UnconfigSunDSConf

  /etc/init.d/dsserv start

  return $STATUS
}

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

ImportUTPrefs() {

   UT_PREF_DIR=/var/opt/SUNWut/preferences
   PREF=$(find $UT_PREF_DIR ! -name "DEFAULT" -a -type f -print)
   typeset STATUS=0

   # 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
}

UpdateAdminServerPort() {
  typeset STATUS=0
  typeset CONF_FILE="/etc/http/$UT_INST.httpd.conf"

  CreateBeforeFile $CONF_FILE

  nawk '
    $1 == "port" && $3 == "{" {
      $2 = Port;
    }
    $1 == "ssl_enable" {
	$2 = SSLenable
    }

    {
      print $0;
    }
  ' Port="$UT_PORT" SSLenable="$SSLENABLE" $CONF_FILE >$TMP_CONF_FILE

  ReplaceFile $CONF_FILE $TMP_CONF_FILE

  return $STATUS
}

DowndateAdminServerPort() {
  typeset STATUS=0
  typeset CONF_FILE="/etc/http/$UT_INST.httpd.conf"

  DestroyBeforeFile $CONF_FILE

  return $STATUS
}

PrintLocalhostEntry() {
  typeset STATUS=0

  print "# SUNWut begin"
  print "url "/" {"
  print "	$REMOTE_ENABLE host *"
  print "	+ host $IPA"
  print "}"
  print "# SUNWut end"

  return $STATUS
}

AppendLocalhostRestriction() {
  typeset STATUS=0
  typeset CONF_FILE="$UT_INST_SITE/conf/access.conf"
  typeset IPA THE_REST
  
  getent hosts localhost | read IPA THE_REST

  CreateBeforeFile $CONF_FILE

  DeleteUTEntry $CONF_FILE >$TMP_CONF_FILE

  PrintLocalhostEntry >>$TMP_CONF_FILE

  ReplaceFile $CONF_FILE $TMP_CONF_FILE

  return $STATUS
}

AppendCgiUser() {
  typeset STATUS=0
  typeset CONF_FILE="$UT_INST_SITE/conf/default_site.site.conf"

  CreateBeforeFile $CONF_FILE

  DeleteUTEntry $CONF_FILE >$TMP_CONF_FILE

  cat >>$TMP_CONF_FILE <<-!
	# SUNWut begin
	cgi_user $CGI_USER
	# SUNWut end
	!

  ReplaceFile $CONF_FILE $TMP_CONF_FILE

  return $STATUS
}

SetupCgiNodes() {

  typeset CGI_SOURCE_DIR=${UTA_BASEDIR}/cgi-bin
  typeset CGI_DEST_DIR=${UT_INST_SITE}/cgi-bin

  if [[ -d $CGI_DEST_DIR ]]; then
    for node in $(ls $CGI_SOURCE_DIR)
    do
      if [[ -f ${CGI_SOURCE_DIR}/${node} && -x ${CGI_SOURCE_DIR}/${node} ]]; then
         SymLinkForSure $CGI_SOURCE_DIR/${node} ${CGI_DEST_DIR}/${node}
      else
         Note "${CGI_SOURCE_DIR}/${node} is not an executable file.\nSkipping link to ${CGI_DEST_DIR}"
      fi
    done
  fi
}


EditCgiTokensCronEntry() {
  typeset STATUS=0
  typeset D="${VAR_OPT_UT}/cgitokens"

  crontab -l | sed "\:find $D:d" >$TMP_FILE
  case "$1" in
  add)
    print "0 3 * * * find $D -type f -mtime +1 -exec rm {} \;" >>$TMP_FILE
    ;;
  esac
  crontab $TMP_FILE

  return $STATUS
}

SetupCgiTokens() {
  chown $CGI_USER $TOKEN_DIR
  chmod 700       $TOKEN_DIR
  EditCgiTokensCronEntry add
  return $?
}

TakedownCgiTokens() {
  chown sys $TOKEN_DIR
  chmod 777 $TOKEN_DIR
  EditCgiTokensCronEntry delete
  return $?
}

SymLinkForSure() {
  rm -f $2
  ln -s $1 $2
  return $?
}

CreateUTTempDir() {
  

  if [[ ! -d $TMP_DIR_PATH ]]; then
    mkdir -m 770 -p $TMP_DIR_PATH
  fi

  # Add the utadmin group if it doesn't exist

  if ! grep -c -w $UTADMIN_GROUP /etc/group >> /dev/null; then
	groupadd $UTADMIN_GROUP 
  fi
  chgrp $UTADMIN_GROUP $TMP_DIR_PATH
  
}

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 SunRay 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
}

ConfigRemoteAdmin() {

  typeset REMOTE=false
  typeset SSL=false
  
  # Default answer is NO -- user must explicitly want remote admin
  if ! ReplyIsNo "Enable remote server administration?"; then
     REMOTE=true

     if SSLInstalled; then
	 ssl_advise_MSG
	 if ReplyIsYes "Enable Secure Socket Layer (SSL) connection ?"; then
            SSL=true
 	 fi
      else
	 ssl_missing_MSG
	 ssl_advise_MSG
 	 if ReplyIsNo "Do you still wish to enable remote server administration?"; then
 	      REMOTE=false
 	 fi
 
      fi
 	   
   fi

   if $REMOTE; then
       REMOTE_ENABLE="+"
       REMOTE_ENABLE_S="Enabled"
   fi
   if $SSL; then
       SSLENABLE="yes"
       SSL_ENABLE_S="Enabled"
   fi

}

ConfigSWS() {
  typeset STATUS=0
  typeset COMMENT="ut admin web server cgi user"

  if ! getent passwd $CGI_USER 1>&- 2>&-; then
    print "Adding user account for '$CGI_USER' ($COMMENT) ..."
    useradd -c "$COMMENT" -d /tmp -g $UTADMIN_GROUP $CGI_USER
  else 
    #
    # User exists; add rights to the utadmin group. First find out any other
    # local groups the user is in, then run usermod to add utadmin to them.
    #
    typeset OLDGROUPS=$(/bin/nawk -F '[:]' '{
	s = split($4, users, ",");
	for (i = 1; i <= s; i++) {
	  if (users[i] == user) {
	    printf("%s,", $1);
	    break;
	  }
	}
      }' user=$CGI_USER /etc/group)
    print "\nAdding user account '$CGI_USER' to group '$UTADMIN_GROUP' ..."

    usermod -G ${OLDGROUPS}${UTADMIN_GROUP} $CGI_USER 2>/dev/null

    # Identify previously installed SunRay web-admin CGI user
    # and force utadmin to be its primary group.
    typeset UT_WWW_USER=$(grep "${COMMENT}" /etc/passwd | cut -d: -f1)
    if [[ -n "${UT_WWW_USER}" ]]; then
        typeset WWWGROUP=$(logins -l ${UT_WWW_USER} | nawk '{print $3}')
        if [[ "${WWWGROUP}" == "${UTADMIN_GROUP}" || "${WWWGROUP}" == staff ]]
	then
            usermod -g ${UTADMIN_GROUP} -d ${TMP_DIR_PATH} ${UT_WWW_USER}
        fi
    fi
  fi

  print "\nCreating $SWS_PROD_NAME '$UT_INST' instance ..."

  # check for an existing webserver instance
  htserver query $UT_INST 1>/dev/null 2>&1

  if [[ $? -ne 0 ]]; then
      htserver add $UT_INST 
  fi

  UpdateAdminServerPort

  # delete not needed SWS cgi scripts for tightened security.
  rm -f $UT_INST_SITE/cgi-bin/*

  SetupCgiNodes

  CreateBeforeDir $UT_INST_SITE/public

  SymLinkForSure $UTA_BASEDIR/lib/locale $UT_INST_SITE/public

  if EnglishDocsInstalled; then
     SymLinkForSure $EN_DOC_DIR $UTA_BASEDIR/$LOCAL_EN_DOC_DIR
     SymLinkForSure $EN_DOC_DIR $UTA_BASEDIR/$LOCAL_FR_DOC_DIR
     SymLinkForSure $EN_DOC_DIR $UTA_BASEDIR/$LOCAL_ZH_DOC_DIR
  fi

  if JapaneseDocsInstalled; then
    SymLinkForSure $JA_DOC_DIR $UTA_BASEDIR/$LOCAL_JA_DOC_DIR
    # Workaround for the japanese docs having different names.
    SymLinkForSure $JA_DOC_DIR/adminguide/admguideTOC.html \
                   $JA_DOC_DIR/adminguide/adminguideTOC.html
    SymLinkForSure $JA_DOC_DIR/advadminguide/advadminguideTOC.html\
                   $JA_DOC_DIR/advadminguide/advancedTOC.html
    SymLinkForSure $JA_DOC_DIR/installguide/installguideTOC.html\
		   $JA_DOC_DIR/installguide/installTOC.html
  fi

  htmap add -h $THIS_HOST -i $UT_INST -f /images -t $UT_INST_SITE/public/images
  htmap add -h $THIS_HOST -i $UT_INST -f /docroot -t $UT_INST_SITE/public/
  htmap add -h $THIS_HOST -i $UT_INST -f /javascript -t $UT_INST_SITE/public/javascript
  htmap add -h $THIS_HOST -i $UT_INST -f / -t $UT_INST_SITE/cgi-bin/start -c CGI

  # Added to disable directory listing.
  htcontent add -i $UT_INST -h $HOSTNAME -n /cgi-bin/ -u siteAdmin -O d=off

  AppendLocalhostRestriction
  AppendCgiUser
  SetupCgiTokens

  htserver enable $UT_INST

  htserver start $UT_INST

  return $STATUS
}

UnconfigSWS() {
  typeset STATUS=0

  print "\nRemoving $SWS_PROD_NAME '$UT_INST' instance ..."

  htserver stop $UT_INST 2>/dev/null

  TakedownCgiTokens

  DowndateAdminServerPort

  htserver delete $UT_INST 2>/dev/null

  if [[ $? -ne 0 ]]; then
      print "\nProblem encountered during removal of $SWS_PROD_NAME '$UT_INST' instance ..."
  fi

  rm -rf /var/http/$UT_INST
  rm -f /etc/http/$UT_INST.httpd.conf

  if $DELETE_CGI_USER; then
    print "\nDeleting user account for '$CGI_USER' ..."

    if getent passwd $CGI_USER; then
      userdel $CGI_USER
    else
      print "Warning: CGI user '$CGI_USER' was not found"
    fi
      groupdel $UTADMIN_GROUP
  fi

  # Clean up and remove the symlinks associated with the
  # web-based administration framework.

  rm -f $UT_INST_SITE/cgi-bin/admincgi
  rm -f $UT_INST_SITE/cgi-bin/desktop
  rm -f $UT_INST_SITE/cgi-bin/gstatus
  rm -f $UT_INST_SITE/cgi-bin/log
  rm -f $UT_INST_SITE/cgi-bin/main
  rm -f $UT_INST_SITE/cgi-bin/nav
  rm -f $UT_INST_SITE/cgi-bin/status
  rm -f $UT_INST_SITE/cgi-bin/smartcard
  rm -f $UT_INST_SITE/cgi-bin/start
  rm -f $UT_INST_SITE/cgi-bin/user
  rm -f $UT_INST_SITE/cgi-bin/mhstatus

  # Clean up orphaned documentation link directories.
  rm -f $UTA_BASEDIR/$LOCAL_EN_DOC_DIR
  rm -f $UTA_BASEDIR/$LOCAL_FR_DOC_DIR
  rm -f $UTA_BASEDIR/$LOCAL_ZH_DOC_DIR
  rm -f $UTA_BASEDIR/$LOCAL_JA_DOC_DIR

  # Clean up orphaned japanese documentation links.
  rm -f $JA_DOC_DIR/adminguide/adminguideTOC.html
  rm -f $JA_DOC_DIR/advadminguide/advancedTOC.html
  rm -f $JA_DOC_DIR/installguide/installTOC.html

  return $STATUS
}

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
}

InitSWSVars() {

  UT_ADMIN_WEB_S="UT admin web server"
  DEFAULT_UT_INST="utadmin"
  DEFAULT_UT_PORT="1660"
  DEFAULT_CGI_USER="utwww"

  UT_INST="${DEFAULT_UT_INST}"
  UT_PORT="${DEFAULT_UT_PORT}"
  CGI_USER="${DEFAULT_CGI_USER}"

  DELETE_CGI_USER=false

  TOKEN_DIR="${VAR_OPT_UT}/cgitokens"

  REMOTE_ENABLE="-"
  REMOTE_ENABLE_S="Disabled"

  HTTPCFGFILE="UNKNOWN"
  SSLENABLE="no"
  SSL_ENABLE_S="Disabled"

  return 0
}

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

  InitSWSVars
  SWSInfo

  PromptForParameters 

  SetupCgiNodes

  [[ ! -f /etc/http/$UT_INST.httpd.conf ]] && \
    HTTPCFGFILE=UNKNOWN

  ConfigUtadmin

  if [[ "$HTTPCFGFILE" != "UNKNOWN" ]]; then
    SetupCgiTokens
  fi

  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
  SDS_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 SunDS configuration
  UnconfigSunDSConf 
  # Configure the schema + LDAP base entries
  ConfigSunDS
  # 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

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

  CRYPTD_ROOTPW="$SAVED_CRYPTDPW"
  DestroyDatastore

  CreateDatastore

  ConfigDbm
  ConfigSmartCard

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

  ImportUTPrefs

  RestartSunDS

  # end of the upgrade, reset the flag.
  SDS_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

  ConfigUtadmin

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

  cat <<-!

	$SDS_PROD_NAME $SDS_VERSION
	    Hostname: $THIS_HOST
	    $UT_ROOT_S entry: $ROOTENTRY
	    $UT_ROOT_S name: $ROOTNAME
	    UT $ROOTNAME admin password: (not shown)
	    $SDS_ROOTDN_S: $ROOTDN
	!
   
  if $CONFIG_SWS; then
    cat <<-!

	$SWS_PROD_NAME $SWS_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"


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

  if ! $SKIP_SDS ; then
     UnconfigSunDS
     ConfigSunDS
  fi
  

  if $CONFIG_SWS; then
    ConfigSWS
  fi

  ConfigDbm
  ConfigSmartCard

  ConfigGroup

  RestartSunDS

  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 /opt/SUNWut/sbin/utpolicy $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

  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 SWSInstalled && SWSVersion $SWS_VERSION && $SWS_ALREADY_CFG; then
      UNCONFIG_SWS=true
      DELETE_CGI_USER=true
  fi

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

  print "\n$SDS_PROD_NAME $SDS_VERSION"

  if $UNCONFIG_SWS; then
    print "$SWS_PROD_NAME $SWS_VERSION"
  fi

  print "$UT_PROD_NAME $UT_VERSION"

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

  UnconfigGroup

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

  UnconfigDbm
  UnconfigUtadmin
  if $UNCONFIG_SWS; then
    UnconfigSWS
  fi

  if PreviousUTDataStore ; then
      UnconfigSunDS
  fi

  RemoveOldBackupFiles

  utpolicy_MSG

  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 $?
}



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

You have enabled SSL. Before using the Sun Ray administration
tool you will need to create and install the appropriate 
certificates for your system.  

Please consult the Administrator's Guide.

!
}

ssl_missing_MSG() {
cat <<-!
Secure Socket Layer (SSL) package is not installed on $THIS_HOST
!
}

ssl_advise_MSG() {
cat <<-!

Selecting remote administration without SSL poses a potential 
security risk and is not advised.
!
}

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="autoconfigure"
FORCE=false

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

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

CheckUidIsZero

UT_PROD_NAME="Sun Ray enterprise server"
UT_VERSION="1.2"

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"

SDS_PROD_NAME="Sun Directory Services"
SDS_VERSION="3.1"
SDS_PACKAGE="SUNWsds"

if ! SunDSInstalled; then
  Fatal "$SDS_PROD_NAME is not installed on this host"
elif ! SunDSVersion $SDS_VERSION; then
  Fatal "version $SDS_VERSION of $SDS_PROD_NAME is not installed on this host"
elif SunDSInstallPartial; then
  Fatal "$SDS_PROD_NAME version $SDS_VERSION is only partially installed"
fi

SDS_BASEDIR="$(pkginfo -r $SDS_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="UT 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/SUNWconn/ldap/dbm.ut"
VAR_OPT_LDAP_REPLOG="/var/opt/SUNWconn/ldap/replog"
SDS_UPGRADE_FLAG="NO"

SDS_LDAP_CURRENT="/etc/opt/SUNWconn/ldap/current"
SDS_LDAP_HTML="$SDS_BASEDIR/SUNWconn/ldap/html"
DS_CONF_FILE="$SDS_LDAP_CURRENT/dsserv.conf"

SWS_PROD_NAME="Sun Web Server"
SWS_VERSION="2.1"

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/tmp/${PROGRAM_ID}.$(date '+%Y_%m_%d_%H:%M:%S').log"

print "# Script: ${PROGRAM_ID}\tVersion: \n" > $LOGFILE



 # When upgrading an existing directory the hostname
 # used to re-build the relavent SunDS 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

# }
