#!/bin/sh 
# sdsetup.sh - RSA Authentication Manager Installation Script
# Copyright (c) 1990-2005 RSA Security Inc. 

############################################################################
# linux_line_func()
# Read a line from standard input on Linux. Because Linux has no 'line'
# command available.
############################################################################
linux_line_func()
{
	read
	echo $REPLY
}

############################################################################
# set_exec_path()
# Set the path variables
############################################################################
set_exec_path()
{
  EXEC_PATH=$1
  if [ "$EXEC_PATH" = "" ] ; then
     EXEC_PATH="/bin"
  fi

  UNCOMPRESS_EXEC="/$EXEC_PATH/uncompress"
  LINE_EXEC="$EXEC_PATH/line"
  PWD_EXEC="$EXEC_PATH/pwd"
  SED_EXEC="$EXEC_PATH/sed"
  LN_EXEC="$EXEC_PATH/ln"
  CHMOD_EXEC="$EXEC_PATH/chmod"
  CHOWN_EXEC="$EXEC_PATH/chown"
  CHGRP_EXEC="$EXEC_PATH/chgrp"
  CLEAR_EXEC="$EXEC_PATH/clear"
  FIND_EXEC="$EXEC_PATH/find"
  TAR_EXEC="$EXEC_PATH/tar"
  MT_EXEC="$EXEC_PATH/mt"
  DD_EXEC="$EXEC_PATH/dd"
  LS_EXEC="$EXEC_PATH/ls"
  GREP_EXEC="$EXEC_PATH/grep"
  TR_EXEC="$EXEC_PATH/tr"
  MKDIR_EXEC="$EXEC_PATH/mkdir"
  RM_EXEC="$EXEC_PATH/rm"
  WHOAMI_EXEC=""  
  SDREP_EXEC="_sdrepmgmt"
  MV_EXEC="$EXEC_PATH/mv"
}

############################################################################
# init_global_vars()
# Initialize the global variables.  This initializes variables defined at
# start of installation as well as those used for return values from 
# subroutines. These values may be redefined later, but this routine provides 
# initial values as well as identifies variables to be used.
############################################################################
init_global_vars()
{
  DEFVARACE="/var/ace"
  DEFUSRACE="/usr/ace"
  DEFDLC="unknown"
  DEFPROPATH="$USR_ACE/proapi/adbapi.pl,$USR_ACE/proapi/sdproapi.pl,$USR_ACE,$USR_ACE/protrig"
  CURRENT_AS_VERSION="6.1"
# The lowest allowed version we support migration from MAJOR+MINOR no revs ot pathces 
# Minor is in the two digit format
  ALLOWED_V="501"
  ALLOWED_VP="5.1"
# WARN_UPGRADE controls backward upgrade
  WARN_UPGRADE=FALSE
# The existence and usage of the dump files
  SERV_DUMP_EXISTS=FALSE
  LOG_DUMP_EXISTS=FALSE
  INSTALL_PRIMARY_OR_REPLICA=FALSE
  INSTALL_PRIMARY_OR_AGENT=FALSE
  PRIMARY="primary"
  PRIMARY_PRETTY="Primary Server"
  REPLICA="replica"
  REPLICA_PRETTY="Replica Server"
  AGENT="agent"
  SDREPMGMT="repmgmt"
  SDREPGEN="package"
  APPLY_RP="apply_package"
  APPLY_CR="apply_config"
  PORT_CHG="port_config"
  DEF_PAGE="iso8859-1"
  SD_ALL_REPLICAS="all_replicas"
  SERVER_NAME="RSA Authentication Manager"
  ROLLING_UPGRADE=FALSE
  OK_TO_WIPE_OUT_ACE=FALSE
  INSTALL_FILES_ARE_UPPERCASE=FALSE
  APPLY_NEW_LICENSE=FALSE
  REPLICATION_ELEVATED=FALSE

# Define and export a variable that lets sdrepmgmt know if it was called by sdsetup.
# This is checked by sdrepmgmt to see if "sdsetup -repmgmt [USAGE]" should be 
# printed in the usage message, instead of "sdrepmgmt [USAGE]".
  SDREPMGMT_CALLED_FROM_SDSETUP=TRUE; export SDREPMGMT_CALLED_FROM_SDSETUP


#DEFPROPATH gets defined later because it needs USR_ACE to be defined first.
# OS specific executables
  UNAME_EXEC="/bin/uname"
  UNAMER_EXEC="$UNAME_EXEC -r"
  UNAMEV_EXEC="$UNAME_EXEC -v"
  
  set_exec_path

# Disk space require for the installation
  SPACE=400000

# Temp. file ensuring only one setup process can be executed at a time.
  SDSETUP_RUNNING_FILE="/tmp/sdsetup.running"

# ACE Runtime variables
  
  if [ "$VAR_ACE" = "" ] ; then
         VAR_ACE=$DEFVARACE; export VAR_ACE
  fi

   if [ "$USR_ACE" = "" ] ; then
         USR_ACE=$DEFUSRACE; export USR_ACE
   fi

   if [ "$DLC" = "" ] ; then
         DLC=$DEFDLC; export DLC
   fi

   if [ "$PROPATH" = "" ] ; then
          DEFPROPATH="$USR_ACE/proapi/adbapi.pl,$USR_ACE/proapi/sdproapi.pl,$USR_ACE,$USR_ACE/protrig"
          PROPATH=$DEFPROPATH; export PROPATH
   fi


# ACE specific utility programs
  DLC_PROUTIL="$DLC/bin/proutil"

#  Directory from which the ACE installation files are obtained.
  ACE_INSTALL_DIR=`$PWD_EXEC`

# Ownership and Group for install
  OWNER_NAME=""
  GROUPNAME=""

# UMASK values
  USER_FULL_ACCESS=077

# Used for DB conversion and migration

  echo_no_nl_mode="unknown"
  MADE_NEW_DB=FALSE
  NEW_INSTALLATION=FALSE
  CONVERTED_DB=FALSE
  CUR_DB_VERS=""
  ORIG_DB_VERS=""
  MIGRATE_DB=FALSE
  CONVERT_DB=FALSE

# Other flag variables

  INSTALL_TYPE=""
  OVERWRITE=""
  PATH_ROOT=""
  SILENT_MODE=FALSE
  PRESERVE_DB=FALSE
  SOURCE_DIR="`pwd`"
  SKIPWARNING=FALSE
  UPGRADE_SUCCESS=FALSE
  PRIMARY_APPLY_PACKAGE=FALSE
}

##############################################################################
# clear_screen()
# sdsetup falls to this if clear doesn't exist as a command.
# It prints 25 <CR>'s.
##############################################################################
clear_screen()
{
  counter=0
  while [ $counter -lt 25 ]
  do
    echo ""
    counter=`expr $counter + 1`
  done
}

##############################################################################
# echo_no_nl()
# Echo a string with no carriage return (if possible).  Must set
# $echo_no_nl to "unknown" before using for the first time.
##############################################################################
echo_no_nl()
{
  if [ "$echo_no_nl_mode" = "unknown" ] ; then
     echo_test=`echo \\\c`
     if [ "$echo_test" = "\c" ] ; then
        echo_no_nl_mode="-n"
     else
        echo_no_nl_mode="\c"
     fi
  fi

  if [ "$echo_no_nl_mode" = "\c" ] ; then
     echo $* \\c
  else
     echo $ECHO_FLAG -n "$*"
  fi
}

##############################################################################
# check_os_version()
# Make sure the OS version on the target machine is supported added 
# additional lines of code which were being done by setup platforms
# you pass it the "common" or the "server" flags
##############################################################################
check_os_version()
{
  check_type=$1
  VALID_OS=FALSE

# common option does os and platform checking for stuff common to
# primary, replica and agent
  
  if [ "$check_type" = "common" ] ; then

    if [ -x "$UNAME_EXEC" ] ; then
      SYSUNAME=`$UNAME_EXEC`
      SYSUNAMER=`$UNAMER_EXEC`
    else
      SYSUNAME="NONE"
    fi
  
    case "$SYSUNAME"
    in
      'AIX'    )  PLATFORM="aix"
                  AIX_VERS="`$UNAMEV_EXEC`.`$UNAMER_EXEC`"
                  case "$AIX_VERS" in
                   '5.2' ) VALID_OS=TRUE;;
                   '5.3' ) VALID_OS=TRUE;;
                  esac;;
      'HP-UX'  )  PLATFORM="hp"
                  HP_VERS=`echo $SYSUNAMER | awk '{print substr($1, 3, 5)}'`
                  case "$HP_VERS" in
                    '11.11' ) VALID_OS=TRUE;;
                  esac;;
      'SunOS'  )  PLATFORM="sol"
                  SUN_VERS=`echo $SYSUNAMER | awk '{print substr($1, 1, 1)}'`
                  case "$SUN_VERS" in
                    '5' ) VALID_OS=TRUE;;
                  esac;;
      'Linux'  )  PLATFORM="linux"
                  LINUX_VERS=`rpm -q -v redhat-release | awk '{print substr($1,16,3)}'`
                  case "$LINUX_VERS" in
                    '3AS' ) VALID_OS=TRUE;;
                    '3ES' ) VALID_OS=TRUE;;
                    *     ) LINUX_VERS=`cat /etc/SuSE-release | grep VERSION | awk '{print $3}'`
                            case "$LINUX_VERS" in
                              '9' ) VALID_OS=TRUE;;
                              '9.2' ) VALID_OS=TRUE;;
                            esac;;
                  esac;;
    esac
    if [ -z "$PLATFORM" ] ; then
      echo ""
      echo "Unable to determine operating system."
      abort_installation
    fi

    if [ "$VALID_OS" = FALSE ] ; then
      echo ""
      echo "The version of your operating system is not supported."
      echo "Upgrade the OS and run 'sdsetup' again."
      abort_installation
    fi
  
# the call type was server, so we'll do server specific os checks  
  elif [ "$check_type" = "server" ] ; then
    case "$SYSUNAME" in
      'AIX'    )  
                  case "$AIX_VERS" in
                    '5.2' ) VALID_OS=TRUE;;
                    '5.3' ) VALID_OS=TRUE;;
                  esac;;
      'HP-UX'  )  
                  case "$HP_VERS" in
                    '11.11' ) VALID_OS=TRUE;;
                  esac;;
      'SunOS'  ) 
                  SUN_VERS=`echo $SYSUNAMER | awk '{print substr($1, 1, 3)}'` 
                  case "$SUN_VERS" in
                    '5.9' ) VALID_OS=TRUE;;
                    '5.1' ) SUN_VERS=`echo $SYSUNAMER | awk '{print substr($1, 1, 4)}'` 
                            case "$SUN_VERS" in
                              '5.10' ) VALID_OS=TRUE;;
                            esac;;
                  esac;;
      'Linux'  )  PLATFORM="linux"
                  LINUX_VERS=`rpm -q -v redhat-release | awk '{print substr($1,16,3)}'`
                  case "$LINUX_VERS" in
                    '3AS' ) VALID_OS=TRUE;;
                    '3ES' ) VALID_OS=TRUE;;
                    *     ) LINUX_VERS=`cat /etc/SuSE-release | grep VERSION | awk '{print $3}'`
                            case "$LINUX_VERS" in
                              '9' ) VALID_OS=TRUE;;
                              '9.2' ) VALID_OS=TRUE;;
                            esac;;
                  esac;;
    esac    

    if [ "$VALID_OS" = FALSE ] ; then
      echo ""
      echo "The version of your operating system does not support server"
      echo "operation. Upgrade the OS and run 'sdsetup' again."
      abort_installation
    fi
  fi
}

##############################################################################
# setup_platforms()
# setup the platform specific variables values
##############################################################################
setup_platforms()
{
  # Modify the defaults if necessary for some OS's
  case "$PLATFORM"
  in
    'hp'    )   CLEAR_EXEC="/usr/bin/clear"
                UNCOMPRESS_EXEC="/usr/bin/uncompress";;
    'linux' )   CLEAR_EXEC="/usr/bin/clear"
                UNCOMPRESS_EXEC="/usr/bin/uncompress"
                if [ -f "$LINE_EXEC" ] ; then
                    export LD_ASSUME_KERNEL=2.4.0
                else
                    LINE_EXEC="linux_line_func"
                fi
                ECHO_FLAG="-e"
                FIND_EXEC="/usr/bin/find"
                TR_EXEC="/usr/bin/tr"
                CLEAR_EXEC="/usr/bin/clear";;
  esac

  # Based on platform, set global variables to reflect OS specific tar files.
  SERVER_SOFTWARE=sdserver_"$PLATFORM".tar
  CLIENT_SOFTWARE=sdclient_"$PLATFORM".tar
  PROGRESS_SOFTWARE=rdbms_"$PLATFORM".tar
#  PROGRESS_INSTALL_SOFTWARE=progress_v82c."$PLATFORM".tar
}

##############################################################################
# check_exec_paths()
# Check to make sure the executable paths defined in init_global_vars
# exist and can be used.
##############################################################################
check_exec_paths()
{

#
# Test for existence
#
  for testprogram in "$CHMOD_EXEC" "$CHOWN_EXEC" "$UNCOMPRESS_EXEC" \
         "$TAR_EXEC" "$LS_EXEC"
  do
    if [ ! -x "$testprogram" ] ; then
      $CLEAR_EXEC
      echo "Unable to find the utility $testprogram.  This utility is necessary"
      echo "for the execution of 'sdsetup'."
      echo ""
      echo "If you do not have this file, see the section \"Getting Support and Service\"" 
      echo "in the $SERVER_NAME for UNIX Installation Guide (aceservdoc/unix_install.pdf"
      echo "on the $SERVER_NAME CD) for information about contacting technical support."
      abort_installation
    fi
  done

#
# May not have clear, may not have term type set
#
  if [ ! -x "$CLEAR_EXEC" ] ; then
    CLEAR_EXEC="clear_screen"
  elif [ -z "`$CLEAR_EXEC`" ] ; then
    CLEAR_EXEC="clear_screen"
  fi
  $CLEAR_EXEC

  if [ ! -x "$FIND_EXEC" ] ; then
    execute_error "$FIND_EXEC"
  fi

#
# No big loss if grep doesn't exist
#
  if [ ! -x "$GREP_EXEC" ] ; then
    GREP_EXEC=""
  fi


## lets see if we can find the whoami utility to identify the current user ##
  if [ -x "/bin/whoami" ] ; then
    WHOAMI_EXEC="/bin/whoami"
  elif [ -x "/usr/bin/whoami" ] ; then
    WHOAMI_EXEC="/usr/bin/whoami"
  elif [ -x "/usr/ucb/whoami" ] ; then
    WHOAMI_EXEC="/usr/ucb/whoami"
  else
    WHOAMI_EXEC=""
  fi
}

##############################################################################
# get_install_directory()
# Get the base directory of the installation software abort on error. This 
# routine will examine the $0 argument which contains the path used to call 
# sdsetup.  This path will be extracted and used to define ACE_INSTALL_DIR 
# and SOURCE_DIR which are passed back to the calling routine in the environment.
##############################################################################
get_install_directory()
{

  SOURCE_DIR=""

  if [ -x "$PWD_EXEC" ] ; then
    SOURCE_DIR=`"$PWD_EXEC"`
  elif [ -n "$PWD" ] ; then
    SOURCE_DIR=$PWD
  elif [ -n "$cwd" ] ; then
    SOURCE_DIR=$cwd
  else
    echo ""
    echo "Unable to determine current working directory."
    abort_installation
  fi

  case $0 in
    */*) test_cd_base_dir=`dirname $0`;;
    *) test_cd_base_dir=$SOURCE_DIR;;
  esac

  cd $test_cd_base_dir
  if [ $? != 0 ] ; then
    echo "Cannot change directory to '$test_cd_base_dir'.  Verify that the"
    echo "CD is mounted correctly and run 'sdsetup' again."
    abort_installation
  fi

if [ ! -d "$ACE_INSTALL_DIR/sdinstall" ] ; then
  if [ -x "$PWD_EXEC" ] ; then
    ACE_INSTALL_DIR=`$PWD_EXEC`
  elif [ -n "$PWD" ] ; then
    ACE_INSTALL_DIR=$PWD
  elif [ -n "$cwd" ] ; then
    ACE_INSTALL_DIR=$cwd
  fi
fi

  cd "$SOURCE_DIR"
}

##############################################################################
# print_usage()
# Prints the proper syntax for sdsetup and exits from program.
##############################################################################
print_usage()
{
  usage_type=$1
  USAGE=""
  if [ "$usage_type" = "long" ] ; then
    USAGE="The correct syntax is
sdsetup [-$PRIMARY | -$REPLICA | -config | -license | -$SDREPMGMT |
         -$SDREPGEN | -$APPLY_RP [path_to_package] |  -$APPLY_CR [path_to_config] |
         -$PORT_CHG [service_name port_number] | [service_name] | [- port_number] ]
         [-o yes | no ] [-f fileowner] [-p path] [-c CD_location] [-r yes | no] "    
    
  else
    USAGE="The correct syntax is
sdsetup [-$PRIMARY | -$REPLICA | -config | -license | 
         -$SDREPMGMT | -$SDREPGEN | -$APPLY_RP | -$APPLY_CR | -$PORT_CHG ] "
  fi
  echo ""
  echo "$USAGE"
  abort_installation
}

##############################################################################
# getyesorno()
# Gets either a "yes" or a "no" in the traditional (y/n) pattern or
# "quit" to abort installation.
#   $1  The default value if user hits <Enter> (TRUE/FALSE)
#   $2  The string to print to prompt the user
# The variable $YESORNO is set in accordance to what the user entered.
##############################################################################
getyesorno()
{
  yesornodef=$1
  yesornoprompt=$2

  YESORNO=""
  until [ -n "$YESORNO" ] ;
  do
    echo ""
    echo_no_nl "$yesornoprompt"
    YESORNO=`$LINE_EXEC`

    case "$YESORNO"
    in
      'y' )  YESORNO=TRUE;;
      'n' )  YESORNO=FALSE;;
      'q' )  abort_installation;;
      ''  )  YESORNO=$yesornodef;;
      '\c'  )  YESORNO=$yesornodef;;
      '\n'  )  YESORNO=$yesornodef;;
      *   )  echo ""
       echo "Please enter 'y', 'n' or 'q'."
       YESORNO="";;
    esac
  done
}

##############################################################################
# getyesorno_noabort()
# Gets either a "yes" or a "no" in the traditional (y/n) pattern or
# "quit" to abort installation.
#   $1  The default value if user hits <Enter> (TRUE/FALSE)
#   $2  The string to print to prompt the user
# The variable $YESORNO is set in accordance to what the user entered.
##############################################################################
getyesorno_noabort()
{
  yesornodef=$1
  yesornoprompt=$2

  YESORNO=""
  until [ -n "$YESORNO" ] ;
  do
    echo ""
    echo_no_nl "$yesornoprompt"
    YESORNO=`$LINE_EXEC`

    case "$YESORNO"
    in
      'y' )  YESORNO=TRUE;;
      'n' )  YESORNO=FALSE;;
      ''  )  YESORNO=$yesornodef;;
      '\c'  )  YESORNO=$yesornodef;;
      '\n'  )  YESORNO=$yesornodef;;
      *   )  echo ""
       echo "Please enter 'y' or 'n'."
       YESORNO="";;
    esac
  done
}

##############################################################################
# abort_installation()
# Abort the installation - this calls cleanup_installation() - however, it
# also prints on the screen that the installation was aborted.
##############################################################################
abort_installation()
{
  echo ""
  echo "Aborting sdsetup..."
  cleanup_installation "$1"
  exit 1
}

##############################################################################
# uncompress_progress()
# Uncompresses the progress tar file
##############################################################################
uncompress_progress()
{

  echo ""
  echo "The current time is `date`"
  echo "Uncompressing Progress software..."

  if $FIND_EXEC $PATH_ROOT/ace/rdbms -name "*.Z" -exec $UNCOMPRESS_EXEC {} \;
    then
      :
  else
      execute_error "$UNCOMPRESS_EXEC"
  fi
}

##############################################################################
# execute_error ()
# If an error ever occurs during the launch of any program, this will
# tell the user something happened, tell them it is fatal, and
# abort. If this is a new install, then all  RSA Authentication Manager software will
# be removed. If this is a re-install, then the original  RSA Authentication Manager
# software will be restored.
##############################################################################
execute_error()
{
  execute_file=$1
  echo ""
  echo ""
  echo "An unexpected error occurred while running $execute_file."
  echo "This error is fatal to the installation of the $SERVER_NAME; installation"
  echo "cannot continue."
  echo "If you require assistance with the installation, see the section \"Getting Support and Service\""
  echo "in the $SERVER_NAME for UNIX Installation Guide (aceservdoc/unix_install.pdf"
  echo "on the $SERVER_NAME CD) for information about contacting technical support."


  cleanup_installation
  exit 1
}

##############################################################################
# cleanup_installation()
# This subroutine removes files that were recently installed and restores
# the previous installation files, if they existed. In the event that this
# routine is called with a parameter "no_clean" or the environment variable
# SDSETUP_NO_CLEAN is set, the cleanup will be skipped BUT sdsetup.running
# will be deleted. In general, this is useful for debugging OR if it was
# determined that there is no write access to the install directory.
##############################################################################
cleanup_installation()
{
   if [ "$DEBUG_SETUP" = TRUE ] ; then
      echo "Debug mode. The data is not restored."
      return
   fi
   if [  "no_clean" != "$1" -o "$SDSETUP_NO_CLEAN" = FALSE ] ; then
   if [ "$OK_TO_WIPE_OUT_ACE" = TRUE ] ; then 
    if [ -d "$PATH_ROOT/ace" ] ; then
      echo ""
      echo "Removing installed files..."
      cd $PATH_ROOT
      rm -rf "ace"
      echo "Software removed."
    fi

    if [ -d "$PATH_ROOT/ace_tmp" ] ; then
      echo ""
      echo "Restoring original files..."
      mv "$PATH_ROOT/ace_tmp" "$PATH_ROOT/ace"
      echo "Original installation restored."
    fi
   fi
  fi

  if [ "$SDSETUP_RUNNING_FILE" != "" ] ; then
    if [ -f $SDSETUP_RUNNING_FILE ] ; then
       rm -f $SDSETUP_RUNNING_FILE
    fi
  fi

  if [ "" != ORIG_UMASK ] ; then
    umask $ORIG_UMASK
  fi

  echo ""
  echo "Sdsetup aborted."
  echo ""
}

##############################################################################
# check_newdb_connections()
# See if the current version of the database is busy
# This should be run before any files are copied.
##############################################################################
check_newdb_connections()
{
  newdb=$1
  type=$2
  RET_VAL=""
  $DLC_PROUTIL $newdb -C busy > /dev/null 2> /dev/null
  RET_VAL="$?"
  if [ $RET_VAL = 64 -o $RET_VAL = 6 ] ; then
    if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
         "$INSTALL_TYPE" = "$REPLICA" ] ; then
      echo "Error - The $type database is currently busy - exiting"
      abort_installation
    elif [ "$INSTALL_TYPE" = 'license' -o \
          "$INSTALL_TYPE" = 'config' -o \
          "$INSTALL_TYPE" = "$APPLY_CR" -o \
          "$INSTALL_TYPE" = "$PORT_CHG" ] ; then
      echo "Note: The server database is currently busy.  If the aceserver "
      echo "is also running, you must stop and restart the aceserver and brokers "
      echo "before these changes take effect."
    fi
  fi
}

##############################################################################
# check_running()
# Check to see if sdsetup is already running. Create the running file to 
# prevent another copy from running. The running file should be 
# removed after the install, or if the installation is aborted for any reason.
##############################################################################
check_running()
{
  if [ -f $SDSETUP_RUNNING_FILE ] ; then
    echo "A copy of 'sdsetup' is currently running or was previously abnormally"
    echo "terminated.  Please conclude the running copy before starting another,"
    echo "or if you are certain that another copy of 'sdsetup' is not running"
    echo "remove the file '$SDSETUP_RUNNING_FILE' and restart 'sdsetup'."
    exit 1
  fi
  if [ "$PLATFORM" = "aix" ] ; then
     MYPID=`who  -mi | awk '{print $7}'`
  else 
     MYPID=`who -mT | awk '{print $8}'`
  fi
  echo "A copy of 'sdsetup' is currently running (PID $MYPID)." \
> $SDSETUP_RUNNING_FILE
}

##############################################################################
# exit_cleanly()
# This routine removes the running file and exits
##############################################################################
exit_cleanly()
{
  if [ -f "$SDSETUP_RUNNING_FILE" ] ; then
    rm -f "$SDSETUP_RUNNING_FILE"
  fi

  if [ "" != ORIG_UMASK ] ; then
    umask $ORIG_UMASK
  fi
  
  exit 0
}

##############################################################################
# check_startup()
# Checks the "essentials" of startup - sufficient disk space, what the current
# working directory is (must be writable), and whether the user is root or 
# file owner.
##############################################################################
check_startup()
{
  # We write the license.rec file to the current working directory, so
  # the current working directory must be writable.

  if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
       "$INSTALL_TYPE" = 'license' ] ; then
    if [ ! -w . ] ; then
      echo "The current working directory must be writable.  Check for proper"
      echo "permissions or select a different working directory and run 'sdsetup' again."
      
      abort_installation "no_clean"
    fi
  fi

############################################
# Try to determine current working directory
############################################

  if [ -x $PWD_EXEC ]; then
     SOURCE_DIR=`$PWD_EXEC`
  elif [-n "$PWD" ]; then
     SOURCE_DIR=$PWD
  elif [ -n "$cwd" ]; then
     SOURCE_DIR=$cwd
  else 
    echo ""
    echo "Unable to determine current working directory."
    abort_installation
  fi

###############################################
# Try to determine whether user has permissions
###############################################
  isroot=FALSE

  if [ "$INSTALL_TYPE" = 'config' -o \
       "$INSTALL_TYPE" = 'license' -o \
       "$INSTALL_TYPE" = "$APPLY_RP" -o \
       "$INSTALL_TYPE" = "$APPLY_CR" -o \
       "$INSTALL_TYPE" = "$PORT_CHG" ] ; then

    SDCFGVAL_EXEC="$USR_ACE/sdcfgval"

    if [ ! -x $SDCFGVAL_EXEC ] ; then
      echo "Your $SERVER_NAME installation is not setup properly."
      echo "Verify the USR_ACE variable setting."
      abort_installation
    fi
 
  else
  # install type is primary, replica, or agent
    SDCFGVAL_EXEC="$INSTALL_TOOLS_DIR/sdcfgval"

    if [ ! -x $SDCFGVAL_EXEC ] ; then
      echo "A necessary installation utility is not available.  Verify that"
      echo "the CD is properly mounted and that you are logged in as root."
      echo "If you are not installing from CD, make sure that the entire"
      echo "directory structure has been copied from the CD."
      abort_installation
    fi

  fi


## Try to determine the current user
CURRENT_USER=""

if [ -n "$WHOAMI_EXEC" ] ; then
    CURRENT_USER=`"$WHOAMI_EXEC"`
elif [ "$LOGNAME" ] ; then
    CURRENT_USER="$LOGNAME"
fi

ACE_OWNER="`$SDCFGVAL_EXEC ownername`"
CUR_UID="`$SDCFGVAL_EXEC current_uid`"


if [ "$CUR_UID" != "0" ] ; then

  ## check if the current user matches root, or the RSA Authentication Manager owner
  if [ "$INSTALL_TYPE" = 'config' ] ; then

    if [ "$CURRENT_USER" = "" ] ; then
      echo "Error: Unable to determine identity of current user"
    fi
  
    if [ "$CURRENT_USER" != "$ACE_OWNER"  ] ; then
  
      echo "You must be root or the RSA Authentication Manager owner"
      echo "in order to run 'sdsetup -config'."
      echo "Please 'su' to root or log out and log in as root."
      abort_installation
    fi
  
  else
    echo "You must be root in order to run 'sdsetup -$INSTALL_TYPE'."
    echo "Please 'su' to root or log out and log in as root."
    abort_installation    
  fi
fi

}

##############################################################################
# get_ace_version()
# Get RSA Authentication Manager version number from file version.txt
# SOURCE_DIR and ACE_INSTALL_DIR are defined in get_install_directory()
# INSTALL_TOOLS_DIR is defined in verify_sdinstall_dir()
##############################################################################
get_ace_version()
{
  LOCALDIR="$USR_ACE"
  
  if [ -f $INSTALL_TOOLS_DIR/getacev ]; then
      CUR_ACE_VERSION=`$INSTALL_TOOLS_DIR/getacev $ACE_INSTALL_DIR`
      LOCALDIR="$ACE_INSTALL_DIR"
  elif [ -f $USR_ACE/getacev ]; then
      CUR_ACE_VERSION=`$USR_ACE/getacev $USR_ACE`
  else
      echo "Cannot find file 'getacev'. Please make sure the CD is mounted correctly"
      echo "and run 'sdsetup' again. "
      abort_installation
  fi

  if [ "$?" != "0" ] ; then
    echo "'sdsetup' failed to get $SERVER_NAME version number from file"
    echo "'$LOCALDIR/version.txt'."
    echo "Verify that the CD is mounted correctly and run 'sdsetup' again."
    abort_installation
  else
    ACE_VERSION=`echo "$CUR_ACE_VERSION" | sed -e "s/\./ /g" | awk '{ print $1"."$2 }'`
  fi
}





##############################################################################
# verify_sdinstall_dir ()
# The INSTALL_TOOLS_DIR variable will be set and checked 
# based on the ACE_INSTALL_DIR variable
##############################################################################
verify_sdinstall_dir()
{
  INSTALL_TOOLS_DIR=$ACE_INSTALL_DIR/sdinstall

  if [ ! -d $INSTALL_TOOLS_DIR ] ; then
    echo "The installation directory 'sdinstall' cannot be found in"
    echo "'$ACE_INSTALL_DIR'."
    echo "The "$INSTALL_TYPE" option must be installed using the 'sdsetup'"
    echo "utility located on the $SERVER_NAME installation CD.  Verify that"
    echo "the CD is properly mounted and run 'sdsetup' again."
    abort_installation
  fi
  cd "$SOURCE_DIR"
}

##############################################################################
# get_db_version()
# Get RSA Authentication Manager version number from file version.txt in ace/data
##############################################################################
get_db_version()
{
  CUR_DB_VERS=`$USR_ACE/getacev $VAR_ACE`
  if [ "$?" != "0" ] ; then
    echo "'sdsetup' failed to get $SERVER_NAME DB version number from file version.txt."
    echo "Please make sure that version.txt is in the current working directory."
    abort_installation
  fi
}





##############################################################################
# startup_screens()
# Display copyright information, welcome screens, etc.  Should be
# incorporated in this file to minimize installation files.
##############################################################################
startup_screens()
{
  if [ "$INSTALL_TYPE" = "$PRIMARY" -o "$INSTALL_TYPE" = "$REPLICA" ] ; then 
    print_license
    $CLEAR_EXEC
  fi

  if [ "$SILENT_MODE" != "TRUE" ] ; then
     print_copyright
     print_install_warning
  fi
}

##############################################################################
# check_silent_mode()
# Check to see if user wants to run in silent mode. Currently this is determined because
# the user has specified the file owner and directory on the sdsetup command line.
##############################################################################
check_silent_mode()
{
  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
    if [ -n "$OWNER_NAME" -a -n "$PATH_ROOT" ] ; then
      SILENT_MODE=TRUE
    fi
  elif [ "$INSTALL_TYPE" = "$REPLICA" ] ; then
    if [ -n "$OWNER_NAME" -a -n "$PATH_ROOT" ] ; then
      SILENT_MODE=TRUE
    fi
  elif [ "$INSTALL_TYPE" = "$AGENT" ] ; then
    if [ -n "$OVERWRITE" -a -n "$PATH_ROOT" ] ; then
      SILENT_MODE=TRUE
    fi
  fi
}

##############################################################################
# print_copyright()
##############################################################################
print_copyright()
{
  echo ""
  if [ "$SILENT_MODE" = FALSE ] ; then
    if [ -n "$ACE_INSTALL_DIR" -a -r $ACE_INSTALL_DIR/copyright.txt ] ; then
      cat $ACE_INSTALL_DIR/copyright.txt
    elif [ -r $USR_ACE/copyright.txt ] ; then
      cat $USR_ACE/copyright.txt
    else
      echo "Cannot find copyright information. Aborting sdsetup."
      abort_installation
    fi
    echo "
*****************************************************************************
* This software  is proprietary  and  confidential  to  RSA Security  Inc., *
* is  furnished  under a license,  and  may  be used  and  copied  only  in *
* accordance  with the terms of such license and with the  inclusion of the *
* above  copyright notice.  This software or any  copies thereof may not be *
* provided or otherwise made  available to any other person. No title to or *
* ownership of the  software is hereby transferred. Any unauthorized use or *
* reproduction  of  this  software  may  be  subject to  civil  or criminal *
* liability.                                                                *
*                                                                           *
* This  software  is subject  to change  without  notice and  should not be *
* construed as a commitment by RSA Security Inc.                            *
*****************************************************************************
"
    echo_no_nl 'Press <Enter> to continue'
    input=`$LINE_EXEC`
    $CLEAR_EXEC
  fi
}


##############################################################################
# print_install_warning()
##############################################################################
print_install_warning()
{
  echo ""
  echo "    !!!!!!!!!!!!!!!!!!!!!!!!!! WARNING !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  echo "    !!                                                             !!"
  echo "    !! You  may  abort  the  installation  at  any  time  prior to !!"
  echo "    !! completion by pressing CTRL+C .                             !!"


# Customize the message.  If -config is run the installation will not be removed.

  if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
        "$INSTALL_TYPE" = "$REPLICA" -o \
        "$INSTALL_TYPE" = "$AGENT" ] ; then
  echo "    !! A full cleanup will be performed before termination.        !!"
  fi

  echo "    !!                                                             !!"
  echo "    !! If you require assistance with the installation, please     !!"
  echo "    !! see the section \"Getting Support and Service\" in the        !!"
  echo "    !! RSA Authentication Manager for UNIX Installation Guide      !!"
  echo "    !! (aceservdoc\unix_install.pdf on the RSA Authentication      !!"
  echo "    !! Manager CD) for information about contacting technical      !!"
  echo "    !! support.                                                    !!"
  echo "    !!                                                             !!"
  echo "    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"

  echo_no_nl 'Press <Enter> to start installation'
  input=`$LINE_EXEC`
  $CLEAR_EXEC
}

##############################################################################
# print_warning()
##############################################################################
print_warning()
{
# Display the warning text .
  echo ""
  echo "                UPGRADE WARNINGS"
  echo ""
  echo "     Before you upgrade, back up your database."
  echo "     If you have an active Replica, reconcile your"
  echo "     database before upgrading.  If you do not have"
  echo "     an active Replica, ignore reconciliation messages."
  echo ""

#
# After viewing the warning, a choice must be made whether
# to continue or abort the install.
#
    create=""
    until [ -n "$create" ] ;
    do
        echo_no_nl "(o = OK, c = Cancel) [c]:"
        create=`$LINE_EXEC`
        if [ "$create" = '' ] ; then
          create='c'
        fi
        case "$create"
        in
          'o' ) continue;;
# OK to proceed with the installation
          'c' ) abort_installation;;
           *  ) echo ""
                create=""
                echo "Enter one of the choices.";;
        esac
    done
}

##############################################################################
# print_license()
# Display the license text that came with the license if it exists.
# Otherwise, display the one that is part of the distribution. If a license
# cannot be found the installation will fail because it is a necessary
# legal issue. Even silent mode will display the license and prompt the
# user to be sure that they agree with its terms.
##############################################################################
print_license()
{
    if [ -f ./license.sh ] ; then
      ./license.sh
    elif [ -f $ACE_INSTALL_DIR/sdinstall/license.sh ] ; then
      $ACE_INSTALL_DIR/sdinstall/license.sh
    else
      echo "The License Agreement could not be found."
      echo "Installation is aborting..."
      abort_installation
    fi
    if [ "$?" != "0" ] ; then
      abort_installation
    fi
}

##############################################################################
# setup_owner_name()
#   verify_name()
#   get_owner_name()
# Prompt for the name of the file owner. (Only for primary installations.
# agents have a default ownername of root)
##############################################################################
setup_owner_name()
{
  valid_name=FALSE

  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
    if [ -n "$OWNER_NAME" ] ; then
      verify_name "$OWNER_NAME"
      if [ "$valid_name" = FALSE ] ; then
        get_owner_name
      fi
    else
      echo ""
      echo "Specify the login name of the administrator who owns the"
      echo "$SERVER_NAME directories and files."
      echo "This administrator name must belong to a secure group"
      echo "that will be allowed to access these directories."
      get_owner_name
    fi
  elif [ "$INSTALL_TYPE" = "$AGENT" ] ; then
    OWNER_NAME="root"
  fi
  $CLEAR_EXEC
}

##############################################################################
# verify_name()
##############################################################################
verify_name()
{
  test_name=$1
  valid_name=FALSE

  if [ "`$INSTALL_TOOLS_DIR/sdcfgval validate_owner $test_name`" = "" ] ; then
    echo ""
    echo "Login name '$test_name' does not exist.  Please specify another"
    echo "login name."
  else
    valid_name=TRUE
  fi


  GROUPNAME="`$INSTALL_TOOLS_DIR/sdcfgval get_groupname $test_name`"
  if [ "$GROUPNAME" = "" ] ; then
    echo "Group name for user '$test_name' does not exist in /etc/group"
    echo "Please specify another user or add group to group file"
    valid_name=FALSE
  fi
}

##############################################################################
# get_owner_name()
##############################################################################
get_owner_name()
{
  until [ "$valid_name" = TRUE ] ;
  do
    test_owner=""
    until [ -n "$test_owner" ] ;
    do
      echo ""
      echo_no_nl "Which administrator will own the $SERVER_NAME files? "
      test_owner=`$LINE_EXEC`
    done

    getyesorno TRUE "You have specified administrator '$test_owner'. Is this correct: (y/n/q) [y]: "
    if [ "$YESORNO" != TRUE ] ; then
      test_owner=""
      continue
    fi
    verify_name "$test_owner"
# We have a good name so now we will check if he is root
    if [ "$test_owner" != "root" ] ; then
        echo ""
        echo "The owner that you specified for the RSA Authentication Manager is not root."
        echo "If that is correct, you must synchronize the time between the Primary"
        echo "and Replica Servers either by using a reliable time service such as NTP"
        echo "or by allowing the RSA replication service to run as a root level process."
        getyesorno TRUE "Do you want to continue? (y/n/q) [y]: "
        if [ "$YESORNO" != TRUE ] ; then
            test_owner=""
            valid_name=FALSE
            continue
        fi
        echo ""
        echo "Setup can make the RSA replication service a root level process"
        echo "so that it synchronizes the time between the Primary and Replica."
        echo "Otherwise, you must use a reliable time synchronization service"
        echo "such as NTP."
        getyesorno TRUE "Do you want to make the replication service a root level process? (y/n/q) [y]: "
        if [ "$YESORNO" = TRUE ] ; then
            REPLICATION_ELEVATED=TRUE
        fi

    fi
  done
  
  OWNER_NAME="$test_owner"
}


##############################################################################
#get_rep_ace()
# Get the name of the replica package directory, REP_ACE, and other related variables
# that are related. This is only done on
##############################################################################
get_rep_ace()
{
  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then 
   DEF_REP_ACE="$VAR_ACE/data_base/"
  else
   DEF_REP_ACE=""
  fi

  if [ -z "$REP_ACE" ] ; then
   REP_ACE="$DEF_REP_ACE"
  fi

 until [ -n "$test_dir" ] ; 
  do
    test_dir=""
      echo ""
  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then 
      echo_no_nl "What is the name of the Replica Package directory [$REP_ACE] ? "
  else
      echo_no_nl "What is the name of the Replica Package directory ? "
  fi
      test_dir=`$LINE_EXEC`
    if [ -z "$test_dir" ] ; then
      test_dir="$DEF_REP_ACE"
    fi
    getyesorno TRUE "You have specified directory '$test_dir'. Is this correct: (y/n/q) [y]: "
    if [ "$YESORNO" != TRUE ] ; then
      test_dir=""
      continue
    fi
  # Is that really a directory?
   if [ -d "$test_dir" -a "$INSTALL_TYPE" = "$REPLICA" ] ; then
   :
   else
      echo "Replica Package directory must exist.  Please specify existing directory."
      test_dir=""
   fi
  done

   REP_ACE="$test_dir" 
   REP_ACE_DB="$REP_ACE/database"; export REP_ACE_DB
   REP_ACE_LICENSE="$REP_ACE/license"; export REP_ACE_LICENSE
   SDREPNODES="$REP_ACE_LICENSE/sdrepnodes.txt"; export SDREPNODES
}


##############################################################################
# setup_install_path()
# Prompt for the location of the top level directory path.
# If it doesn't exist, ask whether the user wants to abort, shell, or create.
##############################################################################
setup_install_path()
{

  if [ -z "$PATH_ROOT" ] ; then
    echo ""
    echo "You must specify a top level directory path where the $SERVER_NAME"
    echo "software should reside."
  else
    test_path="$PATH_ROOT"
    verify_path
  fi
  
  until [ -n "$test_path" ]
  do
    echo ""
    echo_no_nl "Enter the top level directory path: "
    test_path=`$LINE_EXEC`
    case "$test_path" in
      'quit' ) abort_installation;;

        *     )  if [ "$test_path" = "" ] ; then
                     continue
                  fi
                  getyesorno TRUE "You have specified '$test_path'. Is this correct? (y/n/q) [y]: "
                  if [ "$YESORNO" = FALSE ] ; then
                    test_path=""
                    continue
                  fi

                  PATH_ROOT="$test_path"
                  verify_path
    esac
  done

#
# Set the new environment variables
#
  
  # Make sure PATH_ROOT is an absolute pathname
  cd "$test_path"
  PATH_ROOT=`pwd`

  cd "$SOURCE_DIR"

  export_our_paths
  $CLEAR_EXEC
}

##############################################################################
# export_our_paths()
##############################################################################
export_our_paths()
{
  USR_ACE="$PATH_ROOT/ace/prog";export USR_ACE
  VAR_ACE="$PATH_ROOT/ace/data";export VAR_ACE
  DLC="$PATH_ROOT/ace/rdbms";export DLC
  DLC_PROUTIL="$DLC/bin/proutil";export DLC_PROUTIL
  PROTERMCAP="$PATH_ROOT/ace/rdbms/protermcap";export PROTERMCAP
  PROPATH="$USR_ACE/proapi/adbapi.pl,$USR_ACE/proapi/sdproapi.pl,$USR_ACE,$USR_ACE/protrig";export PROPATH
}

##############################################################################
# verify_path()
# Determine if the location specified to install the RSA ACE software exists and
# contains a release.  If it's not there, proceed with install.  If it is there
# then must decide to either overwrite, respecify, or abort the installation.
##############################################################################
verify_path()
{

#
# Remove trailing '/'
#
  last_char=`echo $test_path | awk '{print substr($1, length($1), 1)}'`
  if [ "$last_char" = "/" ] ; then
    test_path=`echo $test_path | awk '{print substr($1, 1, length($1)-1)}'`
  fi

# check to see if its a new installation
  if [ -d "$test_path/ace/data" -a \
        -f "$test_path/ace/data/sdconf.rec" -a \
        -f "$test_path/ace/data/server.cer" -a \
        -f "$test_path/ace/data/server.key" -a \
        -f "$test_path/ace/data/license.rec" -a \
        -f "$test_path/ace/data/sdti.cer" -a \
        -f "$test_path/ace/data/version.txt" ] ; then
    NEW_INSTALLATION=FALSE
    CUR_DB_VERS=`$INSTALL_TOOLS_DIR/getacev -f $ACE_INSTALL_DIR`
    ORIG_DB_VERS=`$INSTALL_TOOLS_DIR/getacev -f "$test_path/ace/data"`
    if [ "$CUR_DB_VERS" = "$ORIG_DB_VERS" ] ; then
        PRESERVE_DB=TRUE
        # we must set up var_ace to check validity of install
        # it will be set to this eventually anyeway, if we are successful
    else
# Check that we can upgrade from this version
        ORIG_MJ_MN=`echo "$ORIG_DB_VERS" | awk '{print substr($1, 1, 3)}'`
        CUR_MJ_MN=`echo "$CUR_DB_VERS" | awk '{print substr($1, 1, 3)}'`        
        if [ "$ALLOWED_V" -gt "$ORIG_MJ_MN" ] ; then
# No upgrade from less then ALLOWED_V
            CUR_DB_VERS=`$INSTALL_TOOLS_DIR/getacev $ACE_INSTALL_DIR`
            ORIG_DB_VERS=`$INSTALL_TOOLS_DIR/getacev "$test_path/ace/data"`
            echo "$SERVER_NAME $ORIG_DB_VERS software can't be upgraded"
            echo "directly to version $CUR_DB_VERS."
            echo "Upgrade current installation at least to version $ALLOWED_VP"
            echo "and try again."
            abort_installation 
        elif [ "$CUR_DB_VERS" -lt "$ORIG_DB_VERS" ] ; then
# We can upgrade but do we upgrade to newer version than the original one?
# it turned out that we upgrade to earlier version
            WARN_UPGRADE=TRUE
            PRESERVE_DB=FALSE
        elif [ "$CUR_MJ_MN" = "$ORIG_MJ_MN" ] ; then 
# The version we try to install is greater than the one we already have.
# Do we need to preserve database? May be it is just software upgrade...
# We looked at only major minor and if they are same we should preserve
# database 
            PRESERVE_DB=TRUE
        else
# Just upgrade
            PRESERVE_DB=FALSE
        fi
    fi
    VAR_ACE="$test_path/ace/data"; export VAR_ACE
    check_valid_install
# Now also just for reference check the existence of the DUMPS
    if [ -f "$VAR_ACE/sdserv.dmp" ] ; then
      SERV_DUMP_EXISTS=TRUE
    fi
    if [ -f "$VAR_ACE/sdlog.dmp" ] ; then
      LOG_DUMP_EXISTS=TRUE
    fi
 
    
  else
      OK_TO_WIPE_OUT_ACE=TRUE
      NEW_INSTALLATION=TRUE
  fi
  
  if [ -d "$test_path/ace/prog" -a -f "$test_path/ace/prog/version.txt" ] ; then
    if [ -z "$OVERWRITE" ] ; then
      echo ""
      echo "An $SERVER_NAME installation is detected in '$test_path/ace'."
      echo ""
      if [ "$WARN_UPGRADE" = TRUE ] ; then
        echo "Currently installed version of $SERVER_NAME software"
        echo "is later than the version being installed."
        echo "If you choose to install over the existing database"
        echo "will be destroyed."  
        echo "Do you want to install over '$test_path/ace' directory?"
      else
        echo "Do you want to install over this directory?"
      fi

      validchoice=""
      until [ -n "$validchoice" ] ;
      do
        echo_no_nl "(y = overwrite/upgrade, r = respecify, q = quit) [y]: "
        create=`$LINE_EXEC`
        if [ "$create" = "" ] ; then
          create='y'
        fi
        case "$create"
        in
          'y' )
# Determine if the server and log databases in ./ace/data
# are currently busy.  If they are busy, then abort.

                if [ "$WARN_UPGRADE" = TRUE ] ; then
        	    OK_TO_WIPE_OUT_ACE=TRUE
                    NEW_INSTALLATION=TRUE
                elif [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
                    print_warning
                fi

# In the case of primary upgrade figure out whether we want to use 
# dump files
                if [ "$INSTALL_TYPE" = "$PRIMARY" -a \
                     "$NEW_INSTALLATION" = FALSE -a \
                     "$PRESERVE_DB" = FALSE ] ; then
                    if [ "$SERV_DUMP_EXISTS" = TRUE ] ; then
                       USE_DUMP=FALSE
                       ask_about_dump "sdserv"
                       SERV_DUMP_EXISTS=$USE_DUMP
                    fi
                    if [ "$LOG_DUMP_EXISTS" = TRUE ] ; then
                       USE_DUMP=FALSE
                       ask_about_dump "sdlog"
                       LOG_DUMP_EXISTS=$USE_DUMP
                    fi
                fi

                OVERWRITE="yes"
                validchoice=TRUE
                DLC="$test_path/ace/rdbms"
                DLC_PROUTIL="$DLC/bin/proutil"                                
                preserve_ace_directory $test_path
                create_new_directory $test_path;;

          'r' ) test_path=""
                return;;
          'q' ) abort_installation;;
           *  ) echo ""
                 echo "Enter one of the choices.";;
        esac
     done
    elif [ "$OVERWRITE" = "no" ] ; then
      echo "The directory '$test_path/ace' already exists."
      echo "Installation is aborting..."
      abort_installation
    else
# must be yes, preserve contents of ace to ace_tmp
# Do not use dump files in silen overwrite mode
      SERV_DUMP_EXISTS=FALSE
      LOG_DUMP_EXISTS=FALSE
      preserve_ace_directory $test_path
      create_new_directory $test_path
      return
    fi
  else
    OVERWRITE="no"
    if [ -d "$test_path/ace" ] ; then
      preserve_ace_directory $test_path
    elif [ -d "$test_path/ace_tmp" ] ; then
      rm -rf "$test_path/ace_tmp"
    fi
    create_new_directory $test_path
  fi
}

##############################################################################
# ask_about_dump()
# Ask user if wants to use detected dump files
##############################################################################
ask_about_dump()
{
   dump_name="$1"
   
   echo ""
   echo "Installation has detected dump file $dump_name.dmp in the data"
   echo "directory of the existing installation. It is possible that"
   echo "this file could be out of date. It is not recommended that you"
   echo "use this file during the load operation unless you are absolutely"
   echo "sure that it is the most recent dump file. Database files are assumed"
   echo "to be most recent and will automatically be used by default"
   echo "during the migration."
   echo ""

   getyesorno FALSE "Do you want to use this dump file to migrate the database? (y/n) [n]: "
   if [ "$YESORNO" = FALSE ] ; then
      USE_DUMP=FALSE
   else
      USE_DUMP=TRUE
   fi
}


##############################################################################
# check_valid_install()
# Check to see if we are not installing a primary over a replica or vice versa
##############################################################################
check_valid_install()
{
     if [ "$PRESERVE_DB" = TRUE ] ; then

        PRIMARYNAME="`$INSTALL_TOOLS_DIR/sdcfgval primary | cut -d "." -f1`"
        HOSTNAME="`$INSTALL_TOOLS_DIR/sdcfgval current_host | cut -d "." -f1`" 

        if [ "$INSTALL_TYPE" = "$PRIMARY" -a \
           "$HOSTNAME" != "$PRIMARYNAME" ] ; then 
           echo "You can not upgrade a Replica Server to be the Primary Server."
           abort_installation
        elif [ "$INSTALL_TYPE" = "$REPLICA" -a \
           "$HOSTNAME" = "$PRIMARYNAME" ] ; then
           echo "You can not upgrade the Primary Server to be a Replica Server."
           abort_installation
        fi
     fi
        
}
##############################################################################
# check_if_enough_space()
# Check to see if there is enough space to back up the 
# ACE server before upgrading. This is called repeatedly so
# assume the best if the installation location is not defined.
##############################################################################
check_if_enough_space()
{
   echo "Checking disk space requirements..."
   case "$SYSUNAME"
   in
      'HP-UX' )
                dir="`df -b $PATH_ROOT | awk '{print($5)}'`";;
      'SunOS' )
                dir="`df -k $PATH_ROOT | sed -e "1,1d" | awk '{print($4)}'`";;
      'AIX'   )
                dir="`df -k $PATH_ROOT | sed -e "1,1d" | awk '{print($3)}'`";;
      'Linux' ) 
                dir="`df -k $PATH_ROOT | sed -e "1,1d" | awk '{print($4)}'`";;
   esac
   if [ $dir -lt $SPACE ]; then
      echo "Insufficient disk space to perform the RSA ACE server installation."
      echo "$SPACE kilobytes are required."
      echo ""
      abort_installation 
   fi
}

##############################################################################
# preserve_ace_directory()
# Move the current installation directory to a backup location.  
# Typically done when an installation is to be overwritten.
##############################################################################
preserve_ace_directory()
{
  root_path="$1"

  if [ -d "$root_path/ace_tmp" ] ; then
    rm -rf "$root_path/ace_tmp"
    err=$?
    if [ $err -gt 0 ] ; then
    echo "Failed to remove $root_path/ace_tmp"
    abort_installation
    fi
  fi

  DLC="$root_path/ace/rdbms"
  check_newdb_connections "$root_path/ace/data/sdserv" server
  check_newdb_connections "$root_path/ace/data/sdlog" log
  
  mv $root_path/ace $root_path/ace_tmp
  err=$?
  if [ "$err" = 0 ] ; then
      echo "Copying old version of $SERVER_NAME to  $root_path/ace_tmp..."
      OK_TO_WIPE_OUT_ACE=TRUE
  else
      echo "Failed to copy old version of $SERVER_NAME to $root_path/ace_tmp..."
      abort_installation
    fi   
}

##############################################################################
# create_new_directory()
# Creates the required directory hierarchy at the install location specified. 
##############################################################################
create_new_directory()
{
  root_path=$1

  OLDUMASK=`umask`
  umask 006
  if [ ! -d "$root_path" ] ; then
    mkdir -p "$root_path"
    chmod 775 "$root_path"
  fi
  mkdir -p "$root_path/ace"
  mkdir -p "$root_path/ace/prog"
  mkdir -p "$root_path/ace/data"
  mkdir -p "$root_path/ace/data/atkpools"
  mkdir -p "$root_path/ace/data/output"


  if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
       "$INSTALL_TYPE" = "$REPLICA" ] ; then
    mkdir -p "$root_path/ace/doc"
    mkdir -p "$root_path/ace/utils"
    if [ ! -d "$root_path/ace/rdbms" ] ; then
       mkdir -p "$root_path/ace/rdbms"
    fi
  fi

  # No need for replica package directory. It is cleared by newdb anyways.

  umask $OLDUMASK
}

##############################################################################
# setup_agent_config()
# For agent installations, verify that the sdconf.rec exists in the
# current working directory or the /ace_tmp/data directory
# once found, than copy the sdconf.rec to the ace/data directory
##############################################################################
setup_agent_config()
{
  if [ "$INSTALL_TYPE" = "$AGENT" ] ; then
    if [ ! -f "$SOURCE_DIR/sdconf.rec" -a \
          ! -f "$PATH_ROOT/ace_tmp/data/sdconf.rec" ] ; then
      $CLEAR_EXEC
      echo "Unable to locate configuration file. If you are installing an agent, your current"
      echo "working directory or $VAR_ACE must contain the sdconf.rec file."
      abort_installation
    else
      if [ -f "$SOURCE_DIR/sdconf.rec" ] ; then
        cp $SOURCE_DIR/sdconf.rec "$PATH_ROOT/ace/data"
      elif [ -f "$PATH_ROOT/ace_tmp/data/sdconf.rec" ] ; then
        cp $PATH_ROOT/ace_tmp/data/sdconf.rec "$PATH_ROOT/ace/data"
      fi
    fi
  fi
}

##############################################################################
# find_license_config()
# For primary verify that the server.cer, sdti.cer, server.key and license.rec 
# exists in either the current working directory or the temporary ./ace_tmp/data
# directory.
# For replica, verify the above 4 file and the sdconf.rec file exists in the
# replica_package/license directory
##############################################################################
find_license_config()
{
  license_certs="license.rec server.key sdti.cer server.cer"
  not_found=""

  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
    #
    # see if the license record is in the source directory is upper case.
    #    If so, we'll assume all the files are upper case. Currently no
    #    no support for mixed file cases.
    #
    if [ -f $SOURCE_DIR/LICENSE.REC ] ; then
       INSTALL_FILES_ARE_UPPERCASE=TRUE
       license_certs="`echo $license_certs | $TR_EXEC a-z A-Z`"
    fi
    for atfil in $license_certs
    do
      if [ ! -f "$SOURCE_DIR/$atfil" -a  \
            ! -f "$PATH_ROOT/ace_tmp/data/$atfil"  ] ; then
        not_found="$not_found $atfil"
      fi
    done
  elif [ "$INSTALL_TYPE" = "$REPLICA" ] ; then
    license_certs="$license_certs sdconf.rec"
    if [ "$PRESERVE_DB" = FALSE ] ; then
      REPFILE_SRC_DIR=$REP_ACE_LICENSE
    else
      REPFILE_SRC_DIR=$PATH_ROOT/ace_tmp/data
    fi   
    for atfil in $license_certs
    do
      if [ ! -f "$REPFILE_SRC_DIR/$atfil"   ] ; then
        not_found="$not_found $atfil"
      fi
    done
  fi

  if [ ! -z "$not_found" ] ; then
    $CLEAR_EXEC
    echo "Unable to locate the following files:"
    for atfil in $not_found
    do
      echo "- $atfil"
    done
    if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
      echo ""
      echo "A Primary Server installation requires that the server.cer (Server Certificate),"
      echo "server.key (Certificate Key), sdti.cer (SDTI Certificate) and the license.rec"
      echo "files exist in your current working directory."
      echo "If you do not have these files, see the section" 
      echo "\"Getting Support and Service\" in the"
      echo "$SERVER_NAME for UNIX Installation Guide"
      echo "(aceservdoc/unix_install.pdf on the $SERVER_NAME CD)"
      echo "for information about contacting technical support."
      abort_installation
    elif [ "$INSTALL_TYPE" = "$REPLICA" ] ; then
      echo "" 
      echo "A Replica server installation requires that the"
      echo "server.cer (Server Certificate), server.key (Certificate Key)"
      echo "sdti.cer (SDTI Certificate), sdconf.rec (Configuration)"
      echo "and the license.rec files"
      echo "exist in the $REP_ACE_LICENSE directory."
      abort_installation
    fi
  fi

  # Validate repnodes
  if [ "$INSTALL_TYPE" = "$REPLICA" -a  "$PRESERVE_DB" = FALSE ] ; then
     validate_repnodes
     if [ "$?" != "0" ] ; then
         abort_installation
     fi 
  fi
}

##############################################################################
# setup_license_config()
# this function is used during primary/replica installs
# it is used to setup the license files, the sdconf.rec file
# and copy the certificate files to the ace/data directory
##############################################################################
setup_license_config()
{
  license_path=""
  copy_list="server.cer sdti.cer server.key"

  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
    setup_primary_license_file
    
    if [ "$NEW_INSTALLATION" = TRUE ] ; then
      license_path="$SOURCE_DIR"
      #
      # if we're a new installation and the files are upper case,
      #     convert the list.
      #
      if [ "$INSTALL_FILES_ARE_UPPERCASE" = "TRUE" ] ; then
         copy_list="`echo $copy_list | $TR_EXEC a-z A-Z`"
      fi
    else
      license_path="$PATH_ROOT/ace_tmp/data"
      copy_list="$copy_list sdconf.rec" 
    fi
    
    for atfil in $copy_list
    do
      cp $license_path/$atfil "$PATH_ROOT/ace/data/`echo $atfil | $TR_EXEC A-Z a-z`"
    done
    #
    # ensure primary and this host are set.   -setup performs update if
    #     a config record already exists
    #
    if $INSTALL_TOOLS_DIR/sdconfig -setup des $OWNER_NAME ; then
      :
    else
      abort_installation
    fi
  
  elif [ "$INSTALL_TYPE" = "$REPLICA" -a "$PRESERVE_DB" = FALSE ] ; then
    copy_list="$copy_list license.rec sdconf.rec"

    for atfil in $copy_list
    do
      cp $REP_ACE_LICENSE/$atfil "$PATH_ROOT/ace/data"
    done
    # We still need to create conf record here
    # though it will be updated later
    # when we apply the package
    # Without configuration record the Replica Management will not work
    #
    # ensure this host is set. primary should be left alone.
    #
    if $INSTALL_TOOLS_DIR/sdconfig -upgrade ; then
          :
    else
      abort_installation
    fi
    
    ask_about_ep_replica "$INSTALL_TOOLS_DIR"

  elif [ "$INSTALL_TYPE" = "$REPLICA" -a "$PRESERVE_DB" = TRUE ] ; then
    copy_list="$copy_list license.rec sdconf.rec"

    for atfil in $copy_list
    do
      cp $PATH_ROOT/ace_tmp/data/$atfil "$PATH_ROOT/ace/data"
    done
    # Here we do not touch configuration record - preserve what we had before
  fi
}

##############################################################################
# The procedure will ask about priveleges on replica
##############################################################################
ask_about_ep_replica()
{
    UTL_PATH="$1"

    ONAME="`$UTL_PATH/sdcfgval ownername`"

    if [ "$ONAME" != "root" ] ; then

        echo "The owner of the RSA Authentication Manager is not root."
        echo "Setup can make the RSA replication service a root level process"
        echo "so that it synchronizes the time between the Primary and Replica."
        echo "Otherwise, you must use a reliable time synchronization service"
        echo "such as NTP."
        getyesorno_noabort TRUE "Do you want to make the replication service a root level process? (y/n) [y]: "
        if [ "$YESORNO" = TRUE ] ; then
            REPLICATION_ELEVATED=TRUE
        fi        
    fi
}
##############################################################################
# migrate_license_file()
# Does license conversion during upgrade
# Converts license to v4 if it is v3. Do not do anything if it is v4
##############################################################################
migrate_license_file()
{
  lic_file=$1

  if [ "$INSTALL_TYPE" = 'license' ] ; then
    LIC_EXEC="$USR_ACE/rsalicutil"
  else
    LIC_EXEC="$INSTALL_TOOLS_DIR/rsalicutil"
  fi

  if [ ! -x $LIC_EXEC ] ; then
    echo "'sdsetup' could not find program 'rsalicutil'."
    abort_installation
  fi

  if [ ! -f "$lic_file" ] ; then
    echo ""
    echo "Original license file is not found."
    abort_installation
  fi

  $CHMOD_EXEC 660 $lic_file
  $LIC_EXEC -t -u $lic_file
  RET_CODE="$?"
  if [ "$RET_CODE" != "0" ] ; then
    execute_error "rsalicutil"
  fi
}


##############################################################################
# make_license_file()
# Create a new security block key for the license.rec file.
# (For new primary server database installations only)
##############################################################################
make_license_file()
{
  lic_file=$1

  LIC_EXEC="$INSTALL_TOOLS_DIR/rsalicutil"

  if [ ! -x $LIC_EXEC ] ; then
    echo "'sdsetup' could not find program 'rsalicutil'."
    abort_installation
  fi


  if [ ! -f "$lic_file" ] ; then
    echo ""
    echo "License file is not found."
    abort_installation
  fi

  $CHMOD_EXEC 660 $lic_file

# check that the V4 license has not expired
  REP_LIC=`$LIC_EXEC -s -f "$lic_file" "iexpired"`
  RET_CODE="$?"
  if [ "$RET_CODE" != "0" ] ; then
    execute_error "rsalicutil"
  fi
  if [ "License Expired" = "$REP_LIC" ] ; then
    echo ""
    echo "The license you selected has expired."
    abort_installation
  fi

# make the license by generating new license key
  $LIC_EXEC -t -m $lic_file
  RET_CODE="$?"
  if [ "$RET_CODE" != "0" ] ; then
    execute_error "rsalicutil"
  fi
}


##############################################################################
# upgrade_license_file
# Called only when user upgrades license i.e. sdsetup -license
# or at the very end of the upgrade when user presented new license
# For license upgrades, copy the appropriate license.rec file
# to the ace/data directory.
##############################################################################
upgrade_license_file()
{
    lic_file=$1
    
    if [ -f $lic_file ] ; then

       cp $VAR_ACE/license.rec $VAR_ACE/license.old
       $CHMOD_EXEC 660 $VAR_ACE/license.old
       cp $lic_file $VAR_ACE/license.rec

# Now do license upgrade

       $CHMOD_EXEC 660 $VAR_ACE/license.rec
       $USR_ACE/rsalicutil -t -a $VAR_ACE/license.old $VAR_ACE/license.rec

# Check the results
   
       err=$?
       if [ $err -gt 0 ] ; then
# 105 is RefuseToApply and 106 is UserCancel so don't print Fail msg
           if [ $err -ne 105  -a  $err -ne 106 ] ; then
              echo "License upgrade failed. Error ($err)."
           fi
           echo "Restoring original license..."
           rm $VAR_ACE/license.rec
           mv $VAR_ACE/license.old $VAR_ACE/license.rec
           UPGRADE_SUCCESS=FALSE
# No abort since the user can apply license manually
       else
           UPGRADE_SUCCESS=TRUE
       fi
    else
       echo "New license file is not found."
    fi
# change the file owner and permission after upgrade
    cd $USR_ACE
    OWNER_NAME="`$USR_ACE/sdcfgval ownername`"
    GROUPNAME="`$USR_ACE/sdcfgval ownergroup`"
    "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/license.rec
    "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/license.rec
   


}


##############################################################################
# check_license_limit
# Called at the end of the primary installtion or upgrade
# will check the the users and replicas against the license.
##############################################################################
check_license_limit()
{
# If that fails there is no harm.
# License can remain in the upgrade violation mode. 
# The hourly license check will take care of the problem
# if the installation is not corrupt so that it it not
# usable.

    echo ""
    $USR_ACE/rsalicutil -p -c $VAR_ACE/license.rec

# Check the results
   
    err=$?
    if [ $err -gt 0 ] ; then
       echo "License check failed..."
    fi
}


##############################################################################
# setup_primary_license_file
# For primary installation, copy the appropriate license.rec file
# to the ace/data directory.
##############################################################################
setup_primary_license_file()
{


  #
  # we'll take the files from the source directory in upper case only,
  #    once we have the files, they'll always be lower case.
  #
  if [ "$INSTALL_FILES_ARE_UPPERCASE" = "TRUE" ] ; then
     SOURCE_DIR_LICENSE_FILENAME="$SOURCE_DIR/LICENSE.REC"
  else
     SOURCE_DIR_LICENSE_FILENAME="$SOURCE_DIR/license.rec"
  fi

  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then

# If both an old license.rec and a new license.rec exist, then this is an
# upgrade, otherwise this is a new install.
    if [ -f "$PATH_ROOT/ace_tmp/data/license.rec"  -a \
         -f "$SOURCE_DIR_LICENSE_FILENAME" ] ; then

      
      cp "$PATH_ROOT/ace_tmp/data/license.rec" \
            "$PATH_ROOT/ace/data/license.rec"

      migrate_license_file "$PATH_ROOT/ace/data/license.rec"

      APPLY_NEW_LICENSE=TRUE

# It is a new software install with a new license.    
    elif [ -f "$SOURCE_DIR_LICENSE_FILENAME" ] ; then

      cp "$SOURCE_DIR_LICENSE_FILENAME" "$PATH_ROOT/ace/data/license.rec"
      make_license_file "$PATH_ROOT/ace/data/license.rec"
    
# It is a software upgrade with no new license information.
    elif [ -f "$PATH_ROOT/ace_tmp/data/license.rec" ] ; then

      cp "$PATH_ROOT/ace_tmp/data/license.rec" \
          "$PATH_ROOT/ace/data/license.rec"
      migrate_license_file "$PATH_ROOT/ace/data/license.rec"
    fi
  fi
}

##############################################################################
# get_licval()
# This routine obtains the license option from the specified license file.
##############################################################################
get_licval()
{
  which_opt=$1
  which_lic=$2

  if [ -f "$INSTALL_TOOLS_DIR/rsalicutil" ] ; then
    SDLICVAL_EXEC="$INSTALL_TOOLS_DIR/rsalicutil"
  elif [ -f "$USR_ACE/rsalicutil" ] ; then
    SDLICVAL_EXEC="$USR_ACE/rsalicutil"
  else
    echo "Error - Could not locate installation utilities.  Verify"
    echo "USR_ACE and try executing 'sdsetup' from the Installation CD. "
    abort_installation
  fi

  result="`$SDLICVAL_EXEC -t -f "$which_lic" "$which_opt"`"
  if [ "$?" = "1" ] ; then
    abort_installation
  fi
}

##############################################################################
# install_files()
# Copy files to the ace/prog and ace/rdbms directories.
##############################################################################
install_files()
{
  if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
       "$INSTALL_TYPE" = "$REPLICA" ] ; then
    echo ""
    echo "If you have not done so already, ensure that the system time is set"
    echo "accurately. To obtain the current Coordinated Universal Time"
    echo "(UTC) you can call a reliable time service. You can call the "
    echo "following United States telephone number +1 303-499-7111." 
    echo ""
    echo "The system clocks on the Primary and Replica Servers" 
    echo "must be set to the same time (to within one minute)."
    echo ""
    echo "The overall installation may take from 5 to 90 minutes."

    if [ ! -f "$ACE_INSTALL_DIR/$SERVER_SOFTWARE" ] ; then
      echo ""
      echo "Problem reading '$ACE_INSTALL_DIR/$SERVER_SOFTWARE';"
      echo "install aborting."
      abort_installation
    fi

    cd "$PATH_ROOT/ace"
    echo ""
    echo "The current time is `date`"
    echo "Moving $SERVER_NAME $INSTALL_TYPE_PRETTY software to"
    echo "'$USR_ACE'..."
    if $TAR_EXEC -xpf "$ACE_INSTALL_DIR/$SERVER_SOFTWARE"; then
      :
    else
      echo ""
      echo "Cannot complete server unpack. Check available disk space."
      abort_installation
    fi
    cd "$SOURCE_DIR"
    
    cd "$PATH_ROOT/ace/rdbms"
    echo ""
    echo "The current time is `date`"
    echo "Moving $SERVER_NAME database software to"
    echo "'$PATH_ROOT/ace/rdbms'..."
    if $TAR_EXEC -xpf "$ACE_INSTALL_DIR/$PROGRESS_SOFTWARE"; then
      :
    else
      echo ""
      echo "Cannot complete Progress unpack. Check available disk space."
      abort_installation
    fi
    uncompress_progress
    cd "$SOURCE_DIR"
  elif [ "$INSTALL_TYPE" = "$AGENT" ] ; then
    echo ""
    echo "Please be patient. The overall installation will take from 15 to 30 minutes."

    if [ ! -f "$ACE_INSTALL_DIR/$CLIENT_SOFTWARE" ] ; then
      echo ""
      echo "Problem reading '$ACE_INSTALL_DIR/$CLIENT_SOFTWARE';"
      echo "install aborting."
      echo "Please verify that 'sdsetup' is being executed from the"
      echo "aceagent installation directory."
      abort_installation
    fi

    cd "$PATH_ROOT/ace"
    echo ""
    echo "The current time is `date`"
    echo "Moving $SERVER_NAME $INSTALL_TYPE_PRETTY software to"
    echo "'$USR_ACE'..."
    if $TAR_EXEC -xpf "$ACE_INSTALL_DIR/$CLIENT_SOFTWARE"; then
      :
    else
      echo ""
      echo "Cannot complete $AGENT unpack. Check available disk space."
      abort_installation
    fi
    cd "$SOURCE_DIR"
  fi
}

##############################################################################
# edit_scripts()
# Put USR_ACE, VAR_ACE, and DLC values into scripts
##############################################################################
edit_scripts()
{
  echo ""
  echo "The current time is `date`"
  echo "Creating $SERVER_NAME $INSTALL_TYPE_PRETTY runtime scripts..."

# Be sure that the umask is properly set
  SCRPTUMSK=`umask`
  umask $USER_FULL_ACCESS

  cd "$PATH_ROOT/ace/prog"
  scriptfiles="`$LS_EXEC *.orig 2> /dev/null`"
  if [ -n "$scriptfiles" ] ; then
     if [ -f sdised.sed ] ; then
        rm -f sdised.sed
     fi

     echo "s!DEFVARACE=\"/var/ace\"!DEFVARACE=\"$VAR_ACE\"!" > sdised.sed
     echo "s!DEFUSRACE=\"/usr/ace\"!DEFUSRACE=\"$USR_ACE\"!" >> sdised.sed
     echo "s!DEFDLC=\"unknown\"!DEFDLC=\"$DLC\"!" >> sdised.sed

     for sedfile in $scriptfiles
     do
        outname=`basename $sedfile .orig`
        "$SED_EXEC" -f sdised.sed $sedfile > $outname
     done
     rm -f sdised.sed
  fi

  if [ "$INSTALL_TYPE" = "$PRIMARY" -o "$INSTALL_TYPE" = "$REPLICA" ] ; then
     cd "$PATH_ROOT/ace/utils"
     scriptfiles="`$LS_EXEC *.orig 2> /dev/null`"
     if [ -n "$scriptfiles" ] ; then
        if [ -f sdised.sed ] ; then
           rm -f sdised.sed
        fi

        echo "s!DEFVARACE=\"/var/ace\"!DEFVARACE=\"$VAR_ACE\"!" > sdised.sed
        echo "s!DEFUSRACE=\"/usr/ace\"!DEFUSRACE=\"$USR_ACE\"!" >> sdised.sed
        echo "s!DEFDLC=\"unknown\"!DEFDLC=\"$DLC\"!" >> sdised.sed
        echo "s!DEFRPTHOME=\"/usr/ace\"!DEFRPTHOME=\"$PATH_ROOT/ace/utils\"!" >> sdised.sed

        for sedfile in $scriptfiles
        do
           outname=`basename $sedfile .orig`
           "$SED_EXEC" -f sdised.sed $sedfile > $outname
        done
        rm -f sdised.sed
     fi
     
     # setup admenv script for the environ variables for the admin toolkit
     cd "$PATH_ROOT/ace/utils"
     echo "s!PLATFORM=\"unknown\"!PLATFORM=\"$PLATFORM\"!" > sdised.sed
     echo "s!DEFVARACE=\"/var/ace\"!DEFVARACE=\"$VAR_ACE\"!" >> sdised.sed
     echo "s!DEFUSRACE=\"/usr/ace\"!DEFUSRACE=\"$USR_ACE\"!" >> sdised.sed
     echo "s!DEFDLC=\"unknown\"!DEFDLC=\"$DLC\"!" >> sdised.sed
     "$SED_EXEC" -f sdised.sed admenv > tempenv
     mv tempenv admenv
     rm -f sdised.sed

#
     cd "$PATH_ROOT/ace/rdbms/bin"
     scriptfiles="`$LS_EXEC *.orig 2> /dev/null`"
     if [ -n "$scriptfiles" ] ; then
        if [ -f sdised.sed ] ; then
           rm -f sdised.sed
        fi

        echo "s!{DLC-.*}!{DLC-$PATH_ROOT/ace/rdbms}!g"  >> sdised.sed

        for sedfile in $scriptfiles
        do
           outname=`basename $sedfile .orig`
           "$SED_EXEC" -f sdised.sed $sedfile > $outname
           chmod 755 $outname
           rm $sedfile
        done
        rm -f sdised.sed
     fi
  fi

###################################################################
# The following block was added to replace the hard-coded Progress
# path in some of the Progress script files.  Since the Progress
# stuff we packed in the kit was from the build machine, the path
# used in some of the script files will be the path from the local
# build machine.  When the kit is installed on the customer's
# machine, the path in the script files will not exist.  The
# following statements replace the hard-coded path with the
# real directory that the user picks during the installation.
#
# NOTE: This behavior has been updated to create backup utilities 
# on both the primary and the replica and to create the sdbkup/
# sdrest utilities correctly (as symlinks to probkup/prorest).
# Bug #14512	
#
###################################################################
  if [ "$INSTALL_TYPE" = "$PRIMARY" -o "$INSTALL_TYPE" = "$REPLICA" ] ; then
     cd "$PATH_ROOT/ace/rdbms/bin"
     scriptfiles="`$GREP_EXEC -l \"\\\${DLC-\" * 2> /dev/null`"
     if [ -n "$scriptfiles" ] ; then
        if [ -f sdised.sed ] ; then
           rm -f sdised.sed
        fi

        echo "s!{DLC-.*}!{DLC-$PATH_ROOT/ace/rdbms}!g" > sdised.sed

        for sedfile in $scriptfiles
        do
           cp $sedfile $sedfile.orig
           "$SED_EXEC" -f sdised.sed $sedfile.orig > $sedfile
        done
        rm -f sdised.sed
     fi

    # Create the soft links for sdbkup and sdrest
    # on Replica Servers.
     if [ -f "probkup" ]; then
        $LN_EXEC -s probkup sdbkup
     fi
 
     if [ -f "prorest" ]; then
        $LN_EXEC -s prorest sdrest
     fi
  fi

  cd $SOURCE_DIR
  umask $SCRPTUMSK
}

##############################################################################
# uncompress_package()
# Untars and uncompresses the software.  Sets the source directory to
# point to the actual uncompressed software.
##############################################################################
uncompress_package()
{
  echo ""
  echo "The current time is `date`"
  echo "Uncompressing $SERVER_NAME $INSTALL_TYPE_PRETTY software..."
  INSTALL_DIR="$PATH_ROOT/ace/prog"

  if $FIND_EXEC $INSTALL_DIR -name "*.Z" -exec $UNCOMPRESS_EXEC {} \;
    then
      :
  else
      execute_error "$UNCOMPRESS_EXEC"
  fi

}


##############################################################################
# move_doc()
# Move all doc files from ace/prog/doc -> ace/doc
##############################################################################
move_doc()
{

  ACE_DOC_DIR="$ACE_INSTALL_DIR/../../aceservdoc"
  
  echo ""
  echo "The current time is `date`"
  echo "Moving README files into"
  echo "$PATH_ROOT/ace/doc..."
  EXBASE_DIR="$PATH_ROOT/ace"

  cd "$PATH_ROOT/ace"

  ## A copy of the primary readme file goes in BOTH the  ##
  ## directory installed from and the ace/doc directory. ##
  if [ -f "$PATH_ROOT/ace/prog/relnotes.txt" ] ; then
     cp $PATH_ROOT/ace/prog/relnotes.txt $SOURCE_DIR/README.TXT
     mv $PATH_ROOT/ace/prog/relnotes.txt $PATH_ROOT/ace/doc/README.TXT
  fi

  if [ -f "$PATH_ROOT/ace/prog/README.aceserv.prn" ] ; then
     mv $PATH_ROOT/ace/prog/README.aceserv.prn $PATH_ROOT/ace/doc/README.PRN
  fi

  if [ -f "$PATH_ROOT/ace/prog/relnotes.pdf" ] ; then
     mv $PATH_ROOT/ace/prog/relnotes.pdf $PATH_ROOT/ace/doc/README.pdf
  fi

# There should be no other documentation files in the prog directory
# all we need we have to copy from acesupp/doc
# If we have some doc or pdf files that are in prog, then they should be
# wiped from kit in the kibuild so they are not untared to prog directory. 

# Copy in the remaining doc files
  if [ -d "$ACE_DOC_DIR" ] ; then  
     echo "Moving Documentation files into"
     echo "$PATH_ROOT/ace/doc..."
     cp $ACE_DOC_DIR/* $PATH_ROOT/ace/doc
  fi

# The relnotes_unix.txt in prog directory are in UNIX format but the
# one in the doc is in NT lets just overwrite it. 

  if [ -f "$PATH_ROOT/ace/prog/relnotes_unix.txt" ] ; then
     cp $PATH_ROOT/ace/prog/relnotes_unix.txt $PATH_ROOT/ace/doc/relnotes_unix.txt 
  fi
}

##############################################################################
# move_utils()
# Move all utility files from ace/prog -> ace/utils
##############################################################################
move_utils()
{
  echo ""
  echo "The current time is `date`"
  echo "Moving all utility files into"
  echo "$PATH_ROOT/ace/utils..."
  UTBASE_DIR="$PATH_ROOT/ace"

  cd "$PATH_ROOT/ace"

  RPTUMSK=`umask`
  umask $USER_FULL_ACCESS

  mkdir utils/std_rpt
  mkdir utils/cust_rpt
  mkdir utils/output

  for utilfil1 in accepted.r attempts.r badpass.r badpin.r \
     assigned.r unassigned.r \
     disabled.r newpin.r slaveon.r wait1.r wait2.r

  do
      if [ -f "$PATH_ROOT/ace/prog/protty/$utilfil1" ] ; then
          cp $PATH_ROOT/ace/prog/protty/$utilfil1 $PATH_ROOT/ace/utils/std_rpt
      fi
  done

  for utilfil2 in rptconnect.orig rptrun.orig sdreport.orig \
     sdrpt-st.d sdrpt-st.df sdrpt.d1 sdrpt.b1 sdrpt.st sdrpt.db sdrpt.lg sdrunlis.df \
     rpt-strt.p run.p d-crt.w d-logbld.w logrpt.w \
     d-seltyp.w d-tokbld.w hstrpt.w tokrpt.w w-rpt.w w-usrinf.w w-usrinf-tty.w \
     w-usrsel.w w-usrsel-tty.w tokcol.i tokpipe.i logcol.i logpipe.i rpthead1.i \
     w-usrsel.w w-usrinf-tty.w w-usrsel-tty.w \
     tokcol.i tokpipe.i logcol.i logpipe.i rpthead1.i \
     rpthead2.i secure.i sdlogmsg.i
  do
    if [ -f "$PATH_ROOT/ace/prog/$utilfil2" ] ; then
      mv $PATH_ROOT/ace/prog/$utilfil2 $PATH_ROOT/ace/utils
    fi
  done
  
  cp  $PATH_ROOT/ace/prog/serv_ini.st $PATH_ROOT/ace/utils/sdrpt.st
  
  umask $RPTUMSK
}

##############################################################################
# move_adminutils()
# Move all admin utility files from ace/prog -> ace/utils
##############################################################################
move_adminutils()
{
  echo ""
  echo "The current time is `date`"
  echo "Moving all admin utility files into"
  echo "$PATH_ROOT/ace/utils..."
  UTBASE_DIR="$PATH_ROOT/ace"

# Create folders with proper permissions
  UTLUMSK=`umask`
  umask $USER_FULL_ACCESS 

  cd "$PATH_ROOT/ace"

  mkdir -p "$PATH_ROOT/ace/utils/tcl/bin"
  mkdir -p "$PATH_ROOT/ace/utils/toolkit"
 
# this stuff should be only installed on primary or replica
  if [ "$INSTALL_TYPE" = "$PRIMARY" -o "$INSTALL_TYPE" = "$REPLICA" ] ; then
    mkdir -p "$PATH_ROOT/ace/utils/oldutil" 
    for utilfil2 in emergency setpin resync repltok
    do
      if [ -f "$PATH_ROOT/ace/prog/$utilfil2" ] ; then
        mv $PATH_ROOT/ace/prog/$utilfil2 $PATH_ROOT/ace/utils/oldutil
      fi
    done
  else
    for utilfil2 in emergency setpin resync repltok
    do
      if [ -f "$PATH_ROOT/ace/prog/$utilfil2" ] ; then
        rm -f $PATH_ROOT/ace/prog/$utilfil2
      fi
    done
  fi
# end of primary or replica only stuff

  for atfil in sdtask.txt
  do
    if [ -f "$PATH_ROOT/ace/prog/$atfil" ] ; then
      cp $PATH_ROOT/ace/prog/$atfil $PATH_ROOT/ace/utils/tcl/bin
      cp $PATH_ROOT/ace/prog/$atfil $PATH_ROOT/ace/utils/toolkit
    fi
  done
  rm $PATH_ROOT/ace/prog/sdtask.txt

  for atfil in ace_api.a apiuser.h ace_apits.a apiuserts.h \
    admexamp.c admexamp.mak admexampts.cpp admexampts.mak \
    sdaceldap certutil sunone.map active.map novell.map \
    prompt_api.a prompt_api.h api_errors.h api_msgs.h message.h
  do
    if [ -f "$PATH_ROOT/ace/prog/$atfil" ] ; then
      mv $PATH_ROOT/ace/prog/$atfil $PATH_ROOT/ace/utils/toolkit
    fi
  done

  # copy the shared library to toolkit from $USR_ACE, set USR_ACE permissions
  cp $PATH_ROOT/ace/prog/libprompt_api.s* $PATH_ROOT/ace/utils/toolkit
  "$CHMOD_EXEC" 550  $PATH_ROOT/ace/prog/libprompt_api.s*
  "$CHMOD_EXEC" 550  $PATH_ROOT/ace/utils/toolkit/libprompt_api.s*

  for tclfil in wish-sd tcl-sd
  do
    if [ -f "$PATH_ROOT/ace/prog/$tclfil" ] ; then
      mv $PATH_ROOT/ace/prog/$tclfil $PATH_ROOT/ace/utils/tcl/bin
    fi
  done

  if [ -f "$PATH_ROOT/ace/prog/common.tmp" ] ; then
     mv $PATH_ROOT/ace/prog/common.tmp $PATH_ROOT/ace/utils/tcl/common.Z
     "$UNCOMPRESS_EXEC" $PATH_ROOT/ace/utils/tcl/common.Z
     cd "$PATH_ROOT/ace/utils/tcl"
     "$TAR_EXEC" -xpf $PATH_ROOT/ace/utils/tcl/common
     rm -f $PATH_ROOT/ace/utils/tcl/common
  fi

  if [ -f "$PATH_ROOT/ace/prog/admenv" ] ; then
    mv $PATH_ROOT/ace/prog/admenv $PATH_ROOT/ace/utils/admenv
    cd "$PATH_ROOT/ace/utils/tcl/bin"
    "$LN_EXEC" -s $PATH_ROOT/ace/utils/admenv admenv
    cd "$PATH_ROOT/ace/utils/toolkit"
    "$LN_EXEC" -s $PATH_ROOT/ace/utils/admenv admenv
    cd "$PATH_ROOT/ace/utils/oldutil"
    "$LN_EXEC" -s $PATH_ROOT/ace/utils/admenv admenv
  fi

  umask $UTLUMSK  
}

##############################################################################
# rename_commonz()
# renames file common.Z to common.tmp to prevent uncompression
##############################################################################
rename_commonz()
{
  if [ -f "$PATH_ROOT/ace/prog/common.Z" ] ; then
     mv $PATH_ROOT/ace/prog/common.Z $PATH_ROOT/ace/prog/common.tmp
  fi
}


##############################################################################
# check_write_permission()
# Check for write permission on the current directory. abort on error.
##############################################################################
check_write_permission()
{
  $CLEAR_EXEC
  if [ ! -w "./" ] ; then
    echo "You do not have 'write' access to the current directory.  You must be root in"
    echo "order to run 'sdsetup' and it does not appear that you are root.  To become"
    echo "root and avoid this message on most platforms, type 'su - root' and run"
    echo "'sdsetup' again."
    abort_installation
  fi
}

##############################################################################
# check_services()
# Check the user's services in sdconf.rec and sees if they can be
# resolved.  Display warning message if they cannot be resolved.
##############################################################################
check_services()
{
  $SDCFGVAL_EXEC requiredservices 
  errStatus_required=$?

  if [ "$errStatus_required" != "1" ] ; then
    acmservice=`$USR_ACE/sdcfgval acmservice`
    acmport=`$USR_ACE/sdcfgval acmport`

    sdadmindservice=`$USR_ACE/sdcfgval adminservice`
    sdadmind_port=`$USR_ACE/sdcfgval adminport`

    lockmgr_service=`$USR_ACE/sdcfgval lockmgr_servicename`
    lockmgr_port=`$USR_ACE/sdcfgval lockmgr_port`

    dps_service=`$USR_ACE/sdcfgval dps_servicename`
    dps_port=`$USR_ACE/sdcfgval dps_port`

    echo ""
    echo "One or more of the services used by the $SERVER_NAME"
    echo "might be missing or misconfigured in the system services file."  
    echo "The $SERVER_NAME configuration file (sdconf.rec) holds these values:"
    echo ""
    echo "    Authentication service name :    $acmservice"
    echo "    Authentication port :            $acmport UDP"

    echo "    Administration service name :    $sdadmindservice"
    echo "    Administration port :            $sdadmind_port TCP"

    echo "    Web Admin service name:          sdcommd"    
    echo "    Web Admin port:                  5570 TCP (default)"

    echo "    Lock Manager service name :      $lockmgr_service"
    echo "    Lock Manager port :              $lockmgr_port TCP"

    echo "    Offline Auth Data servicename:   sdoad"
    echo "    Offline Auth Data port:          5580 TCP (default)"

    echo "    Log Database broker name:        sdlog"
    echo "    Log Database broker port:        5520 TCP (default)"

    echo "    Server Database broker name:     sdserv"
    echo "    Server Database broker port:     5530 TCP (default)"
  fi

#    $SDCFGVAL_EXEC optionalservices 
#    errStatus_optional=$?
#
# if [ "$errStatus_required" != "1" -o  "$errStatus_optional" != "1" ] ; then
  if [ "$errStatus_required" != "1" ] ; then
    echo ""
    echo "The service names and port numbers must be included in the system"
    echo "services record before you can start the aceserver."
    echo ""
    echo "***Note: If your system maintains service entries using an NIS server,"
    echo "a system administrator must add these entries to the NIS server"
    echo "services file."
    echo ""
  fi

}

##############################################################################
# check_acetmp()
# Check for ace_tmp.  If it exists, then display message to the user.
##############################################################################
check_acetmp()
{
  if [ -d "$PATH_ROOT/ace_tmp" ] ; then
    echo ""
    echo "The directory '$PATH_ROOT/ace_tmp' exists and it contains your original"
    echo "$SERVER_NAME installation and/or database files. You should delete or move"
    echo "this directory to avoid conflicts when future upgrades are performed."
  fi
}


##############################################################################
# set_file_ownerships()
# Change file ownerships in accordance with what the user specified in sdconfig.
##############################################################################
set_file_ownerships()
{
#
# Change to $USR_ACE - make sure sdcfgval is executable
#
  cd $USR_ACE
  "$CHMOD_EXEC" 110 sdcfgval

  if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
        "$INSTALL_TYPE" = "$REPLICA" -o \
        "$INSTALL_TYPE" = 'config' ] ; then
    OWNER_NAME="`$USR_ACE/sdcfgval ownername`"
  elif [ "$INSTALL_TYPE" = "$AGENT" ] ; then
    OWNER_NAME="root"
  fi

  echo ""
  echo "The current time is `date`"
  echo "Changing file ownerships..."

  cd $USR_ACE
  cd ../../
  "$CHOWN_EXEC" "$OWNER_NAME" ./ace
  "$CHOWN_EXEC" "$OWNER_NAME" ./ace/*
  "$CHOWN_EXEC" "$OWNER_NAME" ./ace/rdbms/*
  "$CHOWN_EXEC" "$OWNER_NAME" ./ace/rdbms/bin/*

  cd $USR_ACE
  "$CHOWN_EXEC" "$OWNER_NAME" *

  for clientfile in _sdfindshell sdshell sdshell_adm _sdprompt sdshell_auth _sdtacplusd 
  do
    if [ -f "$clientfile" ] ; then
      "$CHOWN_EXEC" root $clientfile
    fi
  done

  if [ "$PLATFORM" = "aix" ] ; then
      if [ "$AIX_VERS" = "5.2" -o "$AIX_VERS" = "5.3" ] ; then
          "$CHOWN_EXEC" root _mprosrv
      fi
  fi

  if [ "$REPLICATION_ELEVATED" = TRUE ] ; then
      "$CHOWN_EXEC" root acesyncd
  fi

  for testdir in protrig proapi protty
  do
    if [ -d "$USR_ACE/$testdir" ] ; then
      cd $USR_ACE/$testdir
      "$CHOWN_EXEC" "$OWNER_NAME" *
    fi
  done


#
# Go handle files in VAR_ACE
#
  if [ -d $VAR_ACE ] ; then
    "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE
    "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/*
    "$CHOWN_EXEC" -R "$OWNER_NAME" $VAR_ACE/atkpools
    "$CHOWN_EXEC" -R "$OWNER_NAME" $VAR_ACE/ldapjobs
    "$CHOWN_EXEC" -R "$OWNER_NAME" $VAR_ACE/output
    "$CHOWN_EXEC" -R "$OWNER_NAME" $VAR_ACE/queries

 

    if [ -f "$VAR_ACE/sdace.txt" ] ; then
      "$CHMOD_EXEC" 444 $VAR_ACE/sdace.txt
      "$CHOWN_EXEC" root $VAR_ACE/sdace.txt
    fi
    if [ -d "$VAR_ACE/replica_package" ] ; then
      "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package
    fi
    if [ -d "$VAR_ACE/replica_package/license" ] ; then
      "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package/license
      "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package/license/*
    fi
    if [ -d "$VAR_ACE/replica_package/database" ] ; then
      "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package/database
      "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package/database/*
    fi

  fi

#
# Go handle doc files
#
  if [ -d $USR_ACE/../doc ] ; then
     cd $USR_ACE
     cd ..
     "$CHOWN_EXEC" "$OWNER_NAME" ./doc
     docfiles="`$LS_EXEC ./doc/* 2> /dev/null`"
     if [ -n "$docfiles" ] ; then
        for modfile in $docfiles
        do
            "$CHOWN_EXEC" "$OWNER_NAME" "$modfile"
        done
     fi
  fi

#
# Go handle utility files
#
  if [ -d $USR_ACE/../utils ] ; then
     cd $USR_ACE
     cd ..
     "$CHOWN_EXEC" -R "$OWNER_NAME" ./utils
  fi

}

##############################################################################
# set_file_permissions()
# Change file permissions in accordance with what the user specified in sdconfig.
##############################################################################
set_file_permissions()
{

# Change to $USR_ACE - make sure sdcfgval is executable
  cd $USR_ACE
  "$CHMOD_EXEC" 110 sdcfgval

# Change permissions according to install type
  echo ""
  echo "The current time is `date`"
  echo "Changing file permissions..."
  "$CHMOD_EXEC" 771 $PATH_ROOT/ace
  "$CHMOD_EXEC" 771 $VAR_ACE
  "$CHMOD_EXEC" 771 $USR_ACE


# Setup permissions on USR_ACE

  cd $USR_ACE
  for subdir in protrig proapi protty
  do
     if [ -d "$subdir" ] ; then
       "$CHMOD_EXEC" 550 $subdir
       cd $USR_ACE/$subdir
       "$CHMOD_EXEC" 550 *
       cd $USR_ACE
     fi
  done

  

# Copyright, version and sdace files
  "$CHMOD_EXEC" 440 $USR_ACE/copyright.txt

  if [ -f $USR_ACE/license.sh ] ; then
     "$CHMOD_EXEC" 550 $USR_ACE/license.sh
  fi

  if [ -f $USR_ACE/license1.txt ] ; then
     "$CHMOD_EXEC" 440 $USR_ACE/license1.txt
     if [ -f "/tmp/RSA_LICENSE1_COUNTRY_OF_ORIGIN" ] ; then 
       cp $USR_ACE/license1.txt $VAR_ACE/rsa_license.txt
       rm "/tmp/RSA_LICENSE1_COUNTRY_OF_ORIGIN" 
     fi
  fi
  if [ -f $USR_ACE/license2.txt ] ; then
     "$CHMOD_EXEC" 440 $USR_ACE/license2.txt
     if [ -f "/tmp/RSA_LICENSE2_COUNTRY_OF_ORIGIN" ] ; then 
       cp $USR_ACE/license2.txt $VAR_ACE/rsa_license.txt
       rm "/tmp/RSA_LICENSE2_COUNTRY_OF_ORIGIN" 
     fi
  fi
  if [ ! -f $VAR_ACE/rsa_license.txt ] ; then
     cp $USR_ACE/license1.txt $VAR_ACE/rsa_license1.txt
     cp $USR_ACE/license2.txt $VAR_ACE/rsa_license2.txt   
     "$CHMOD_EXEC" 440 $VAR_ACE/rsa_license1.txt
     "$CHMOD_EXEC" 440 $VAR_ACE/rsa_license2.txt
  else 
     "$CHMOD_EXEC" 440 $VAR_ACE/rsa_license.txt
  fi

  if [ -f $USR_ACE/other_license.txt ] ; then
     "$CHMOD_EXEC" 440 $USR_ACE/other_license.txt
     cp $USR_ACE/other_license.txt $VAR_ACE/other_license.txt
  fi
  if [ -f $USR_ACE/question1.txt ] ; then
     "$CHMOD_EXEC" 440 $USR_ACE/question1.txt
  fi
  if [ -f $USR_ACE/question2.txt ] ; then
     "$CHMOD_EXEC" 440 $USR_ACE/question2.txt
  fi

  if [ -f "$VAR_ACE/sdace.txt" ] ; then
    "$CHMOD_EXEC" 444 $VAR_ACE/sdace.txt
    "$CHOWN_EXEC" root $VAR_ACE/sdace.txt
  fi

  "$CHMOD_EXEC" 440 $USR_ACE/version.txt
  "$CHMOD_EXEC" 440 $VAR_ACE/version.txt
  "$CHMOD_EXEC" 664 $VAR_ACE/sdmsg.cat
  "$CHMOD_EXEC" 770 $VAR_ACE/output
  "$CHMOD_EXEC" 660 $USR_ACE/commands.conf
  "$CHMOD_EXEC" 660 $USR_ACE/hosts.conf
  "$CHMOD_EXEC" 660 $USR_ACE/nsconfig.conf
  "$CHMOD_EXEC" 660 $USR_ACE/sdcommd.conf


# Config operation only
  if [ "$INSTALL_TYPE" = "config" ] ; then
    "$CHMOD_EXEC" 550 sdsetup
    "$CHMOD_EXEC" 110 sdconfig
  fi

# Primary installation only
  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
    "$CHMOD_EXEC" 550 sdadmin sdimport 
    "$CHMOD_EXEC" 110 sdconfig sdcfgval sdmpro
    
    cd $PATH_ROOT/ace/utils
    "$CHMOD_EXEC" 770 oldutil
    
    cd $PATH_ROOT/ace/utils/oldutil
    "$CHMOD_EXEC" 550 *
  fi


# Primary and replica installations
  if [ "$INSTALL_TYPE" = "$PRIMARY" -o "$INSTALL_TYPE" = "$REPLICA" ] ; then
    
    cd $USR_ACE
      "$CHMOD_EXEC" 440 serv_ini.*
      "$CHMOD_EXEC" 440 log_ini.*

    $DLC_PROUTIL serv_ini.db -C truncate bi -G 1 > /dev/null
    $DLC_PROUTIL log_ini.db  -C truncate bi -G 1 > /dev/null

# PROGRESS parameter files
    "$CHMOD_EXEC" 440 sdserv.pf
    "$CHMOD_EXEC" 440 sdlog.pf

# Scripts
    "$CHMOD_EXEC" 550 aceserver sdinfo sdnewdb sdconnect sdlogmon sdcompress \
          sdcreadm sddump sdload sdsetup aceping \
          sdrepmgmt sdadmin \
          sdcfgedit agent_nsload rsaextconv sdtestauth


# Images
    "$CHMOD_EXEC" 110 getacev _sdcfgedit _sdinfo sdmpro _agent_nsload _rsaextconv
    "$CHMOD_EXEC" 110 _dmp_srv _dmp_log _ld_srv _ld_log
    "$CHMOD_EXEC" 550 sdldapsync bindtest apidemon sdrsakeygen sdcertreqgen sdcertgen 
    "$CHMOD_EXEC" 110 _aceping _sdtestauth
    "$CHMOD_EXEC" 110 _aceserver_fe _aceserver_be
    if [ "$REPLICATION_ELEVATED" = TRUE ] ; then
        "$CHMOD_EXEC" 4110 acesyncd
    else
        "$CHMOD_EXEC" 110 acesyncd
    fi
#   For some reason TACACS should be owned by root and have 's' bit set
    "$CHMOD_EXEC" 4110 _sdtacplusd _mprosrv
    "$CHMOD_EXEC" 110 rsalicutil dumpreader
    "$CHMOD_EXEC" 110 sdadmind jsed sdoad logmaintthd sdcommd _sdrepmgmt systable
# changed terminology DPS="Download Password Service" to "Offline Auth Data"
    "$CHMOD_EXEC" 110 sdoad
    "$CHMOD_EXEC" 660 apidemon.ini

# For AIX 5.2 5.3 it should be owned by root and have s bit set
    if [ "$PLATFORM" = "aix" ] ; then
        if [ "$AIX_VERS" = "5.1" -o "$AIX_VERS" = "5.2" -o "$AIX_VERS" = "5.3" ] ; then
            "$CHMOD_EXEC" 4110 _mprosrv 
        fi
    fi


    cd $USR_ACE
    case "$PLATFORM" in
      'hp'    )
              SO="sl";;
       *      )
              SO="so";;
    esac
    "$CHMOD_EXEC" 550 *.$SO
    "$CHMOD_EXEC" 550 libsdxauthr.$SO
    if [ -h /usr/lib/libsdxauthr.$SO ] ; then
#  symbolic link already exists, replace it.
      echo "Replacing old symbolic link at '/usr/lib/libsdxauthr.$SO'."
      echo "Previous link:"
      ls -l /usr/lib/libsdxauthr.$SO
      rm /usr/lib/libsdxauthr.$SO
      if [ ! "$?" = "0" ] ; then
         echo "Error removing old link to dynamic authorization library."
         abort_installation
      fi
      ln -s "$USR_ACE"/libsdxauthr.$SO /usr/lib/libsdxauthr.$SO
      if [ "$?" = 0 ] ; then
        echo "Created symbolic link /usr/lib/libsdxauthr.$SO to reference"
        echo "   external authorization library $USR_ACE/libsdxauthr.$SO"
      else
        echo "Error creating symbolic link /usr/lib/libsdxauthr.$SO."
        abort_installation
      fi
    else
      if [ -d /usr/lib/libsdxauthr.$SO ] ; then
#  Directory exists, Abort.
        echo "Error External authorization dynamic library /usr/lib/libsdxauthr.$SO"
        echo "  can not be created because a directory exists with the same name"
        abort_installation
      else
        if [ -f /usr/lib/libsdxauthr.$SO ] ; then
#  File exists, leave it alone (Ace Server will use it).
          echo "External authorization dynamic library /usr/lib/libsdxauthr.$SO already exists."
          echo "$SERVER_NAME will use this dynamic library instead of"
          echo "creating a symbolic link to $USR_ACE/libsdxauthr.$SO"
        else
#  No previous instance with name libsdxauthr, create symbolic link.
          ln -s "$USR_ACE"/libsdxauthr.$SO /usr/lib/libsdxauthr.$SO
          if [ "$?" = 0 ] ; then
            echo "Created symbolic link /usr/lib/libsdxauthr.$SO to reference"
            echo "external authorization library $USR_ACE/libsdxauthr.$SO"
          else
            echo "Error creating symbolic link /usr/lib/libsdxauthr.$SO."
            abort_installation
          fi
        fi
      fi
    fi

    "$CHMOD_EXEC" 440 $PATH_ROOT/ace/doc/* 2> /dev/null
    
    cd $PATH_ROOT/ace/utils
    "$CHMOD_EXEC" 440 *
    "$CHMOD_EXEC" 770 output std_rpt cust_rpt oldutil 
    "$CHMOD_EXEC" 550 admenv rptconnect rptrun sdreport
    "$CHMOD_EXEC" 660 sdrpt-st.d sdrpt-st.df sdrpt.b1 sdrpt.d1 sdrpt.st sdrpt.db sdrpt.lg sdrunlis.df
 
    cd $PATH_ROOT/ace/utils/std_rpt
    "$CHMOD_EXEC" 440 * 
    
    cd $PATH_ROOT/ace/utils
    "$CHMOD_EXEC" 770 tcl toolkit

    cd $PATH_ROOT/ace/utils/toolkit
    "$CHMOD_EXEC" 550 sdaceldap admenv certutil
    "$CHMOD_EXEC" 660 *.map admexamp.c admexampts.cpp
    "$CHMOD_EXEC" 440 sdtask.txt
    "$CHMOD_EXEC" 550 libprompt_api.* ace_api.a ace_apits.a prompt_api.a
    "$CHMOD_EXEC" 440 *.h
    "$CHMOD_EXEC" 770 *.mak


    cd $PATH_ROOT/ace/utils/tcl
    "$CHMOD_EXEC" 770 bin

    cd $PATH_ROOT/ace/utils/tcl/bin
    "$CHMOD_EXEC" 550 tcl-sd wish-sd admenv
    "$CHMOD_EXEC" 660 sdtask.txt  
    "$CHMOD_EXEC" 770 test.tcl

    "$CHMOD_EXEC" 770 $PATH_ROOT/ace/data/atkpools
    "$CHMOD_EXEC" 770 $PATH_ROOT/ace/data/output
    "$CHMOD_EXEC" -R 770 $PATH_ROOT/ace/data/queries

    "$CHMOD_EXEC" 770 $PATH_ROOT/ace/data/ldapjobs
    "$CHMOD_EXEC" 770 $PATH_ROOT/ace/data/ldapjobs/sslcerts
    "$CHMOD_EXEC" 440 $PATH_ROOT/ace/data/ldapjobs/sslcerts/ldap-ssl-readme.txt

# Update the permissions in rdbms

    cd $PATH_ROOT/ace/rdbms
    "$CHMOD_EXEC" 750 *
    cd $PATH_ROOT/ace/rdbms/bin
# Files with setuid bit
    "$CHMOD_EXEC" 4750 _*
# Original scripts
    "$CHMOD_EXEC" 750 *.orig 2> /dev/null
# Other scripts
    "$CHMOD_EXEC" 750 pro proapw probiw probkup prolog prorest proserve proshut
    "$CHMOD_EXEC" 750 proutil sdbkup sdrest


    cd $VAR_ACE
    for tacfile in sdtacplus.cfg sdtacplus.arg syslog.cfg
    do
      if [ -f "$tacfile" ] ; then
        "$CHMOD_EXEC" 660 $tacfile
      fi
    done
  fi

#
# Primary, replica or agent installations
#
  if [ \( "$INSTALL_PRIMARY_OR_AGENT" = TRUE -o \
          "$INSTALL_TYPE" = "$REPLICA" \) -a \
          -f "$USR_ACE"/sdshell ] ; then

    cd $USR_ACE
# Scripts
    "$CHMOD_EXEC" 550 sdinfo agent_nsload
    "$CHMOD_EXEC" 555 sdfindshell sdprompt Xprompt sdtestauth

# Images
    "$CHMOD_EXEC" 110 _sdinfo sdcfgval randext _agent_nsload _sdtestauth
    "$CHMOD_EXEC" 4111 _sdfindshell sdshell_adm _sdprompt
    "$CHMOD_EXEC" 4111 sdshell 


# For AIX only: sdshell_auth must be owned by root with the setuid bit turned on.
    if [ "$PLATFORM" = "aix" ] ; then
      "$CHMOD_EXEC" 4111 sdshell_auth
    fi

  fi

  cd $VAR_ACE
  for atfil in sdconf.rec server.cer license.rec sdti.cer
  do
    if [ -f $atfil ] ; then
      "$CHMOD_EXEC" 660 $atfil
    fi
  done
  if [ -f server.key ] ; then
      "$CHMOD_EXEC" 660 server.key
  fi
 
  # Set up replica package permissions
  set_rp_permissions
}

##############################################################################
# set_db_permissions()
# Set db file ownerships and permissions in accordance to what the
# user specified in sdconfig.
##############################################################################
set_db_permissions()
{
#
# Change to $USR_ACE, get name of fileowner
#
  cd $USR_ACE

  if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
       "$INSTALL_TYPE" = "$REPLICA" -o \
       "$INSTALL_TYPE" = "$APPLY_RP" ] ; then
    OWNER_NAME="`$USR_ACE/sdcfgval ownername`"
    GROUPNAME="`$USR_ACE/sdcfgval ownergroup`"

#
# Change to $VAR_ACE, set file ownership and permissions
#
    cd $VAR_ACE

    for dbfile in sdserv.db sdserv.lg sdserv.b1 sdserv.d1 sdserv.st sdserv.vrs \
                  sdlog.db sdlog.lg sdlog.b1 sdlog.d1 sdlog.st sdlog.vrs
    do
      if [ -f $dbfile ] ; then
        $CHOWN_EXEC $OWNER_NAME $dbfile
        $CHGRP_EXEC $GROUPNAME $dbfile
        $CHMOD_EXEC 660 $dbfile
      fi
    done
  fi
}

##############################################################################
# set_rp_permissions
# Set permissions on replica package
##############################################################################
set_rp_permissions()
{
    OWNER_NAME="`$USR_ACE/sdcfgval ownername`"
    GROUPNAME="`$USR_ACE/sdcfgval ownergroup`"
    if [ -d "$VAR_ACE/replica_package" ] ; then
        "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package
        "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package
        "$CHMOD_EXEC" 770 $VAR_ACE/replica_package
        "$CHMOD_EXEC" 770 $VAR_ACE/replica_package/*
    fi
    if [ -d "$VAR_ACE/replica_package/license" ] ; then
        "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package/license
        "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package/license
        "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package/license/*
        "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package/license/*
        "$CHMOD_EXEC" 660 $VAR_ACE/replica_package/license/*
    fi
    if [ -d "$VAR_ACE/replica_package/database" ] ; then
        "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package/database
        "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package/database
        "$CHOWN_EXEC" "$OWNER_NAME" $VAR_ACE/replica_package/database/*
        "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package/database/*
        "$CHMOD_EXEC" 660 $VAR_ACE/replica_package/database/*
    fi
}

##############################################################################
# change_file_groups()
# Set file groups in accordance to the owner's group specified in sdconfig.
##############################################################################
change_file_groups()
{
  cd $USR_ACE

  if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
       "$INSTALL_TYPE" = "$REPLICA" -o \
       "$INSTALL_TYPE" = "config" -o \
       "$INSTALL_TYPE" = "$APPLY_CR" ] ; then
    if GROUPNAME="`$SDCFGVAL_EXEC ownergroup`"
    then
      :
    else
      execute_error sdcfgval
    fi
  elif [ "$INSTALL_TYPE" = "$AGENT" ] ; then
    if GROUPNAME="`$SDCFGVAL_EXEC get_groupname root`"
    then
      :
    else
      execute_error sdcfgval
    fi
  fi

  echo ""
  echo "Changing file group IDs..."
  "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace
  "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/rdbms
  "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/rdbms/*
  "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/rdbms/bin/*
  "$CHGRP_EXEC" "$GROUPNAME" $USR_ACE
  "$CHGRP_EXEC" "$GROUPNAME" $USR_ACE/*
  for testdir in protrig proapi protty
  do
    if [ -d "$USR_ACE/$testdir" ] ; then
      cd $USR_ACE/$testdir
      "$CHGRP_EXEC" "$GROUPNAME" *
    fi
  done


  "$CHGRP_EXEC" -R "$GROUPNAME" $VAR_ACE

  # These might be redundunt but I will leave it in for now
  if [ -d "$VAR_ACE/replica_package" ] ; then
    "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package
  fi
  if [ -d "$VAR_ACE/replica_package/license" ] ; then
    "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package/license
    "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package/license/*
  fi
  if [ -d "$VAR_ACE/replica_package/database" ] ; then
    "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package/database
    "$CHGRP_EXEC" "$GROUPNAME" $VAR_ACE/replica_package/database/*
  fi


  if [ -d $USR_ACE/../doc ] ; then
    "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/doc
    "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/doc/* 2> /dev/null
  fi

  if [ -d $USR_ACE/../utils ] ; then
     "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/utils
     "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/utils/*
     "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/utils/std_rpt/*
  fi

  if [ -d $USR_ACE/../utils/tcl ] ; then
     "$CHGRP_EXEC" -R "$GROUPNAME" $PATH_ROOT/ace/utils/tcl/*
  fi
  if [ -d $USR_ACE/../utils/toolkit ] ; then
     "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/utils/toolkit/*
  fi
  if [ -d $USR_ACE/../utils/oldutil ] ; then
     "$CHGRP_EXEC" "$GROUPNAME" $PATH_ROOT/ace/utils/oldutil/*
  fi

}


##############################################################################
# repair_sdserv_db()
# the .db file for each database has a burned in path to its original
# location. When sdsetup moves to the installed location, we must rebrand the
# .db file
# with this so that procopy will function properly.
##############################################################################
repair_sdserv_db()
{

   cd $VAR_ACE
   $DLC/bin/_dbutil prostrct repair sdserv > /dev/null
   $DLC_PROUTIL sdserv.db -C truncate bi -G 1 > /dev/null
   cd $SOURCE_DIR
}

repair_sdrpt_db()
{

   CURRENT_DIR=`$PWD_EXEC`
   cd $PATH_ROOT/ace/utils
   $DLC/bin/_dbutil prostrct repair sdrpt > /dev/null
   $DLC_PROUTIL sdrpt.db -C truncate bi -G 1 > /dev/null
   cd $CURRENT_DIR
}



# repair_db_files()
# the .db file for each database has a burned in path to its original location.
# When sdsetup moves to the installed location, we must rebrand the .db files
# with this so that procopy will function properly.
##############################################################################
repair_db_files()
{
   repair_mode=$1
   cd $USR_ACE
   $DLC/bin/_dbutil prostrct repair serv_ini > /dev/null	
   $DLC_PROUTIL serv_ini.db -C truncate bi -G 1 > /dev/null

   if [ "$repair_mode" != "sdserv_only" ] ; then 
       $DLC/bin/_dbutil prostrct repair log_ini > /dev/null
       $DLC_PROUTIL log_ini.db  -C truncate bi -G 1 > /dev/null
   fi
   cd $SOURCE_DIR
}

##############################################################################
# setup_server_database()
# For a primary or replica installation, setup the server database.
# The variable $MADE_NEW_DB is set to yes/no.
##############################################################################
setup_server_database()
{

  echo ""
  echo "The current time is `date`"

  repair_db_files

  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
    echo "Setup database for $INSTALL_TYPE_PRETTY..."
    cd $SOURCE_DIR
    if [ "$NEW_INSTALLATION" = FALSE -a \
         "$PRESERVE_DB" = FALSE ] ; then

         # For all types of upgrades with migration (5.0
         # and above) we use rolling upgrade
         ROLLING_UPGRADE=TRUE
      
         
         do_migrate "primary"
         return_code="$MIGRATE_STATUS"
         if [ "$ROLLING_UPGRADE" = TRUE ] ; then
            check_license_limit
            create_common_package ""
         fi

    elif [ "$NEW_INSTALLATION" = FALSE -a \
         "$PRESERVE_DB" = TRUE ] ; then
      
         
         do_migrate "preserve"
         return_code="$MIGRATE_STATUS"

    elif [ "$NEW_INSTALLATION" = TRUE ] ; then
         
         
         $USR_ACE/sdnewdb all
         return_code="2"
    fi


  elif [ "$INSTALL_TYPE" = "$REPLICA" -a "$PRESERVE_DB" = FALSE ] ; then

      DO_NOT_TOUCH_LOG=FALSE
      copy_dbfiles_from_package
      if [ "$?" != "0" ] ; then
         abort_installation
      fi
      return_code="$MIGRATE_STATUS"

  elif [ "$INSTALL_TYPE" = "$REPLICA" -a "$PRESERVE_DB" = TRUE ] ; then
    # we are doing a same version upgrade, so run migrate.
    # it will create a newdb and copy database files from our old install.
       
    
    OLDUMASK=`umask`
    umask $USER_FULL_ACCESS
    do_migrate "preserve"
    return_code="$MIGRATE_STATUS"  
    umask $OLDUMASK

  fi

  if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
  echo ""
  echo "The current time is `date`"
  case "$return_code"
  in
    '0'  )  echo "Database migration complete.";;
    '1'  )  abort_installation;;
    '2'  )  MADE_NEW_DB=TRUE
            insert_primary
            create_administrator;;
    '3'  )  CONVERTED_DB=TRUE;;
    *    )  echo "Error: unexpected return value from sdmigrate ($return_code)."
            abort_installation;;
  esac
  fi
  set_db_permissions

}

##############################################################################
# copy_dbfiles_from_package()
# Migration script wrapper
##############################################################################
copy_dbfiles_from_package()
{
    echo "Applying database files from Replica Package..."
	   
    if [ "$INSTALL_TYPE" = "$REPLICA" ] ; then
        CWD="`pwd`"
        cd $PATH_ROOT
    fi

    OLDUMASK=`umask`
    umask $USER_FULL_ACCESS
    if [ "$NEW_INSTALLATION" = FALSE -a \
         "$INSTALL_TYPE" = "$REPLICA" ] ; then

        if [ -r "$REP_ACE_LICENSE/uidxlate.map" ] ; then
            do_migrate "replica_ru" 
            cp "$REP_ACE_LICENSE/uidxlate.map" "$VAR_ACE/rolling_upgrade"
        else
            echo "Replica Package does not contain uid translation map."
            echo "Existing database will be discarded."
            do_migrate "replica" 
        fi
    fi

# On new install or apply package create the db
# Preserve log if we applying package

    if [ "$INSTALL_TYPE" = "$APPLY_RP" ] ; then
        CRDB_MODE="server"
    else
        CRDB_MODE="all"
    fi

    if [ "$NEW_INSTALLATION" = TRUE -o "$INSTALL_TYPE" = "$APPLY_RP" ] ; then
        echo "Creating new databases......"
        RET_CODE=""
        $USR_ACE/sdnewdb $CRDB_MODE
        RET_CODE="$?"
        if [ "$RET_CODE" != "0" ] ; then
            return $RET_CODE
        fi
    fi

# Add primary and this host from the package
# This also creates config record with proper this node

    echo "Preparing databases......"
    $USR_ACE/$SDREP_EXEC xnodes $REP_ACE_LICENSE
    RET_CODE="$?"
    umask $OLDUMASK

    if [ "$RET_CODE" != "0" ] ; then
        echo ""
        echo "Replica Management cannot create mini database ($RET_CODE)."
        echo ""
        return $RET_CODE
    fi

# Now if we have the database
# Copy it over
    if [ -f "$REP_ACE_DB/sdserv.db" ] ; then
        echo "Copying database files from $REP_ACE_DB directory."
        cp -p \
            $REP_ACE_DB/sdserv.db \
            $REP_ACE_DB/sdserv.lg \
            $REP_ACE_DB/sdserv.b1 \
            $REP_ACE_DB/sdserv.d1 \
            $REP_ACE_DB/sdserv.st \
            $REP_ACE_DB/sdserv.vrs \
            $VAR_ACE
# repair the db files 
            repair_sdserv_db
# Adjust sequence numbers 
            $USR_ACE/$SDREP_EXEC xjs
            RET_CODE="$?"
            if [ "$RET_CODE" != "0" ] ; then
                echo ""
                echo "Replica Management cannot adjust sequences ($RET_CODE)."
                echo ""
                return $RET_CODE
            fi
    fi

       
    if [ "$INSTALL_TYPE" = "$REPLICA" ] ; then
# Call procedure to update port and service only if we are 
# upgrading or installing new replica. Do not do it in other cases.
        getyesorno_noabort FALSE "Do you want to modify service name and port number for the current Replica Server? (y/n) [n]: "
        if [ TRUE = "$YESORNO" ] ; then
            update_rep_port_and_name "" ""
        fi
        cd $CWD
    fi
    umask $OLDUMASK
    return 0
}


##############################################################################
# do_migrate()
# Migration script wrapper
##############################################################################
do_migrate()
{
  migrate_mode=$1
  MIGRATE_STATUS="0"

  case "$migrate_mode"
  in
    'preserve'        ) do_copy_db_files
                        if [ "$MIGRATE_STATUS" = "1" ] ; then
                           echo ""
                           echo "There is not enough disk space to complete migration."
                           echo ""
                        fi;;
    'primary'         ) do_primary_upgrade;;
    'replica'         ) REPLICA_DUMP=FALSE
                        do_replica_upgrade;;
    'replica_ru'      ) REPLICA_DUMP=TRUE
                        do_replica_upgrade;;
    *                 ) echo "Unexpected migration mode."
                        abort_installation;;
  esac
}

##############################################################################
# do_copy_db_files()
# Preserve database files. Just copy them from old installation to new one
##############################################################################
do_copy_db_files()
{
    OLD_VAR_ACE="$PATH_ROOT/ace_tmp/data"
    cp -r $OLD_VAR_ACE/* $VAR_ACE
    if [ "$?" != 0 ] ; then
        MIGRATE_STATUS="1"
        return
    fi

# TBD copy any other files that need to be 
# moved from other directories to corresponding directories 
# of new install    
}

##############################################################################
# do_primary_upgrade()
# Do primary database upgrade
##############################################################################
do_primary_upgrade()
{

# TBD - check the available size
  
   create_migrate_backup
   if [ "$MIGRATE_STATUS" = "1" ] ; then
      return
   fi

   if [ "$SERV_DUMP_EXISTS" = FALSE ] ; then
      dump_old_database "-s" "sdserv"
   fi

   if [ "$LOG_DUMP_EXISTS" = FALSE ] ; then
      dump_old_database "-l" "sdlog"
   fi
# Create new database
   $USR_ACE/sdnewdb all

   load_old_database "-s" "sdserv"
   if [ "$MIGRATE_STATUS" = "1" ] ; then
      del_migrate_backup
      return
   fi

   load_old_database "-l" "sdlog"
# If we failed to do something
# delete backup  
   if [ "$MIGRATE_STATUS" = "1" ] ; then
      del_migrate_backup
   fi

}   
##############################################################################
# do_replica_upgrade()
# Do replica database upgrade
##############################################################################
do_replica_upgrade()
{

# TBD - check the available size
# In the case of replica upgrade we do not load the server dump
  
   create_migrate_backup
   if [ "$MIGRATE_STATUS" = "1" ] ; then
      return
   fi

   if [ "$REPLICA_DUMP" = TRUE ] ; then  
      if [ "$SERV_DUMP_EXISTS" = FALSE ] ; then
         dump_old_database "-s" "sdserv"
      fi
   fi

   if [ "$LOG_DUMP_EXISTS" = FALSE ] ; then
      dump_old_database "-l" "sdlog"
   fi
# Create new database
   if [ "$DO_NOT_TOUCH_LOG" = TRUE ] ; then
      $USR_ACE/sdnewdb server
   else
      $USR_ACE/sdnewdb all
   fi
   echo "Not loading server database"

   if [ "$REPLICA_DUMP" = TRUE ] ; then  
      mkdir -p "$VAR_ACE/rolling_upgrade"
      cp "$PATH_ROOT/ace_tmp/data/sdserv.dmp" "$VAR_ACE/rolling_upgrade"
      cp "$PATH_ROOT/ace_tmp/data/license.rec" "$VAR_ACE/rolling_upgrade"
   fi

   if [ ! "$DO_NOT_TOUCH_LOG" = TRUE ] ; then
       load_old_database "-l" "sdlog"
       # If we failed to do something
       # delete backup  
       if [ "$MIGRATE_STATUS" = "1" ] ; then
          del_migrate_backup
       fi
   fi
}   

##############################################################################
# create_migrate_backup()
# Create a backup directory for the database files
##############################################################################
create_migrate_backup()
{
# Create a tmp directory for migration
  
    OLD_VAR_ACE="$PATH_ROOT/ace_tmp/data"

    MIGR_UMSK=`umask`
    umask=$USER_FULL_ACCESS

    migrate_tmp_dir="$OLD_VAR_ACE/mtmp"

    if [ -d "$migrate_tmp_dir" ] ; then
      $RM_EXEC -rf $migrate_tmp_dir/*
    else
      if $MKDIR_EXEC -p $migrate_tmp_dir 
         then
          :
      else
          echo ""
          echo "Error in creating a temporary directory for migration"
          echo ""
          MIGRATE_STATUS="1"
          return
      fi
    fi

# Copy files to backup
    if [ "$ORIG_MJ_MN" -le "600" ]; then 
      for file in sdserv.db sdserv.bi sdserv.vrs sdserv.lg sdlog.db \
                  sdlog.bi sdlog.vrs sdlog.lg version.txt license.rec
      do
        cp $OLD_VAR_ACE/$file $migrate_tmp_dir
        if [ ! "$?" = "0" ] ; then
           echo ""
           echo "Database backup failed. Check free disk space."
           echo ""
           MIGRATE_STATUS="1"
           return
        fi
      done
   else
      for file in sdserv.db sdserv.b1 sdserv.st sdserv.d1 sdserv.vrs sdserv.lg sdlog.db \
                  sdlog.b1 sdlog.st sdlog.d1 sdlog.vrs sdlog.lg version.txt license.rec
      do
        cp $OLD_VAR_ACE/$file $migrate_tmp_dir
        if [ ! "$?" = "0" ] ; then
           echo ""
           echo "Database backup failed. Check free disk space."
           echo ""
           MIGRATE_STATUS="1"
           return
        fi
      done
 
   fi 

# if dump files already exist, copy them to the temp directory

    for file in sdserv.dmp sdlog.dmp
    do
      if [ -r $OLD_VAR_ACE/$file ] ; then
        cp $OLD_VAR_ACE/$file $migrate_tmp_dir
        if [ ! "$?" = "0" ] ; then
           echo ""
           echo "Database backup failed. Check free disk space."
           echo ""
           MIGRATE_STATUS="1"
           return
        fi
      fi
    done 

    umask "$MIGR_UMSK"
}

##############################################################################
# del_migrate_backup()
# Deletes data backup
##############################################################################
del_migrate_backup()
{
    migrate_tmp_dir="$PATH_ROOT/ace_tmp/data/mtmp"

# Copy old dumps back

    for file in sdserv.dmp sdlog.dmp
    do
      if [ -r $migrate_tmp_dirCE/$file ] ; then
        cp $migrate_tmp_dir/$file ..
      fi
    done 

    if [ -d "$migrate_tmp_dir" ] ; then
      $RM_EXEC -rf $migrate_tmp_dir
    fi
}

##############################################################################
# dump_old_database()
# Dumps an existing database
##############################################################################
dump_old_database()
{
    flag_name="$1"
    file_name="$2"
# Create variables for old install
    USR_ACE="$PATH_ROOT/ace_tmp/prog";export USR_ACE
    VAR_ACE="$PATH_ROOT/ace_tmp/data";export VAR_ACE
    DLC="$PATH_ROOT/ace_tmp/rdbms";export DLC
# No need to set propath. It will be set inside sddump script based on 
# USR_ACE

# Call dump
# Remeber the USR_ACE currently points to old install
    if [ -f "$VAR_ACE/$file_name.dmp" ] ; then
       rm -f "$VAR_ACE/$file_name.dmp"
    fi
    $USR_ACE/sddump "$flag_name" -f"$VAR_ACE/$file_name.dmp"
    MIGRATE_STATUS="$?"     
# Restore our propaths
    export_our_paths
}


##############################################################################
# load_old_database()
# Loads a dump from old installation
##############################################################################
load_old_database()
{
    flag_name="$1"
    file_name="$2"
    lic_file=""
 
# Call load
    if [ "$flag_name" = "-s" ] ; then
        lic_file="-k$PATH_ROOT/ace_tmp/data/license.rec"
    fi

    $USR_ACE/sdload "$flag_name" -f"$PATH_ROOT/ace_tmp/data/$file_name.dmp" "$lic_file"
    MIGRATE_STATUS="$?"     
# If UUID translation was created during the load move it from the 
# place where it is created to the current data
    if [ -f "$PATH_ROOT/ace_tmp/data/uidxlate.map" ] ; then
        cp "$PATH_ROOT/ace_tmp/data/uidxlate.map" "$VAR_ACE"
    fi    
}


##############################################################################
# create_administrator()
# If this is a first time primary install, create a global administrator in the
# server database using the file owner name.
##############################################################################
create_administrator()
{
  if OWNERNAME="`$USR_ACE/sdcfgval ownername`"
  then
    :
  else
    execute_error sdcfgval
  fi

  echo ""
  echo "Creating realm administrator '$OWNERNAME.'"
  OLDUMASK=`umask`
  umask 077
  $USR_ACE/sdcreadm
  RET_CODE="$?"
  umask $OLDUMASK
  if [ "$RET_CODE" != "0" ] ; then
    abort_installation
  else
    echo ""
    echo "Realm administrator "$OWNERNAME" created."
    echo ""
  fi
}

##############################################################################
# insert_primary()
# The procedure takes care of the creation of primary database
##############################################################################
insert_primary()
{
  $USR_ACE/$SDREP_EXEC xfromconfig
  RET_CODE="$?"
  umask $OLDUMASK

  if [ "$RET_CODE" != "0" ] ; then
    echo "Replica management cannot create Primary record in the database ($RET_CODE)."
    abort_installation
  else
    echo ""
    echo "Added current host as Primary Server to the database."
    echo ""
  fi
}

##############################################################################
# install_queries()
# Install predefined queries.
##############################################################################
install_queries()
{
  cd $USR_ACE

  if [ "$PLATFORM" = "sol" ] ; then
      AWK_EXEC=nawk
  else
      AWK_EXEC=awk
  fi

  if [ -f "$USR_ACE/table.txt" ] ; then 
    OLDUMASK=`umask`
    umask $USER_FULL_ACCESS
    RET_CODE=`cat "$USR_ACE/table.txt" | $AWK_EXEC 'BEGIN {
       FS = ":"
    }
    {
         gsub(" ", "_", $2)
         system("mkdir -p \"$VAR_ACE/queries/" $2 "\"")
         system("mv $USR_ACE/" $1 " \"$VAR_ACE/queries/" $2 "/definition.txt" "\"")
    }'`

    umask $OLDUMASK
    rm "$USR_ACE/table.txt"
  fi
}


##############################################################################
# finish_install()
# Finish the install process with miscellaneous tasks.
##############################################################################
finish_install()
{
#
# Set permissions on all the *.orig script files.
#
  cd $USR_ACE
  origfiles="`$LS_EXEC *.orig 2> /dev/null`"
  if [ -n "$origfiles" ] ; then
    for modfile in $origfiles
    do
      "$CHMOD_EXEC" 440 "$modfile"
    done
  fi

# Need previous installations conf/cfg files but not commands.conf because 
# A/S 5.1 added some ATK cmds to it for QuickAdmin
  prev_config="sdcommd.conf hosts.conf"
  for atfil in $prev_config
  do
    if [ -f "$PATH_ROOT/ace_tmp/prog/$atfil" ] ; then
      cp $PATH_ROOT/ace_tmp/prog/$atfil $USR_ACE
    fi
  done

# Preserve files in ldapjobs
  prev_jobs="cert7.db"
  for atfil in $prev_jobs
  do
    if [ -f "$PATH_ROOT/ace_tmp/data/ldapjobs/sslcerts/$atfil" ] ; then
      cp $PATH_ROOT/ace_tmp/data/ldapjobs/sslcerts/$atfil $VAR_ACE/ldapjobs/sslcerts
    fi
  done

# Preserve map files from the previous installation
# There are several things to do:
# 1) Name old netscape.map to sunone.map
# 2) Add proper lines for new map fields
  map_path="$PATH_ROOT/ace/utils/toolkit"

  if [ -f "$PATH_ROOT/ace_tmp/utils/toolkit/active.map" ] ; then
      cp $PATH_ROOT/ace_tmp/utils/toolkit/active.map $PATH_ROOT/ace/utils/toolkit
      if [ -n "$ORIG_MJ_MN" ] && [ "$ORIG_MJ_MN" -lt "502" ] ; then
          ins_fld "$map_path/active.map" "chDisabledUser=UserAccountControl" \
                  "chGroupMembers=Member"
      fi
  fi

  if [ -f "$PATH_ROOT/ace_tmp/utils/toolkit/novell.map" ] ; then
      cp $PATH_ROOT/ace_tmp/utils/toolkit/novell.map $PATH_ROOT/ace/utils/toolkit
      if [ -n "$ORIG_MJ_MN" ] && [ "$ORIG_MJ_MN" -lt "502" ] ; then
          ins_fld "$map_path/novell.map" "chDisabledUser=LoginDisabled" \
                  "chGroupMembers=Member"
      fi
  fi

  if [ -f "$PATH_ROOT/ace_tmp/utils/toolkit/netscape.map" ] ; then
      cp $PATH_ROOT/ace_tmp/utils/toolkit/netscape.map $PATH_ROOT/ace/utils/toolkit/sunone.map
      if [ -n "$ORIG_MJ_MN" ] && [ "$ORIG_MJ_MN" -lt "502" ] ; then
          ins_fld "$map_path/sunone.map" "chDisabledUser=nsAccountLock" \
                  "chGroupMembers=UniqueMember"
      fi
  fi

# If we just have sunone - copy it over
  if [ -f "$PATH_ROOT/ace_tmp/utils/toolkit/sunone.map" ] ; then
      cp $PATH_ROOT/ace_tmp/utils/toolkit/sunone.map $PATH_ROOT/ace/utils/toolkit/sunone.map
  fi


#
# Preserve Custom Queries from the previous installation
# 1) If they created new queries, copy them to ace/data/queries
# 2) If they have customized any of the default queries, copy it to ace/data/queries
#    But make a back up (by appending "_ver") of the new one for reference-incase the
#    diff is due to schema changes they can refer to it to update their customized one.
#
# Note: If they have deleted a customized query then the new one will be installed
#       so it will no longer be deleted.
#  
# Remember, at this point we have already installed all the default queries 
#           from the new version into the ace/data/queries directory.
#
  if [ -d $PATH_ROOT/ace_tmp/data/queries ] ; then
    echo ""
    echo "Migrating Custom Queries..."
  fi
  # get the list of queries to be migrated
  for custom_query_name in `ls $PATH_ROOT/ace_tmp/data/queries 2>/dev/null` 
  do
    echo ""
    echo "Custom Query $custom_query_name"
    # does each entry in the list actually have a definition file?
    if [ -f $PATH_ROOT/ace_tmp/data/queries/$custom_query_name/definition.txt ] ; then

      # is it a default query or one they created?
      if [ -d $PATH_ROOT/ace/data/queries/$custom_query_name ] ; then

        # It is a Default Query supplied by us.
        # But have they compiled it? If not we skip it because it has no changes.
        if [ -f $PATH_ROOT/ace_tmp/data/queries/$custom_query_name/query.r ] ; then

          # But have they altered it? Ignore the DEFAULTDIR line because that changes on compilation
          grep -v DEFAULTDIR $PATH_ROOT/ace_tmp/data/queries/$custom_query_name/definition.txt >> $PATH_ROOT/ace_tmp/data/queries/deforig.txt
          grep -v DEFAULTDIR $PATH_ROOT/ace/data/queries/$custom_query_name/definition.txt >> $PATH_ROOT/ace_tmp/data/queries/defnew.txt

          diff $PATH_ROOT/ace_tmp/data/queries/deforig.txt \
               $PATH_ROOT/ace_tmp/data/queries/defnew.txt >> NUL
          RECOPY=$?
          if [ $RECOPY = 0 ]; then
            echo "  Custom Query didn't change."
          else

            # they altered the default query and customized it
            echo "  You have modified the Custom Query from the original version."
            echo "  > Migrated your modified version."
            echo "  > Renamed the $CURRENT_AS_VERSION version to ${custom_query_name}_$CURRENT_AS_VERSION"

            # make a backup of the new ($CURRENT_AS_VERSION) default query for reference
            mv $PATH_ROOT/ace/data/queries/$custom_query_name \
               $PATH_ROOT/ace/data/queries/${custom_query_name}_$CURRENT_AS_VERSION

            # migrate the default query that they altered (check that it exists)
		    if [ -f $PATH_ROOT/ace_tmp/data/queries/$custom_query_name/definition.txt ] ; then
              mkdir -p "$PATH_ROOT/ace/data/queries/$custom_query_name"
              chmod 700 "$PATH_ROOT/ace/data/queries/$custom_query_name"
              cp $PATH_ROOT/ace_tmp/data/queries/$custom_query_name/definition.txt \
                 $PATH_ROOT/ace/data/queries/$custom_query_name/definition.txt 
            fi
          fi
        else
          echo "  Custom Query didn't change."
        fi
      else

        # it is a query they created so migrate it 
        mkdir -p "$PATH_ROOT/ace/data/queries/$custom_query_name"
        chmod 700 "$PATH_ROOT/ace/data/queries/$custom_query_name"
        cp $PATH_ROOT/ace_tmp/data/queries/$custom_query_name/definition.txt \
           $PATH_ROOT/ace/data/queries/$custom_query_name/definition.txt
      fi
    else
      echo "  Skipping this Custom Query because it does not have a definition file to migrate."
    fi
  done
  echo ""


#
# Preserve TacPlus config from previous installation
#
  if [ -f "$PATH_ROOT/ace_tmp/data/sdtacplus.cfg" -o \
       -f "$PATH_ROOT/ace_tmp/data/sdtacplus.arg" ] ; then
     cp $PATH_ROOT/ace_tmp/data/sdtacplus.* $VAR_ACE
  fi

  if [ -f "$PATH_ROOT/ace_tmp/data/syslog.cfg" ] ; then
     cp $PATH_ROOT/ace_tmp/data/syslog.* $VAR_ACE
  fi


#
# Preserve the original nodesecret, if it exists
#
  if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
       "$INSTALL_TYPE" = "$REPLICA" -o \
       "$INSTALL_TYPE" = "$AGENT" ] ; then
    nodesecret=`$USR_ACE/sdcfgval acmservice`
    if [ -f "$PATH_ROOT/ace_tmp/data/$nodesecret" ] ; then
      cp "$PATH_ROOT/ace_tmp/data/$nodesecret" $VAR_ACE
    fi
  fi
  change_file_groups
# need to reset the file owner after all the file copy and upgrade 
  set_file_ownerships
# Set permissions on the files
  "$CHMOD_EXEC" 660 $PATH_ROOT/ace/utils/toolkit/*.map
  "$CHMOD_EXEC" 660 $VAR_ACE/sdtacplus.*
  "$CHMOD_EXEC" 660 $VAR_ACE/syslog.*

  if [ "$SILENT_MODE" = FALSE ] ; then
    $USR_ACE/sdinfo | more
  fi

#
# Installation complete, update sdconnect.
#
  if [ "$INSTALL_TYPE" = "$PRIMARY" -o \
       "$INSTALL_TYPE" = "$REPLICA" ] ; then
    if [ -f "$USR_ACE/sdconnect" ] ; then
      "$SED_EXEC" "s/INSTALL_SUCCESS=0/INSTALL_SUCCESS=1/" \
        "$USR_ACE"/sdconnect > "$USR_ACE"/sdconnect.new
      cp "$USR_ACE"/sdconnect.new "$USR_ACE"/sdconnect
      rm $USR_ACE/sdconnect.new
    fi
  fi

  echo "Installation of $SERVER_NAME $INSTALL_TYPE_PRETTY software complete at `date`."

}
##############################################################################
# ins_fld()
# This functions inserts two lines given as arguments 
#
##############################################################################
ins_fld()
{
  file=$1
  line1=$2
  line2=$3
  tmp_file=$1_tmp

  if [ "$PLATFORM" = "sol" ] ; then
      AWK_EXEC=nawk
  else
      AWK_EXEC=awk
  fi

  OLDUMASK=`umask`
  umask $USER_FULL_ACCESS
  RET_CODE=`cat $file | $AWK_EXEC -v ln1=$line1 -v ln2=$line2 '{
            print $0
            if (NR == 3) {
               print ln1
               print ln2
            }
  }' > $tmp_file`
  mv $tmp_file $file
  umask $OLDUMASK
}
##############################################################################
# write_ace_file()
# This function creates a file that contains the environment variables
# VAR_ACE, USR_ACE in the form:
#   VAR_ACE=<pathname>
#   USR_ACE=<pathname>
##############################################################################
write_ace_file()
{
  if [ -f "$VAR_ACE/sdace.txt" ] ; then
    rm -f "$VAR_ACE/sdace.txt"
  fi

  OLDUMSK=`umask`
  umask $USER_FULL_ACCESS
  echo "VAR_ACE=$VAR_ACE" >  $VAR_ACE/sdace.txt
  echo "USR_ACE=$USR_ACE" >> $VAR_ACE/sdace.txt
  umask $OLDUMSK

  rm -f /etc/sdace.txt
  ln -s $VAR_ACE/sdace.txt /etc/sdace.txt
  "$CHMOD_EXEC" 444 /etc/sdace.txt
  "$CHOWN_EXEC" root /etc/sdace.txt
  FILES_WRITTEN="$FILES_WRITTEN $VAR_ACE/sdace.txt /etc/sdace.txt"
}

##############################################################################
# write_ace_services_file()
# This function creates a file that contains the services needed in the 
# services file so the user can look at and use these if necessary.
#
#
##############################################################################
write_ace_services_file()
{
  # return if non-root
  if [ "$CUR_UID" != "0" ] ; then
    return
  fi

  if [ -f "$VAR_ACE/ace_services.txt" ] ; then
    rm -f "$VAR_ACE/ace_services.txt"
  fi

  echo "#default $SERVER_NAME ports" >  /tmp/ace_services.txt
  echo "securid         5500/udp" >> /tmp/ace_services.txt
  echo "securidprop     5505/tcp" >> /tmp/ace_services.txt
  echo "securidprop_00  5505/tcp" >> /tmp/ace_services.txt
  echo "securidprop_01  5506/tcp" >> /tmp/ace_services.txt
  echo "securidprop_02  5507/tcp" >> /tmp/ace_services.txt
  echo "securidprop_03  5508/tcp" >> /tmp/ace_services.txt
  echo "securidprop_04  5509/tcp" >> /tmp/ace_services.txt
  echo "securidprop_05  5510/tcp" >> /tmp/ace_services.txt
  echo "securidprop_06  5511/tcp" >> /tmp/ace_services.txt
  echo "securidprop_07  5512/tcp" >> /tmp/ace_services.txt
  echo "securidprop_08  5513/tcp" >> /tmp/ace_services.txt
  echo "securidprop_09  5514/tcp" >> /tmp/ace_services.txt
  echo "securidprop_10  5515/tcp" >> /tmp/ace_services.txt
  echo "sdadmind        5550/tcp" >> /tmp/ace_services.txt
  echo "sdlog           5520/tcp" >> /tmp/ace_services.txt
  echo "sdserv          5530/tcp" >> /tmp/ace_services.txt
  echo "sdlockmgr       5560/tcp" >> /tmp/ace_services.txt
  echo "sdcommd         5570/tcp" >> /tmp/ace_services.txt
  echo "sdoad           5580/tcp" >> /tmp/ace_services.txt

  "$CHMOD_EXEC" 640 /tmp/ace_services.txt
}

##############################################################################
# parse_command_line
# Determine what is to be done based on the specified command line.
##############################################################################
parse_command_line()
{
#
# Parse command line and determine setup type
#
  if [ -z "$1" ] ; then
    print_usage
  fi

  while [ "$#" -ne 0 ]
  do
    # Let's get rid of any leading dash (but remember it for later)...
    dash=`echo $1 | awk '{print substr($1,1,1)}'`
    if [ "$dash" = "-" ] ; then 
      firstarg=`echo $1 | awk '{print substr($1, 2 , length($1)-1)}'`
    else
      firstarg=$1
    fi
    case $firstarg in
      "$PRIMARY" | $REPLICA | $AGENT | config | license \
      | "$SDREPMGMT" | "$SDREPGEN" | "$APPLY_RP" | "$APPLY_CR" | "$PORT_CHG" )

        if [ -z "$INSTALL_TYPE" ] ; then
          INSTALL_TYPE=`echo $firstarg | awk '{print substr($1, 1, length($1))}'`
          if [ "$INSTALL_TYPE" = "$PRIMARY" -o "$INSTALL_TYPE" = "agent" ] ; then
            INSTALL_PRIMARY_OR_AGENT=TRUE
          fi
          if [ "$INSTALL_TYPE" = "$SDREPMGMT" ] ; then
              shift
              sdrepmgmt_opt="$*"
              break
          fi
          if [ "$INSTALL_TYPE" = "$SDREPGEN" ] ; then
              shift    
              first_arg="$*"
              break
          fi    
          if [ "$INSTALL_TYPE" = "$APPLY_RP" ] ; then
              shift    
              first_arg="$*"
              break
          fi    
          if [ "$INSTALL_TYPE" = "$APPLY_CR" ] ; then
              shift    
              first_arg="$*"
              break
          fi    
          if [ "$INSTALL_TYPE" = "$PORT_CHG" ] ; then
              shift
              if [ "$#" = "0" ] ; then    
                  first_arg=""
                  second_arg=""
              elif [ "$#" = "2" ] ; then 
                  if [ "$1" = "-" ] ; then
                      first_arg=""
                  else
                      first_arg="$1"
                  fi
                  second_arg="$2"
              elif [ "$#" = "1" ] ; then 
                  first_arg="$1"
                  second_arg=""
              else
                  print_usage "long"
              fi
              break
          fi    

        else
          print_usage
        fi
        shift;;
      
      f ) if [ -z "$2" -o "$dash" != "-" ] ; then
           print_usage "long"

# Don't use -f when there's no INSTALL_TYPE, or INSTALL_TYPE is 
# PRIMARY or when -f is followed directly by something else with a -.
          else
            if [ -z "$INSTALL_TYPE" -o \
                `echo "$2" | awk '{print substr($1, 1, 1)}'` = "-" -o \
                "$INSTALL_TYPE" != "$PRIMARY" -a \
                "$INSTALL_TYPE" != "$REPLICA" ] ; then
              print_usage "long"
            else
              OWNER_NAME="$2"
              SKIPWARNING=TRUE
            fi
          fi
        shift;shift;;
    
      o ) if [ -z "$2" -o "$dash" != "-" ] ; then
           print_usage "long"

# Don't use -o when there's no INSTALL_TYPE, or INSTALL_TYPE is
# in the list, or -o is followed directly by something else with a -.
          else
            if [ -z "$INSTALL_TYPE" -o \
                `echo "$2" | awk '{print substr($1, 1, 1)}'` = "-" -o \
                "$INSTALL_TYPE" = "config" -o \
                "$INSTALL_TYPE" = "license" ] ; then
              print_usage "long"
            else
              if [ "$2" != "yes" -a "$2" != "no" -a \
                  "$2" != "YES" -a "$2" != "NO" ] ; then
                print_usage "long"
            else
              OVERWRITE="$2"
            fi
          fi
        fi
        shift;shift;;

    p) if [ -z "$2" -o "$dash" != "-" ] ; then
          print_usage "long"
        else
#
# Don't use -p when there's no INSTALL_TYPE, or INSTALL_TYPE is
# in the list, or -p is followed directly by something else with a -.
#
          if [ -z "$INSTALL_TYPE" -o \
               `echo "$2" | awk '{print substr($1, 1, 1)}'` = "-" -o \
               "$INSTALL_TYPE" = "config" -o \
               "$INSTALL_TYPE" = "license" ] ; then
            print_usage "long"
          else
            PATH_ROOT="$2"
          fi
        fi
        shift;shift;;
#
#Use -c switch to enter the CD location on the command line  
#
    c) if [ -z "$2" -o "$dash" != "-" ] ; then
          print_usage "long"
        else
#
# Don't use -c when there's no INSTALL_TYPE, or INSTALL_TYPE is
# in the list, or -c is followed directly by something else with a -.
#
          if [ -z "$INSTALL_TYPE" -o \
               `echo "$2" | awk '{print substr($1, 1, 1)}'` = "-" -o \
               "$INSTALL_TYPE" = "config" -o \
               "$INSTALL_TYPE" = "license" ] ; then
            print_usage "long"
          else
            ACE_INSTALL_DIR="$2"
          fi
        fi
        shift;shift;;
# Sdrepmgmt parameters are passed through unparsed above.
# This codes does not get executed and is only
# here if needed in the future.
    l | list ) if [ "$INSTALL_TYPE" != "$SDREPMGMT" ] ; then
          print_usage "long"
       else
          sdrepmgmt_opt="list"
       fi
       shift;;
    a | add ) if [ "$INSTALL_TYPE" != "$SDREPMGMT" ] ; then
          print_usage "long"
       else
          sdrepmgmt_opt="add"
       fi
       shift;;
    d | delete ) if [ "$INSTALL_TYPE" != "$SDREPMGMT" ] ; then
          print_usage "long"
       else
          sdrepmgmt_opt="delete"
       fi
       shift;;
    m | modify ) if [ "$INSTALL_TYPE" != "$SDREPMGMT" ] ; then
          print_usage "long"
       else
          sdrepmgmt_opt="modify"
       fi
       shift;;
    r | refresh ) if [ "$INSTALL_TYPE" != "$SDREPMGMT" ] ; then
          print_usage "long"
       else
          sdrepmgmt_opt="refresh"
       fi
       shift;;
    n | nominate ) if [ "$INSTALL_TYPE" != "$SDREPMGMT" ] ; then
          print_usage "long"
       else
          sdrepmgmt_opt="nominate"
       fi
       shift;;
    t | tag ) if [ "$INSTALL_TYPE" != "$SDREPMGMT" ] ; then
          print_usage "long"
       else
          sdrepmgmt_opt="tag"
       fi
       shift;;
    r | rep_dir ) if [ "$INSTALL_TYPE" != "$REPLICA" ] ; then
          print_usage "long"
        else
          REP_ACE="$2"
          shift
        fi
        shift;;
    * ) print_usage;;
esac
if [ "$INSTALL_TYPE" = "$PRIMARY" ] ; then
      INSTALL_TYPE_PRETTY="$PRIMARY_PRETTY"
    elif [ "$INSTALL_TYPE"="REPLICA" ] ; then 
      INSTALL_TYPE_PRETTY="$REPLICA_PRETTY"
    else
      INSTALL_TYPE_PRETTY="$INSTALL_TYPE"
    fi
done
}
##############################################################################
# check_ace_version()
# Look in the installation directory and make sure the version of the ACE
# software matches what is expected.
##############################################################################
check_ace_version()
{
   expected_version=$1

   if [ ! -f $VAR_ACE/version.txt ] ; then
      echo "The $VAR_ACE/version.txt was not present.  Unable to"
      echo "automatically determine ACE software version.  Verify"
      echo "the $SERVER_NAME software has been installed."
      abort_installation
   fi

   get_ace_version

   if [ "$ACE_VERSION" != "$expected_version" ] ; then
      echo "The currently installed software version ($ACE_VERSION) does not"
      echo "match the expected version ($expected_version).  Aborting."
      abort_installation
   fi  
}

##############################################################################
# common_primary_replica_client()
# The primary/replica/agent installations have alot in common. Try to consolidate 
# common operations here so Mainline doesn't look cluttered.
##############################################################################
common_primary_replica_client()
{
    verify_sdinstall_dir
    check_startup
    get_ace_version

# Display appropriate startup screens
    startup_screens

# Prompt for the file ownername and top level directory name.
    setup_owner_name
    setup_install_path
  # Check for disk space.
  check_if_enough_space


# The PATH_ROOT/ace directory now belongs to us, so wipe it out on abort.
## (No, let's wait until we actually make the copy.)

  if [ "$INSTALL_TYPE" = "$REPLICA" -a "$PRESERVE_DB" = FALSE ] ; then
    get_rep_ace
  fi

  if  [ "$INSTALL_TYPE" = "$PRIMARY" -o "$INSTALL_TYPE" = "$REPLICA" ] ; then
    # check for existence of the required license, cert and config files
    find_license_config
    # now copy them to the ace/data directory
    setup_license_config
  fi

# check for the config file before going further
  if [ "$INSTALL_TYPE" = "$AGENT" ] ; then
    setup_agent_config
  fi
  
# Untar files to target directories
    install_files

# Uncompress files and edit all shell scripts.
    rename_commonz
    uncompress_package

    cd "$USR_ACE"
    $MV_EXEC dps sdoad

# move the Agent message catalog file from .../ace/prog to .../ace/data
  mv $PATH_ROOT/ace/prog/sdmsg.cat "$PATH_ROOT/ace/data"

# Link sdace.txt from /etc to ace/prog
    write_ace_file

}

##############################################################################
# common_primary_replica()
# The primary_replica installations have alot in common.
# Try to consolidate common operations here so Mainline doesn't
# look cluttered.  Some exceptions are made where processing
# order might be affected.
##############################################################################
common_primary_replica()
{
  
# Move utils and documentation
   move_utils
   move_doc

# in 5.0, user can run the toolkit on both primary and replica
   move_adminutils

# Customize any scripts.  Some have coded pathnames that need to be removed.
   edit_scripts

   install_queries

# Setup file ownerships and permissions
   change_file_groups
   set_file_ownerships
   set_file_permissions
 
# Setup the server database
   setup_server_database
# Repair report db
  repair_sdrpt_db 
}

##############################################################################
# process_primary()
# Try to perform all operations specific to the primary installation here.
##############################################################################
process_primary()
{
# Do license limit check

    check_license_limit

#   At this moment we are already at the end of the installtion 
#   so if it was an upgrade and user presented a new license
#   try to use it for upgrade
    if [ "$APPLY_NEW_LICENSE" = "TRUE" ] ; then
	upgrade_license_file "$SOURCE_DIR_LICENSE_FILENAME"
    fi
    $USR_ACE/sdrsakeygen -keyfile $VAR_ACE/radius.key
    $USR_ACE/sdcertreqgen -keyfile $VAR_ACE/radius.key -reqfile $VAR_ACE/radius.req -subject 'RSA RADIUS Server'
    $USR_ACE/sdcertgen -keyfile $VAR_ACE/radius.key -reqfile $VAR_ACE/radius.req -certfile $VAR_ACE/radius.cer -ca 'RSA RADIUS Server'
    rm -f $VAR_ACE/radius.req 
    rm -f $USR_ACE/sdrsakeygen
    rm -f $USR_ACE/sdcertreqgen
    rm -f $USR_ACE/sdcertgen
}

##############################################################################
# process_replica()
# Try to perform all operations specific to the replica installation here.
##############################################################################
process_replica()
{
  # Now when replica can be nominated it should have same files as primary

  #check to see if we exist in the sdrepnodes.txt file

  echo ""
}

##############################################################################
# process_client()
# Try to perform all operations specific to the agent installation here.
##############################################################################
process_client()
{
# Customize any scripts.
    edit_scripts

# Setup file ownerships and permissions
    change_file_groups
    set_file_ownerships
    set_file_permissions
}


##############################################################################
# process_license()
# Try to perform all operations specific to the license installation here.
##############################################################################
process_license()
{
    check_startup

    echo ""
    echo "Updating license.rec in directory '$VAR_ACE'..."
    upgrade_license_file ./license.rec
    echo ""
    if [ "$UPGRADE_SUCCESS" = TRUE ] ; then
      echo "License update completed."
      echo ""
      echo "Stop and restart $SERVER_NAME and database brokers"
      echo "for the changes to take effect."
    fi
}

##############################################################################
# process_config()
# Try to perform all operations specific to creating 
# a new configuration record here.
##############################################################################
process_config()
{
    check_startup
    PATH_ROOT=`echo "$USR_ACE" | awk '{ print substr ($1, 1, length($1)-9) }'`
    
    # Get current owner
    OLD_OWNER_NAME="`$USR_ACE/sdcfgval ownername`"

    # Now we allow the configuring of the replica configuration record
    if $USR_ACE/sdconfig -config ; then
         :
    else
         abort_installation
    fi

    NEW_OWNER_NAME="`$USR_ACE/sdcfgval ownername`"

    if [ "$NEW_OWNER_NAME" != "root" -a "$OLD_OWNER_NAME" != "$NEW_OWNER_NAME" ] ; then
        # Owner changed and he is not root
        echo ""
        echo "The owner that you specified for the RSA Authentication Manager is not root."
        echo "If that is correct, you must synchronize the time between the Primary"
        echo "and Replica Servers either by using a reliable time service such as NTP"
        echo "or by allowing the RSA replication service to run as a root level process."
        getyesorno_noabort TRUE "Do you want to continue? (y/n) [y]: "
        if [ "$YESORNO" = TRUE ] ; then
            echo ""
            echo "Setup can make the RSA replication service a root level process"
            echo "so that it synchronizes the time between the Primary and Replica."
            echo "Otherwise, you must use a reliable time synchronization service"
            echo "such as NTP."
            getyesorno_noabort TRUE "Do you want to make the replication service a root level process? (y/n) [y]: "
            if [ "$YESORNO" = TRUE ] ; then
                REPLICATION_ELEVATED=TRUE
            fi
        else
            # User does not want to continue - restore old name
            $USR_ACE/sdcfgval owner_set $OLD_OWNER_NAME
            echo ""
            echo "Restoring original ownership. Owner is $OLD_OWNER_NAME..."
            # Even if the owner has not changed we will 
            # run the group and ownership update
            # to bring all files to proper access level.
        fi

        if [ "$REPLICATION_ELEVATED" = TRUE ] ; then
            "$CHMOD_EXEC" 4110 acesyncd             
        else                                        
            "$CHMOD_EXEC" 110 acesyncd              
        fi                                            
    fi

    if [ "$CUR_UID" = "0" ] ; then
        set_file_ownerships
        change_file_groups
    fi
  
    check_services
    write_ace_services_file

    check_newdb_connections "$VAR_ACE/sdserv" server
    echo ""
    echo "Configuration update completed."
}

##############################################################################
# process_sdrepmgmt()
# Run sdrepmgmt to allow the administrator to manipulate the replica table.
# This includes, adding, modifying, promoting, and deleting replica entries.
##############################################################################
process_sdrepmgmt()
{
  # If the executable exists, run it.
  if [ ! -x $USR_ACE/$SDREP_EXEC ] ; then 
    echo "Executable not found"
    echo "Unable to run Replica Management."
    abort_installation 
  fi

  OLDUMASK=`umask`
  umask $USER_FULL_ACCESS
  $USR_ACE/$SDREP_EXEC $sdrepmgmt_opt
  RET_CODE="$?"
  umask $OLDUMASK

  if [ 0 = $RET_CODE ] ; then
    echo ""
    echo "SDREPMGMT $sdrepmgmt_opt successful."  
    echo ""
  fi
}

##############################################################################
# create_common_package()
# Creates a package for all listed replicas.
##############################################################################
create_common_package()
{
    HOSTS="$*"

    CCPOLDUMASK=`umask`
    umask $USER_FULL_ACCESS

    # We will have parameter only if we are envoked from command line
    if [ "$HOSTS" != "" ] ; then
        process_sdrepgen "$HOSTS" 
        umask $CCPOLDUMASK
        return
    fi

    # First check that we have any replicas and if we do
    # generate package for all of them 
    REP_COUNT="`$USR_ACE/$SDREP_EXEC xcount`" 
    REP_ERR="$?"
    if [ "$REP_ERR" != "0" ] ; then
        echo ""
        echo "Cannot determine number of Replicas in the database."
        echo "Replica Package will not be generated."
        echo "To generate Replica Package manually use:"
        echo "sdsetup -package"
        echo "For more details check UNIX Installation Guide (aceservdoc/unix_install.pdf"
        echo "on the $SERVER_NAME CD) for information about contacting technical support."
        echo ""
        umask $CCPOLDUMASK
        return
    fi

    if [ "$SILENT_MODE" = TRUE ] ; then
        if [ "$REP_COUNT" -gt 0 ] ; then
            process_sdrepgen "$SD_ALL_REPLICAS"
        fi
        umask $CCPOLDUMASK
        return
    fi

    # Here if not silent mode 
    
    echo ""
    echo "One Primary and $REP_COUNT Replica Servers in the database."
    
    #Check the license type we have
    LIC_EXEC="$USR_ACE/rsalicutil"
    LIC_TYPE=`$LIC_EXEC -t -f "$VAR_ACE/license.rec" "lictype"`
    RET_CODE="$?"
    if [ "$RET_CODE" != "0" ] ; then
        echo ""
        echo "Cannot execute license utility."
        echo ""
        umask $CCPOLDUMASK
        return
    fi

    # Check the license that we can add more replicas 
    # For this envoke license utility
    LIC_EXEC="$USR_ACE/rsalicutil"
    REP_LIC=`$LIC_EXEC -t -f "$VAR_ACE/license.rec" "inumlicensedreplicas"`
    RET_CODE="$?"
    if [ "$RET_CODE" != "0" ] ; then
        echo ""
        echo "Cannot execute license utility."
        echo ""
        umask $CCPOLDUMASK
        return
    fi

    # Bug # 28136.
    # We should be able to add replicas in UPGRADE VIOLATION mode also
    # Compare what we have and what our license allows
    if [ "$REP_COUNT" -lt "$REP_LIC" -o "Upgrade Violation" = "$LIC_TYPE" ] ; then
        if [ "Upgrade Violation" = "$LIC_TYPE" ] ; then
             REP_LIC=10
        fi
        MORE_REP=`expr $REP_LIC - $REP_COUNT`
        echo "Current license allows to add $MORE_REP more Replica(s) to your database."
        getyesorno FALSE "Do you want to add new Replicas before generating Replica Package? (y/n) [n]: "
        if [ TRUE = "$YESORNO" ] ; then
            SD_SUPPRESS_CANCEL=1;export SD_SUPPRESS_CANCEL
            echo ""
            echo "Specify Replica name at the prompt."
            echo "Press 'Enter' at the prompt to finish entering new Replicas."
            until [ "$REP_LIC" = "$REP_COUNT" ] ;
            do
                echo ""
                $USR_ACE/$SDREP_EXEC add 
                RET_CODE="$?"
                if [ 0 = $RET_CODE ] ; then
                    echo ""
                    echo "Replica was added successfully."
                    echo ""
                    REP_COUNT=`expr $REP_COUNT + 1`
                fi
 
                if  [ "$REP_LIC" = "$REP_COUNT" ] ; then
                    echo ""
                    echo "No more Replicas can be added to the database."
                    echo ""
                else 
                    getyesorno TRUE "Have you finished entering new Replicas? (y/n) [y]: "
                    if [ TRUE = "$YESORNO" ] ; then 
                        break
                    fi
                fi
            done
        fi
    fi    

    # Now we have as much replicas as we can
    if [ $REP_COUNT -gt 0 ] ; then
        echo ""
        getyesorno TRUE "There are '$REP_COUNT' Replica(s) in the database.\nDo you want to generate Replica Package for all known Replicas (y/n) [y]: "
        if [ TRUE = "$YESORNO" ] ; then
            process_sdrepgen "$SD_ALL_REPLICAS"
        else
            # May be they want to select specific replicas?
            getyesorno TRUE "Do you want to select Replicas that will be included into Replica Package (y/n) [y]: "
            if [ TRUE = "$YESORNO" ] ; then
                process_sdrepgen ""
            else
                # Nothing more to do here so just return
                umask $CCPOLDUMASK
                return
            fi
        fi
    else
        # No replicas nothing to do
        echo ""
        echo "There no Replicas in the database."
        echo "No Replica Package will be generated." 
        echo ""
    fi
    umask $CCPOLDUMASK
}



##############################################################################
# process_sdrepgen()
# Run sdrepgen to allow the administrator to generate a replica package.
# This can be passed a host name to have a package generated for just
#      a single host.
##############################################################################
process_sdrepgen()
{
  REPNAMEPARAM="$*"

  if [ "$REPNAMEPARAM" = "$SD_ALL_REPLICAS" ] ; then
     echo "Generating Replica Package for all known Replica Servers."
  elif [ "$REPNAMEPARAM" != "" ] ; then
     echo "Generating Replica Package for $REPNAMEPARAM."
  else
     echo "Generating Replica Package."
  fi

## First check to be sure that we are on a primary...

# If the executable exists, run it.
  if [ ! -x $USR_ACE/$SDREP_EXEC ] ; then 
    echo ""
    echo "Executable not found or insufficient access."
    echo "Unable to run Replica Management."
    echo ""
    return
  fi
  
  OLDUMASK=`umask`
  umask $USER_FULL_ACCESS
  $USR_ACE/$SDREP_EXEC primary > /dev/null
  RET_CODE="$?"

  if [ 1 != $RET_CODE ] ; then 
    echo "This operation may only be performed on the Primary Server."
    umask $OLDUMASK
    return
  fi

  
  # The definition of the following REP_ACE variables depends upon where we are.
  # They are different for a client or a replica. Perhaps we should call 
  # get_rep_ace here too?

  if [ "$REP_ACE" = "" ] ; then
    REP_ACE=$VAR_ACE/replica_package; export REP_ACE
  fi
   
  REP_ACE_DB=$REP_ACE/database; export REP_ACE_DB
  REP_ACE_LICENSE=$REP_ACE/license; export REP_ACE_LICENSE

  # All error messages and wairnigns are inside the Replica management utility 
  if [ "$REPNAMEPARAM" != "" ] ; then
      $USR_ACE/$SDREP_EXEC initiate_dbpush "$REPNAMEPARAM" 
  else
      $USR_ACE/$SDREP_EXEC initiate_dbpush
  fi

  # If we are internally envoked then this is upgrade and we have 
  # uidxlate.map file we need to provide
  if [ "TRUE" = "$ROLLING_UPGRADE" ] ; then
     cp -p $VAR_ACE/uidxlate.map $REP_ACE_LICENSE
     RET_CODE="$?"
     if [ 0 != $RET_CODE ] ; then
       echo ""
       echo "Error attempting to copy UID translation map to $REP_ACE_LICENSE."
       echo ""
     fi
  fi
  umask $OLDUMASK

  # Set permissions
  set_rp_permissions

}

#############################################################################
# Wrapping function to change port and service name of the replca's replication 
# service
#############################################################################
change_service_port()
{
    common_replica_checks "check"
    if [ "$CHECK_FAILED" = TRUE ] ; then
       return
    fi

    update_rep_port_and_name $1 $2
}
#############################################################################
# Function to change port and service name of the replca's replication 
# service
#############################################################################
update_rep_port_and_name()
{

    OLD_SERVICE_PORT="`$USR_ACE/$SDREP_EXEC xgetsp`"
    OLD_SERVICE="`echo $OLD_SERVICE_PORT | awk '{ print $1 }'`"   
    OLD_PORT="`echo $OLD_SERVICE_PORT | awk '{ print $2 }'`"   

    echo ""
    echo "Settings for current Replica are:"
    echo "    Service Name: \"$OLD_SERVICE\""
    echo "     Port Number: \"$OLD_PORT\""
    echo ""

       # First check the parameters
    if [ "$1" = "" -a "$2" = "" ] ; then
        # Nothing specified
        # We will go interactive
        echo_no_nl "Enter new Service Name or press Enter to leave it unchanged: "
        NEW_SERVICE=`$LINE_EXEC`
        echo ""
        echo_no_nl "Enter new Port Number or press Enter to leave it unchanged: "
        NEW_PORT=`$LINE_EXEC`
        ASK_CONFIRM=TRUE
    else
        NEW_SERVICE="$1"
        NEW_PORT="$2"
    fi

    # Handle the cases when nothing changed
    if [ "$NEW_SERVICE" = "" -a "$NEW_PORT" = "" ] ; then
        echo ""
        echo "No new Service Name or Port Number has been specified."
        echo "The current settings will remain unchanged."
        echo ""
    elif [ "$NEW_SERVICE" = "$OLD_SERVICE" -a "$NEW_PORT" = "$OLD_PORT" ] ; then
        echo ""
        echo "New Service Name and Port Number are same as the current ones."
        echo "The current settings will remain unchanged."
        echo ""
    else
        if [ "$NEW_SERVICE" = "" ] ; then
            NEW_CONF_SERVICE=$OLD_SERVICE
        else
            NEW_CONF_SERVICE=$NEW_SERVICE
        fi
        if [ "$NEW_PORT" = "" ] ; then
            NEW_CONF_PORT=$OLD_PORT
        else
            NEW_CONF_PORT=$NEW_PORT
        fi
        if [ "$ASK_CONFIRM" = TRUE ] ; then
            echo ""
            echo "You have specified following new values for Service Name and Port Number:"
            echo "    Service Name: \"$NEW_CONF_SERVICE\""
            echo "     Port Number: \"$NEW_CONF_PORT\""
            echo ""
            getyesorno_noabort TRUE "Do you want to apply these values? (y/n) [y]: "
            if [ "$YESORNO" = FALSE ] ; then
                echo ""
                echo "Service Name or Port Number change operation was cancelled."
                echo ""
                return
            fi
        fi
        # Something changed try to apply
        CSPOLDMASK=`umask`
        umask $USER_FULL_ACCESS
        $USR_ACE/$SDREP_EXEC xupdatesp "$NEW_SERVICE" "$NEW_PORT"
        if [ "$?" = "0" ] ; then
            echo ""
            echo "New settings were successfully applied."
            echo "Change the /etc/services file to match new settings."
            echo "Remove line:"
            echo "$OLD_SERVICE \t\t\t$OLD_PORT/tcp"
            echo "Insert line:"
            echo "$NEW_CONF_SERVICE \t\t\t$NEW_CONF_PORT/tcp"
            echo ""
        else        
            echo ""
            echo "Service Name or Port Number change operation failed." 
            echo ""
        fi
        umask $CSPOLDMASK
    fi
}

#############################################################################
# Function to apply configuration record
#############################################################################
apply_config()
{
    PATH_TO_CONFIG="$1"

    ACOLDUMASK=`umask`
    umask $USER_FULL_ACCESS

    common_replica_checks ""
    if [ "$CHECK_FAILED" = TRUE ] ; then
       umask $ACOLDUMASK
       return
    fi
    VALID_PATH=FALSE
    until [ "$VALID_PATH" = TRUE ] ;
    do
        # First check the path
        if [ "$PATH_TO_CONFIG" = "" ] ; then
            # Prompt user for path to the configuration record
            echo ""
            echo_no_nl "Enter the path to the directory containing\nConfiguration Record (sdconf.rec) for this Replica: "
            PATH_TO_CONFIG=`$LINE_EXEC`
        
        elif [ ! -d "$PATH_TO_CONFIG" ] ; then 
            # Path does not exist

            if [ "$1" != "" ] ; then
                echo ""
                echo "Specified directory does not exist."
                echo ""
                umask $ACOLDUMASK
                return
            fi

            echo ""
            getyesorno_noabort TRUE "Specified directory does not exist.\nDo you want to specify another path? (y/n) [y]: "
            if [ "$YESORNO" = FALSE ] ; then
                echo ""
                echo "Apply Configuration Record operation was cancelled."
                echo ""
                umask $ACOLDUMASK
                return
            fi
            PATH_TO_CONFIG=""
        elif [ ! -f "$PATH_TO_CONFIG/sdconf.rec" ] ; then 
           
            if [ "$1" != "" ] ; then
                echo ""
                echo "No Configuration Record found in the specified location."
                echo ""
                umask $ACOLDUMASK
                return
            fi

            echo ""
            getyesorno_noabort TRUE "Configuration Record does not exist in the specified location.\nDo you want to specify another path? (y/n) [y]: "
            if [ "$YESORNO" = FALSE ] ; then
                echo ""
                echo "Apply Configuration Record operation was cancelled."
                echo ""
                umask $ACOLDUMASK
                return
            fi
            PATH_TO_CONFIG=""
        else
            # File exists so we can apply it but we need confirmation
            if [ "$1" != "" ] ; then
                VALID_PATH=TRUE
            else
                getyesorno_noabort TRUE "A Configuration Record was found at the specified location.\nDo you want to apply this Configuration Record? (y/n) [y]: "
                if [ "$YESORNO" = FALSE ] ; then
                    echo ""
                    echo "Apply Configuration Record operation was cancelled."
                    echo ""
                    umask $ACOLDUMASK
                    return
                else
                    VALID_PATH=TRUE
                fi
            fi
        fi
    done

    $USR_ACE/sdconfig -upgrade $PATH_TO_CONFIG/sdconf.rec
    RET_CODE="$?"
    if [ "$RET_CODE" != "0" ] ; then
        echo ""
        echo "Failed to update configuration record ($RET_CODE)."
        echo ""
        umask $ACOLDUMASK
        return
    fi

    PATH_ROOT="$USR_ACE/../.."
    set_file_ownerships
    change_file_groups
    check_services
    write_ace_services_file
    $USR_ACE/sdinfo | more
    check_newdb_connections "$VAR_ACE/sdserv" server
    echo ""
    echo "Configuration update completed."

    umask $ACOLDUMASK
    
}


#############################################################################
# Function to apply full or partial package to the replica
#############################################################################
apply_package()
{
    PATH_TO_PACKAGE=$1
    PRIMARY_APPLY_PACKAGE=TRUE
    common_replica_checks "check"
    if [ "$CHECK_FAILED" = TRUE ] ; then
        return
    fi

    VALID_PATH=FALSE
    until [ "$VALID_PATH" = TRUE ] ;
    do
        # First check the path
        if [ "$PATH_TO_PACKAGE" = "" ] ; then
            # Prompt user for path to the package
            echo ""
            echo_no_nl "Enter the path to the top level directory containing\nReplica Package for this Replica: "
            PATH_TO_PACKAGE=`$LINE_EXEC`
        
        elif [ ! -d "$PATH_TO_PACKAGE" ] ; then 
            # Path does not exist

            if [ "$1" != "" ] ; then
                echo ""
                echo "Specified directory does not exist."
                echo ""
                return
            fi

            echo ""
            getyesorno_noabort TRUE "Specified directory does not exist.\nDo you want to specify another path? (y/n) [y]: "
            if [ "$YESORNO" = FALSE ] ; then
                echo ""
                echo "Apply Replica Package operation was cancelled."
                echo ""
                return
            fi
            PATH_TO_PACKAGE=""
        else
            check_consitency_of_package $PATH_TO_PACKAGE
            # Package mode will be set to 0 if valid
            # and to -1 if it is incomplete or corrupted
            if [ "$PACKAGE_MODE" = "-1" ] ; then
                if [ "$1" != "" ] ; then
                    echo ""
                    echo "Invalid Replica Package."
                    echo ""
                    return
                fi

                getyesorno_noabort TRUE "Invalid Replica Package.\nDo you want to specify another path? (y/n) [y]: "
                if [ "$YESORNO" = FALSE ] ; then
                    echo ""
                    echo "Apply Replica Package operation was cancelled."
                    echo ""
                    return
                else
                    PATH_TO_PACKAGE=""
                fi
            else
                # Prepare variables

                DO_NOT_TOUCH_LOG=TRUE
    
                REP_ACE=$PATH_TO_PACKAGE;export REP_ACE
                REP_ACE_DB=$REP_ACE/database; export REP_ACE_DB
                REP_ACE_LICENSE=$REP_ACE/license; export REP_ACE_LICENSE
                SDREPNODES=$REP_ACE_LICENSE/sdrepnodes.txt; export SDREPNODES
    
                # Validate that replica package is of proper language and 
                # for this replica
                validate_repnodes
                if [ "$?" != "0" ] ; then

                    if [ "$1" != "" ] ; then
                        return
                    fi

                    getyesorno_noabort TRUE "Invalid Replica Package.\nDo you want to specify another path? (y/n) [y]: "
                    if [ "$YESORNO" = FALSE ] ; then
                        echo ""
                        echo "Apply Replica Package operation was cancelled."
                        echo ""
                        return
                    else
                        PATH_TO_PACKAGE=""
                    fi
                else
                    if [ "$1" != "" ] ; then
                        VALID_PATH=TRUE
                    else
                        getyesorno_noabort TRUE "A valid Replica Package was found at the specified location.\nDo you want to apply this package? (y/n) [y]: "
                        if [ "$YESORNO" = FALSE ] ; then
                            echo ""
                            echo "Apply Replica Package operation was cancelled."
                            echo ""
                            return
                        else
                            VALID_PATH=TRUE
                        fi
                    fi      
                fi
            fi
        fi
    done
    

    APOLDUMASK=`umask`
    umask $USER_FULL_ACCESS

    # Copy license directory files 
    # Do not copy confrec
    for atfil in license.rec server.cer sdti.cer server.key
    do
       cp $REP_ACE_LICENSE/$atfil "$VAR_ACE"
    done
    
    # Copy files
    copy_dbfiles_from_package
    if [ "$?" != "0" ] ; then
        echo "Failed to apply Replica Package."
        umask $APOLDUMASK
        return
    fi
    set_db_permissions
#   Currently do not ask about elevation whe we apply package
#   ask_about_ep_replica "$USR_ACE"
    echo ""
    echo "Replica Package was successfully applied."
    echo "" 
    umask $APOLDUMASK
}

#############################################################################
# Function to check the repnodes.
# 1) Check that this package is for this replica
# 2) Check that package is of valid language
#############################################################################
validate_repnodes()
{
    # Unfortunately on UNIX we can't use the sdrepmgmt to validate the package
    # The problem is of chicken and egg.
    # We need to validate the package before we create database
    # so we can abort at early stage before even starting to copy files.
    # At the moment we do the check the sdrepmgmt is not in place
    # and database is not yet created.
    # If it is in place we still need to have database and the database is
    # created very late during the installation.
    # We will use sdcfgval to overcome this problem


    TMP_VAR_ACE=$VAR_ACE
    VAR_ACE=$REP_ACE_LICENSE; export VAR_ACE

    if [ -f "$INSTALL_TOOLS_DIR/sdconfig" ] ; then
        CONFIG_LOCATION=$INSTALL_TOOLS_DIR;export CONFIG_LOCATION
    else
        CONFIG_LOCATION=$USR_ACE;export CONFIG_LOCATION
    fi

    $CONFIG_LOCATION/sdcfgval package $VAR_ACE $DEF_PAGE
    RET_CODE="$?"

    VAR_ACE=$TMP_VAR_ACE;export VAR_ACE

    # Check results
    # See rm_errors.h for error codes

    if [ "$RET_CODE" != "0" ] ; then
        if [ "$RET_CODE" = "4" ] ; then
            echo ""
            echo "Cannot apply Replica Package."
            echo "The Replica Package does not contain an entry for the " \
                 "current host."
            echo "Generate a new Replica Package for this host."
            echo ""
        elif [ "$RET_CODE" = "12" ] ; then
            echo ""
            echo "Cannot apply Replica Package."
            echo "Replica Package Language inconsistency was detected."
            echo "" 
        elif [ "$RET_CODE" = "14" ] ; then
            echo ""
            echo "The Replica Package was generated on this Primary Server."
            echo "Cannot apply Replica Package to the same server."
            echo ""
        else
            echo ""
            echo "Cannot apply Replica Package."
            echo "Replica Package is corrupted."
            echo "" 
        fi
        return 1
    fi

    return 0
}



#############################################################################
# Function to check that we are on replica and optionally check for brokers
#############################################################################
common_replica_checks()
{
    check_startup

    # If the executable exists, run it.
    if [ ! -x $USR_ACE/$SDREP_EXEC ] ; then 
        echo ""
        echo "Executable not found or insufficient access."
        echo "Unable to run sdrepmgmt."
        echo ""
        CHECK_FAILED=TRUE
        return
    fi
    # Check that this is replica
    OLDUMASK=`umask`
    umask $USER_FULL_ACCESS
    $USR_ACE/$SDREP_EXEC primary > /dev/null
    RET_CODE="$?"
    umask $OLDUMASK
    if [ "$PRIMARY_APPLY_PACKAGE" = FALSE ] ; then
      if [ "1" = "$RET_CODE" ] ; then
        echo ""
        echo "Selected operation can be executed on Replica only."
        echo ""
        CHECK_FAILED=TRUE
        return
      elif [ "0" = "$RET_CODE" ] ; then
        echo "You are running on a system that is not currently in dataase."
        # Let them proceed because we may be doing a rename or applying
        # a replica package.
      fi 
    fi 
    PRIMARY_APPLY_PACKAGE=FALSE
    # Do we need to check that brokers are runnig
    if [ "$1" = "check" ] ; then
        ## Now, let's determine if the database is available...
        if [ ! -x $DLC_PROUTIL ] ; then 
            echo ""
            echo "Executable not found or insufficient access."
            echo "Unable to run $DLC_PROUTIL."
            echo ""
            CHECK_FAILED=TRUE
            return
        fi
   
        $DLC_PROUTIL $VAR_ACE/sdserv -C busy  > /dev/null
        RET_CODE="$?"
        if [ 0 != $RET_CODE ] ; then 
            echo ""
            echo "Cannot execute selected operation while database brokers are running."
            echo "Shut down the database brokers."
            echo ""
            CHECK_FAILED=TRUE
            return
        fi
    fi
    CHECK_FAILED=FALSE
}

##############################################################################
# Function to ckeck the consitency of the package
##############################################################################
check_consitency_of_package()
{
    PACKAGE_PATH="$1"
    license_certs="license.rec server.key sdti.cer server.cer sdconf.rec"
    not_found=""
    # Check validity of the top level directory
    if [ ! -d "$PACKAGE_PATH" ] ; then 
        PACKAGE_MODE="-1"
        return
    fi

    # Check license directory existense
    if [ ! -d "$PACKAGE_PATH/license" ] ; then 
        PACKAGE_MODE="-1"
        return
    else
        # Check license directory entity
        for atfil in $license_certs
        do
           if [ ! -f "$PACKAGE_PATH/license/$atfil"   ] ; then
           not_found="$not_found $atfil"
           fi
        done 
        if [ ! -z "$not_found" ] ; then
           $CLEAR_EXEC
           echo "Unable to locate the following files:"
           for atfil in $not_found
           do
              echo "- $atfil"
           done
           PACKAGE_MODE="-1"
           return
        fi
    fi
    # Check data directory 
    if [ ! -d "$PACKAGE_PATH/database" ] ; then 
        PACKAGE_MODE="0"
        return
    fi

    # Check entity of the data directory
    if [ ! -f "$PACKAGE_PATH/database/sdserv.db" -a \
         ! -f "$PACKAGE_PATH/database/sdserv.lg" -a \
         ! -f "$PACKAGE_PATH/database/sdserv.b1" -a \
         ! -f "$PACKAGE_PATH/database/sdserv.d1" -a \
         ! -f "$PACKAGE_PATH/database/sdserv.st" -a \
         ! -f "$PACKAGE_PATH/database/sdserv.vrs" ] ; then 
        PACKAGE_MODE="0"
    elif [ ! -f "$PACKAGE_PATH/database/sdserv.db" -o \
         ! -f "$PACKAGE_PATH/database/sdserv.lg" -o \
         ! -f "$PACKAGE_PATH/database/sdserv.b1" -o \
         ! -f "$PACKAGE_PATH/database/sdserv.d1" -o \
         ! -f "$PACKAGE_PATH/database/sdserv.st" -o \
         ! -f "$PACKAGE_PATH/database/sdserv.vrs" ] ; then 
        PACKAGE_MODE="-1"
    else
        PACKAGE_MODE="0"
    fi

}

##############################################################################
# post_process_primary_replica_client()
# Try to perform all cleanup operations common to
# agent/replica/primary installs here.
##############################################################################
post_process_primary_replica_client()
{
#
# Finish up
#
    finish_install
    check_services
    check_acetmp
}

##############################################################################
##############################################################################
# "Mainline"
#
# Assumptions:
#
# - you logged in as root (primary, replica or $AGENT installations)
# - you logged in as root or fileowner (config, license)
# - this script is in your current working directory
# - your current working directory is not USR_ACE or VAR_ACE (installations)
#
##############################################################################
##############################################################################

############################
# Set up important variables
############################
trap 'trap "" 1 2 15; abort_installation' 1 2 15
ORIG_UMASK=`umask`
umask 277
#set -x

################# Phase 1 ##########################
# Perform initial variable definition and examine the
# $0 variable to find where the RSA Authentication Manager 
# Software is located.
# Also verify that the necessary OS programs required by
# the installation are avaliable.
##################################################
init_global_vars
check_os_version "common"
setup_platforms
check_exec_paths
get_install_directory
check_running

################# Phase 2 ##########################
# Examine the command line parameters and parse them to
# figure out what should be done.
##################################################

parse_command_line $*
check_silent_mode

################# Phase 3 ##########################
# Based on the command line we know the action to 
# perform.  Each potentially requires a different
# set of prompts.  These will be left for the 
# process routines.
##################################################

case "$INSTALL_TYPE"
in
  "$PRIMARY"  )
                check_os_version "server"
                common_primary_replica_client
                common_primary_replica
                process_primary
                post_process_primary_replica_client
                ;;
  "$REPLICA"  )
                check_os_version "server"
                common_primary_replica_client
                common_primary_replica
                process_replica
                post_process_primary_replica_client
                ;;
  "$AGENT"    )
		echo "Agent installation should be performed by running sdsetup in aceagent directory."
                ;;
  'license'   )
                process_license
                ;;
  'config'    )
                process_config
                ;;
  "$SDREPMGMT" )
                process_sdrepmgmt
                ;;
  "$SDREPGEN" )
                create_common_package "$first_arg"
                ;;
  "$APPLY_RP" )
                apply_package "$first_arg"
                ;;
  "$APPLY_CR" )
                apply_config "$first_arg"
                ;;
  "$PORT_CHG" )
                change_service_port "$first_arg" "$second_arg"
                ;;
       *      )
                print_usage
                ;;
esac
exit_cleanly
