#!<<_SHELL_>>

############# NECESSARY BINARIES GIVEN TO US BY THE CALLER.
PACKAGE_NAME="<<_PACKAGE_NAME>>"
PRODUCT_NAME="<<_PRODUCT_NAME>>"

DEFAULT_BASEDIR="<<_INSTALL_DIR>>"
DEFAULT_COMPONENTS="<<_COMPONENTS>>"
DEFAULT_JDK_SUPPORT="<<_JDK_SUPPORT>>"
DEFAULT_JDK_DIR="<<_JDK_DIR>>"

PERL_BINARY="<<_PERL_BINARY>>"
PERL="<<_PERL_>>"

SHELL_BINARY="<<_SHELL_BINARY>>"
SHELL="<<_SHELL_>>"

########################## Define global constants
INTERACTIVE_MODE=yes

DEFAULT_SYSTEMUSER=nobody
DEFAULT_ADMIN_SYSUSER=root
DEFAULT_ADMIN_NAME=admin
DEFAULT_ADMIN_PORT=8888
DEFAULT_STARTONBOOT=yes
# These values will change depending on who is running it
DEFAULT_BASEPORT=1024
DEFAULT_HTTPPORT=80

########################## Global scoped default variables.
# To be filled later in the main program.
DEFAULT_HOSTNAME=""
CURRENT_OS=""
DEFAULT_SYSTEMGROUP=""

###############################################################################
#------------------------------------------------------------------------------
#   Set the directory where the Webserver is being installed.
#------------------------------------------------------------------------------
###############################################################################
BASEDIR="$DEFAULT_BASEDIR"
DEFAULT_CONTENTROOT="${BASEDIR}/docs"
SETUPDIR="$BASEDIR/setup"

SETUP_INF_FILE="${SETUPDIR}/setup.inf"
SETUP_INF_FILE_TEMP="${SETUPDIR}/setup.inf.tmp"
WEBSERVER_INF_FILE="${SETUPDIR}/WebServer/WebServer.inf"
WEBSERVER_INF_FILE_TEMP="${SETUPDIR}/WebServer/WebServer.inf.tmp"

WS_ASKFILE="${SETUPDIR}/ws.askfile.orig"
ADMINPASSWORD_FILE="${SETUPDIR}/.adminpasswd"

##########################  General functions.


function space
{
  remaining=$1
  space=''
  while [ $remaining -gt 0 ]; do
    space="$space "
    remaining=$((remaining-1))
  done

  $WS_echo "$space"
}

function left_justify
{
  string=$1
  length=$2
  remaining=$(($length - ${#string}))

  $WS_echo "$string`space $remaining`"
}

function right_justify
{
  string=$1
  length=$2
  remaining=$(($length - ${#string}))

  $WS_echo "`space $remaining`$string"
}

function menu
{
  clear

  title=$1
  shift

  output="\n"
  output="$output -----------------------------------------------------------------------------\n"
  output="$output| "`left_justify "$title" 75`" |\n"
  output="$output|-----------------------------------------------------------------------------|\n"

  while [ $# -gt 0 ]; do
    output="$output| "`left_justify "$1" 75`" |\n"
    shift
  done
  output="$output -----------------------------------------------------------------------------\n"

  sys_echo -e -n "$output"
}

function query_user
{
  terminal_mark=":"
  invalid_choice="Invalid choice specified"
  query_message=$1
  shift

  options_list=""
  for each in "$@"; do
   before_equals=`$WS_echo $each | $WS_sed 's/=.*$//'`
   after_equals=`$WS_echo $each | $WS_sed 's/^.*=//'`

   case $before_equals in
    "default" )
      default_value="$after_equals"
      each=$default_value ;;
      # Fall-thru

    "terminal_mark" )
      terminal_mark="$after_equals"
      continue ;;

    "invalid_choice" )
      invalid_choice="$after_equals"
      continue ;;
   esac

   if [ "x$options_list" = "x" ]; then
      options_list=$each
   else
      options_list="$options_list:#:$each"
   fi
  done

  options=`$WS_echo $options_list | $WS_sed 's,:#:,/,g'`

  if [ "x$options" = "x" ]; then
    sys_echo "Error: Invalid use of query_user."
    exit 1;
  fi

  query_string="$query_message ($options)$terminal_mark";

  if [ "x$default_value" != "x" ]; then
    query_string="$query_string [$default_value] "
  fi

  while true; do
   sys_echo -n "$query_string"
   read -r readbuffer

   if [ "x$readbuffer" = "x" ] && [ "x$default_value" != "x" ]; then
      query_result=`$WS_echo $default_value | $WS_tr '[A-Z]' '[a-z]'`
      break
   fi

   if $WS_echo $options | $WS_tr '/' '\n' | $WS_grep -i "^$readbuffer$" > /dev/null 2>&1; then
      # Lower-case translate
      query_result=`$WS_echo $readbuffer | $WS_tr '[A-Z]' '[a-z]'`
      break;
   else
      sys_echo -n "$invalid_choice: Press Enter to retry ... "
      read -r dummy
      $WS_echo ""
   fi
  done
}

function sys_echo
{
  sys_echo_nonewline=0

  if [ -z "$BASH_VERSION" ]; then
    if [ -z "$sys_echo_uname" ]; then
      sys_echo_uname=`$WS_uname`
    fi
  else
    sys_echo_uname='all-bash'
  fi

  case $sys_echo_uname in
    Linux|all-bash)
      sys_echo_echoflags=""

      while true; do
        case "$1" in
          -e)
            sys_echo_echoflags="$sys_echo_echoflags -e"
            shift
            ;;

          -n)
            sys_echo_echoflags="$sys_echo_echoflags -n"
            sys_echo_nonewline=1
            shift
            ;;

          *)
            break
            ;;
        esac
      done

      $WS_echo $sys_echo_echoflags "$@"
      ;;

    AIX|SunOS|HP-UX)
      while true; do
        case "$1" in
          -e)
            shift
            ;;

          -n)
            sys_echo_nonewline=1
            shift
            ;;

          *)
            break
            ;;
        esac
      done

      if [ $sys_echo_nonewline -ne 0 ]; then
        $WS_echo "$*\c"
      else
        $WS_echo "$*"
      fi
      ;;

    *)
      $WS_echo "Error: Unsupported OS encountered." 1>&2
      ;;
  esac
}

function display
{
  joined=''
  while [ $# -gt 0 ]; do
    joined="$joined$1\n"
    shift
  done
  sys_echo -e -n $joined
}

function display_error
{
  error="\nError: $1\n"
  shift

  while [ $# -gt 0 ]; do
    #            Error:
    error="$error       $1\n"
    shift
  done

  error="$error\n"

  sys_echo -e -n $error
}

function display_note
{
  note="\nNote: $1\n"
  shift

  while [ $# -gt 0 ]; do
    #          Note:
    note="$note      $1\n"
    shift
  done

  note="$note\n"

  sys_echo -e -n $note
}

function pause
{
  display "$@" ""
  sys_echo -n "Press Enter to continue ..."

  read -r pause_dummy
}

function pause_error
{
  display_error "$@"
  sys_echo -n "Press Enter to continue ..."

  read -r pause_dummy
}

function pause_note
{
  display_note "$@"
  sys_echo -n "Press Enter to continue ..."

  read -r pause_dummy
}


######################### Installation functions

#
# Return value: 0 on success, 1 on error, 2 on function specific return values.
#
function signal_handler
{
  # Ignore signal handlers here.
  trap ":" 1 2 15

  sys_echo ""
  sys_echo "==============================================================================="
  sys_echo "Signal caught, performing cleanup ..."
  sys_echo "==============================================================================="

  # Make sure that the echo is enabled.
  $WS_stty echo

  #  FIX ME:
  #  Clean up any temporary files if necessary.
  cleanup
}
function cleanup
{
  sys_echo "Thanks for choosing ${PRODUCT_NAME}. "
  exit 1
}

# Detects a fully qualified hostname.
function detect_hostname
{
  default_hostname=""
  default_hostname=`$WS_hostname`
  RESOLV_FILE=/etc/resolv.conf

  # If the hostname is not a fully qualified domain name,
  # then we need to find this by ourselves.
  if $WS_echo $default_hostname| $WS_grep "\." > /dev/null 2>&1; then
    # This is a fully qualified domain name.
    :
  elif [ -f "$RESOLV_FILE" -a -r "$RESOLV_FILE" ]; then
    # We need to resolve a fully qualified domain name.
      domain_name=`$WS_cat $RESOLV_FILE | $WS_grep domain | $WS_head -n 1 | $WS_cut -d ' ' -f 2`
      if [ -n "$domain_name" ]; then
        default_hostname="$default_hostname.$domain_name"
      fi
  else
    # Hmm.. looks like something terribly wrong happened in determining 
    # the hostname.
    default_hostname=`
      $WS_perl -e 'use Sys::Hostname; use Socket;
        my $host=hostname(); my $hostbyname=gethostbyname($host);
        my $hostbyaddr=gethostbyaddr($hostbyname,AF_INET);
        print $hostbyaddr' 2>/dev/null`;
    if [ -z "$default_hostname" ]; then
      default_hostname=`$WS_hostname`
    fi
  fi
  $WS_echo $default_hostname
}

# Get the user given hostname and validate
# Return Status: 0 - success, 1 - Error
function validate_hostname
{
  machineName="$1"
  if [ -z "$machineName" ]; then
    return 1
  elif $WS_echo $machineName | $WS_grep '[^A-Za-z0-9_.-]' > /dev/null 2>&1; then
    # Not a valid hostname
    return 1
  else
    return 0
  fi
}

function validate_systemuser
{
  system_user=$1
  if [ -z "$system_user" ]; then
    # Invalid input.
    return 1
  fi
  # validate the userid by seeing if it is in the passwd database
  if $WS_getent passwd $system_user > /dev/null 2>&1; then
    return 0
  else
    return 1
  fi
}

# return value: 0 on success, 1 if system group does not currently exist,
#    2 if the system_user is not a member of the system_group
function validate_systemgroup
{
  system_group=$1
  system_user=$2
  if [ -z "$system_group" ]; then
    return 1;
  fi
  if [ -z "$system_user" ]; then
    return 1;
  fi

  # first validate the group by seeing if it is in the group database
  if $WS_getent group $system_group > /dev/null 2>&1; then
    :
  else
    return 1
  fi

  # then use groups to see if $system_group is a group that $system_user is in
  valid_group=`$WS_groups $system_user | $WS_grep $system_group 2>/dev/null`
  if [ -z "$valid_group" ]; then
    # Hmm.. unable to validate the user information.
    return 2
  fi
  return 0
}

function validate_serverPort
{
  serverPort=$1
  if [ -z "$serverPort" ]; then
    # Invalid port specified here.
    return 2;
  fi

  port_in_use=`$WS_netstat -an | $WS_grep LISTEN | $WS_grep "[:.]$serverPort[^.:0-9]" 2>/dev/null`
  if [ -n "$port_in_use" ]; then
    return 1
  fi
  # Validate whether this port is a valid number.
  if [ $serverPort -lt $DEFAULT_BASEPORT -o $serverPort -gt 65535 ]; then
    return 2
  fi
  return 0
}

function validate_yesorno
{
  yes_or_no=$1
  if [ -z "$yes_or_no" ]; then
    return 2
  fi
  if [ $yes_or_no = 'y' -o $yes_or_no = 'Y' -o $yes_or_no = 'yes' -o $yes_or_no = 'Yes' -o $yes_or_no = "YES" ]; then
    return 1
  elif [ $yes_or_no = 'n' -o $yes_or_no = 'N' -o $yes_or_no = 'no' -o $yes_or_no = 'No' -o $yes_or_no = 'NO' ]; then
    return 0
  fi
  return 2
}


#------------------------------------------------------------------------------
#========================MAIN PROGRAM==========================================
#------------------------------------------------------------------------------

######################### Make sure certain values are always on the PATH
DEFAULT_PATH="/bin:/usr/bin:/sbin:/usr/sbin:/usr/ucb:/usr/local/bin"
if [ -z "$PATH" ]; then
  PATH=$DEFAULT_PATH
else
  PATH="$DEFAULT_PATH:$PATH"
fi
export PATH

# Make sure necessary binaries are NOT struck with wierd alias values.
unalias -a > /dev/null 2>&1


# The following binaries will be searched for in the following search
# paths.  Once located, their full paths will be put in variables named
# WS_<binary>.  If any binaries are missing, report the missing
# binary and exit.
binaries='stty:echo:id:whoami:chown:chmod:chgrp:cat:cut:tr:grep:egrep:sed:awk:tee:head:tail:cp:mv:rm:mkdir:touch:dirname:basename:uname:hostname:nslookup:netstat:getent:groups'
search_dirs=$PATH

OLD_IFS=$IFS
IFS=:

for binary in $binaries; do
  binary_path=""
  for dir in $search_dirs; do
    if [ -x "$dir/$binary" ]; then
      binary_path="$dir/$binary"
      break
    fi
  done

  if [ -z "$binary_path" ]; then
    echo "Error: Unable to locate binary '$binary'."
    echo "       Please make certain this binary is on your path and try again."
    exit 1
  else
    eval "WS_$binary=$binary_path"
  fi
done

IFS=$OLD_IFS


# Enable signal handler.
trap signal_handler 1 2 15

# check what OS we're on
OS=`$WS_uname -s`
if [ -z "$OS" ]; then
  display_error "Unable to determine operating system."
  exit 1
else
  CURRENT_OS="$OS"
fi

# Linux does not have umask as a command instead it is a shell command.
# So set the variables appropriately so that we can use it later.
if [ "$CURRENT_OS" = "Linux" ]; then
  WS_umask="umask"
else
  # For Solaris and other platforms, use umask if it is an executable.
  if [ -x "/bin/umask" ]; then
    WS_umask="/bin/umask"
  elif [ -x "/usr/bin/umask" ]; then
    WS_umask="/usr/bin/umask"
  else
    # Hope, there is a shell built in variable for this.
    WS_umask="umask"
  fi
fi

# Validate whether the user is a root user.
user=`$WS_whoami 2>/dev/null`
if [ "$user" != "root" ]; then
  display_error "This product must be installed as root."
  # Restrict the non root users to bind to port greater than $DEFAULT_BASEPORT.
  DEFAULT_BASEPORT=1024
  DEFAULT_HTTPPORT=1080
  exit 1;
else
  # For Root users, there is no restriction on the list
  # of ports they can bind to.
  DEFAULT_BASEPORT=1
  DEFAULT_HTTPPORT=80
fi

# Default file creation to 644 or 755.
$WS_umask 022

# Perl is necessary, but detect and report its error condition.
if [ -n "$PERL" ]; then
  WS_perl="$PERL"
fi

if [ -z "$WS_perl" ] && [ -x "/opt/perl/bin/perl" ]; then
  WS_perl="/opt/perl/bin/perl"
elif [ -z "$perl" ] && [ -x "/opt/perl5/bin/perl" ]; then
  WS_perl="/opt/perl5/bin/perl"
fi

if [ "x$WS_perl" = "x" ]; then
  # Perl must not have been detected properly.
  $WS_echo
  $WS_echo "Error: Setup could not find Perl on your machine. Perl must exist"
  $WS_echo "       for setup to continue."
  $WS_echo
  $WS_echo "Note: Make sure the perl program is installed and is in your path."
  $WS_echo
  exit 1
elif $WS_perl -e 'use 5.005_03;' > /dev/null 2>&1; then
  :
else
  # This version is not the supported version.
  perl_version=`$WS_perl -e 'print $]'`;
  $WS_echo "Error: Perl version $perl_version detected."
  $WS_echo "       Your perl version must be 5.005_03 or later to install"
  $WS_echo "       $PRODUCT_NAME."
  exit 1
fi

# Detect System configuration like hostname, port etc.
#####################################################################
DEFAULT_HOSTNAME=`detect_hostname`
if [ -z "$DEFAULT_HOSTNAME" ]; then
  display_error "Unable to detect the hostname."
  exit 1
fi

###############################################################################
#------------------------------------------------------------------------------
#   Did user pass in a filename providing variable info?
#   If so, include the file to get the variables
#------------------------------------------------------------------------------
###############################################################################
if [ x"$1" = x"-f" ]; then
  if [ -z "$2" ]; then
    display_error "You did not provide a filename"
    $WS_echo "usage:  configure [-f filename]"
    exit 1;
  else
    # make sure filename is absolute path
    if $WS_echo $2 | $WS_egrep '^/' > /dev/null 2>&1 ; then
      filename=$2
    else
      display_error \
      " Filename provided is not an absolute path." \
      " Filename must start with '/'." \
      ""
      exit 1;
    fi

    if [ -f $filename ]; then
      # Does the file look like a valid variable file?
      OLD_IFS=$IFS
      IFS='
'
      for line in `$WS_cat $filename`; do
        if $WS_echo $line | $WS_egrep '^[A-Za-z0-9_]+=.*$' > /dev/null 2>&1; then
	  :
	else
          display_error \
            "Format of '$filename' does not look valid." \
            "Each line should be of the format 'name=value'" \
            "with no whitespace." \
            ""
          exit 1;
        fi
      done
      IFS=$OLD_IFS

      $WS_cat $filename | $WS_grep -v "ADMINPASSWORD" > $WS_ASKFILE
      $WS_cat $filename | $WS_grep "ADMINPASSWORD" | $WS_sed "s/ADMINPASSWORD/AdminPassword/" > $ADMINPASSWORD_FILE

      if [ -f "$WS_ASKFILE" ] && [ -r "$WS_ASKFILE" ]; then
        :
      else
        display_error \
          "The file:'$WS_ASKFILE' doesn't exist." 
        exit 1
      fi

      if [ -f "$ADMINPASSWORD_FILE" ] && [ -r "$ADMINPASSWORD_FILE" ]; then
        :
      else
        display_error \
          "The file:'$ADMINPASSWORD_FILE' doesn't exist." 
        exit 1
      fi


      # Ok, include the file
      . $WS_ASKFILE

      INTERACTIVE_MODE=no
    else
      display_error "The filename provided does not appear to exist."
      exit 1;
    fi
  fi
elif [ -n "$1" ]; then
  display_error "usage:  configure [-f filename]"
  exit 1
fi

# Validate the current installation.
if [ -d "$SETUPDIR" ]; then
  :
else
  display_error \
  "" \
  "It appears that the package: ${PACKAGE_NAME} did not install successfully." \
  "Unable to find the folder:'$BASEDIR/setup'." \
  ""
  exit 1
fi

if [ -f "$SETUP_INF_FILE" ] && [ -r "$SETUP_INF_FILE" ]; then
  :
else
  display_error \
  "" \
  "It appears that the package: ${PACKAGE_NAME} did not install successfully." \
  "Unable to find FILE:'$SETUP_INF_FILE'." \
  ""
  exit 1
fi

if [ -f "$WEBSERVER_INF_FILE" ] && [ -r "$WEBSERVER_INF_FILE" ]; then
  :
else
  display_error \
  "" \
  "It appears that the package: ${PACKAGE_NAME} did not install successfully." \
  "Unable to find FILE:'$WEBSERVER_INF_FILE'." \
  ""
  exit 1
fi

###############################################################################
#  SOLARIS ONLY:
#   Default is /opt/SUNWwbsvr, but this could have been changed
#   by providing an askfile to pkgadd. If so, then this
#   variable below will be changed from /opt/SUNWwbsvr by pkgadd.
###############################################################################

### Get agreement to license
#####################################################################
if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
  # EULA
  if [ -f "$BASEDIR/LICENSE.txt" ]; then
    LIC_FILE="$BASEDIR/LICENSE.txt"
  elif [ -f "$BASEDIR/setup/LICENSE.txt" ]; then
    LIC_FILE="$BASEDIR/setup/LICENSE.txt"
  else
    $WS_echo "WARNING: Unable to find the LICENSE FILE in this current installation."
  fi
  if [ -n "$LIC_FILE" ]; then
    if tty > /dev/null; then
      more $LIC_FILE
    else
      $WS_cat $LIC_FILE
    fi
  fi
  sys_echo ""
  sys_echo "BY INSTALLING THIS SOFTWARE YOU ARE CONSENTING TO BE BOUND BY"
  sys_echo "AND ARE BECOMING A PARTY TO THIS AGREEMENT. "
  sys_echo "IF YOU DO NOT AGREE TO ALL OF THE TERMS OF THIS AGREEMENT,"
  sys_echo "PLEASE DO NOT INSTALL OR USE THIS SOFTWARE."
  sys_echo ""
  query_user "Do you want to agree with the terms of agreement and continue with installation" "terminal_mark=?" "yes" "default=no"

  if [ "$query_result" != "yes" ]; then
    $WS_echo "\nCannot continue without agreeing to LICENSE agreement."
    exit 1
  fi

  menu  \
    "$PRODUCT_NAME - Configuration Setup" \
    "Setup will now configure this '$PRODUCT_NAME'. " \
    "To accept the default (shown in brackets below), press Enter." \
    "" \
    "Note: Configuration options specific to this installation " \
    "      are contained in '$BASEDIR'. " \
    "      Make a note of this directory's location, so you can easily " \
    "      find $PRODUCT_NAME files at a later time." \
    ""
fi

###############################################################################
#------------------------------------------------------------------------------
#   Obtain information from person installing this package,
#   unless that information was provided by a given file
#------------------------------------------------------------------------------
###############################################################################
### Get full machine name
#####################################################################
if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
  FULLMACHINENAME=""
  valid=0
  while [ "$valid" = "0" ]; do
    menu \
    " $PRODUCT_NAME - Hostname Configuration" \
    " Enter the fully qualified domain name of the computer on which you are " \
    " installing this product, using the form <hostname>.<domainname>." \
    " For example: eros.airius.com" \
    ""
    sys_echo -n "Enter the hostname for this machine [$DEFAULT_HOSTNAME]: "
    read -r FULLMACHINENAME
    if [ -z "$FULLMACHINENAME" ]; then
      FULLMACHINENAME=$DEFAULT_HOSTNAME
    fi

    if validate_hostname $FULLMACHINENAME; then
      valid=1
    else
      valid=0
      pause_error \
        "" \
        "The machine name $FULLMACHINENAME does not appear valid." \
        "Please enter the hostname for this machine again." \
        ""
    fi
  done
else
  if validate_hostname $FULLMACHINENAME; then
    :
  else
    display_error \
      "" \
      " Setup cannot continue without a valid hostname." \
      " Enter a valid, fully qualified hostname and try again." \
      ""
    exit 1
  fi
fi

### Get system user & group
#####################################################################
if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
  if [ "$CURRENT_OS" = "SunOS" ]; then
    DEFAULT_SYSTEMUSER=webservd
  fi
  have_valid_user=0
  while [ "$have_valid_user" = "0" ]; do
    menu \
      "$PRODUCT_NAME - User/Group Configuration." \
      "Choose a user and group to run the user web server as. It " \
      "is recommend that this user be a non-privileged user, as " \
      "this will help to insure a secure web server configuration. " \
      ""
    display_note \
      "If you have not yet created a non-privileged user and group " \
      "for the specific task of serving up web pages, it is " \
      "recommended that you cancel configuration by typing Control-C " \
      "and restarting configuration when this task is complete. " \
      ""
    sys_echo -n "Enter a valid system user [$DEFAULT_SYSTEMUSER]: "
    read -r SYSTEMUSER
    if [ -z "$SYSTEMUSER" ]; then
      SYSTEMUSER=$DEFAULT_SYSTEMUSER
    fi 
    validate_systemuser $SYSTEMUSER
    result=$?
    if [ $result -ne 0 ]; then
      have_valid_user=0
      pause_error \
        "" \
        "The user ID $SYSTEMUSER does not currently exist." \
        "Choose another user, or create this user and start again." \
        ""
      continue
    fi
    have_valid_user=1
    have_valid_group=0
    # use $SYSTEMUSER to get a default SYSTEMGROUP
    DEFAULT_SYSTEMGROUP="`$WS_id $SYSTEMUSER | $WS_awk -F' ' '{print $2}' | $WS_cut -d'(' -f2 | $WS_cut -d')' -f1`"

    while [ "$have_valid_group" = "0" ]; do
      sys_echo ""
      sys_echo -n "Enter a valid system group [$DEFAULT_SYSTEMGROUP]: "
      read -r SYSTEMGROUP
      if [ -z "$SYSTEMGROUP" ]; then
        SYSTEMGROUP=$DEFAULT_SYSTEMGROUP
      fi 
      validate_systemgroup $SYSTEMGROUP $SYSTEMUSER
      result=$?
      if [ $result -eq 1 ]; then
        have_valid_user=0
        have_valid_group=0
        pause_error \
          "" \
          "The group $SYSTEMGROUP does not currently exist." \
          "Choose another group, or create this group and start again." \
          ""
        break
      elif [ $result -eq 2 ]; then
        have_valid_user=0
        have_valid_group=0
        pause_error \
          "" \
          "The system user $SYSTEMUSER is not in the $SYSTEMGROUP group." \
          "Choose another user, or create this user and start again." \
          ""
        break
      else
        have_valid_group=1
      fi
    done
  done
else
  if [ -z "$SYSTEMUSER" ] || [ -z "$SYSTEMGROUP" ]; then
    display_error \
      "" \
      " Setup cannot continue without a valid user/group name." \
      " Enter a valid user/group name and try again." \
      ""
    exit 1
  fi
  validate_systemuser $SYSTEMUSER
  result=$?
  if [ $result -eq 1 ]; then
    display_error \
      "The provided SYSTEMUSER variable '$SYSTEMUSER' is not " \
      "a currently existing system user." \
      "" 
    exit 1
  fi
  validate_systemgroup $SYSTEMGROUP $SYSTEMUSER
  result=$?
  if [ $result -eq 1 ]; then
    display_error \
      "The provided SYSTEMGROUP variable '$SYSTEMGROUP' is not " \
      "a currently existing system user." \
      "" 
    exit 1
  elif [ $result -eq 2 ]; then
    display_error \
      "The provided SYSTEMUSER variable '$SYSTEMUSER'" \
      "is not a member of the provided SYSTEMGROUP group '$SYSTEMGROUP'."
    exit 1
  fi
fi

### Get web server port
#####################################################################
if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
  have_valid_port=0
  while [ $have_valid_port -eq 0 ]; do
    menu \
      " $PRODUCT_NAME - Port Configuration" \
      " $PRODUCT_NAME need to listen on a port number between $DEFAULT_BASEPORT and 65535" \
      " to serve the incoming HTTP requests. " \
      ""
    sys_echo ""
    sys_echo -n " Enter your $PRODUCT_NAME server port [$DEFAULT_HTTPPORT]: "
    read -r HTTPPORT
    if [ -z "$HTTPPORT" ]; then
      HTTPPORT=$DEFAULT_HTTPPORT
    fi
    validate_serverPort $HTTPPORT
    result=$?
    if [ $result -eq 1 ]; then
      have_valid_port=0
      pause_error \
        "" \
        "Port $hTTPPORT is already in use. The setup program requires an" \
        "available port to succeed. Please choose a port that is not" \
        "currently in use. You can change the port number later using" \
        "the $PRODUCT_NAME Administration Server."
        ""
      continue
    elif [ $result -eq 2 ]; then
      have_valid_port=0
      pause_error \
        "" \
        " Setup requires that the port number be a number between $DEFAULT_BASEPORT and 65535" \
        " Please try again with a valid port number." \
        ""
      continue
    elif [ $result -eq 2 ]; then
      have_valid_port=0
      $WS_echo "Please enter a number bewteen $DEFAULT_BASEPORT and 65535."
    else
      have_valid_port=1
    fi
  done
else
  if [ -z "$HTTPPORT" ]; then
    display_error \
      "" \
      " $PRODUCT_NAME 'Web Server' port number cannot be NULL or invalid." \
      " Please enter a valid port number and try again." \
      ""
      exit 1
  fi
  validate_serverPort $HTTPPORT
  result=$?
  if [ $result -eq 1 ]; then
    display_error \
      "" \
      "The provided HTTPPORT variable '$HTTPPORT' is already in use." \
      ""
    exit 1
  elif [ $result -eq 2 ]; then
    display_error \
      "" \
      "The provided HTTPPORT variable '$HTTPPORT' is not a number bewteen $DEFAULT_BASEPORT and 65535." \
      ""
    exit 1
  fi
fi

### Get content root
#####################################################################
if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
  have_valid_docroot=0
  while [ $have_valid_docroot -eq 0 ]; do
    menu \
      " $PRODUCT_NAME - Content Root Configuration." \
      " Please enter a content root directory which you want to publish" \
      " through the web server (aka document root). " \
      ""
    display_note \
      "" \
      " If you want to choose a different location other than the default " \
      " value, then you will need to ensure that the directory exists and " \
      " that it has the correct permissions enabled so as to make the " \
      " directory web server accessible." \
      ""
    sys_echo -n "Enter a content root [$DEFAULT_CONTENTROOT]: "
    read -r CONTENTROOT
    if [ -z "$CONTENTROOT" ]; then
      have_valid_docroot=1
      CONTENTROOT=$DEFAULT_CONTENTROOT
      break
    elif [ -d "$CONTENTROOT" ]; then
      have_valid_docroot=1
    else
      have_valid_docroot=0
      pause_error "Setup cannot continue without a valid content root location specified."
      continue
    fi
  done
else
  if [ -z "$CONTENTROOT" ]; then
    display_note \
      "" \
      " WARNING: Content root location has not been specified. Defaulting to $DEFAULT_CONTENTROOT" \
      ""
    CONTENTROOT="$DEFAULT_CONTENTROOT"
  fi
fi

### Get whether to start on reboot
#####################################################################
if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
  menu \
    " $PRODUCT_NAME - Restart on boot Configuration" \
    " $PRODUCT_NAME can be configured to automatically restart after " \
    " a system reboot. To enable this feature, you will need to say " \
    " 'yes' to the below given option. " \
    ""
  display_note \
    "" \
    " If you choose 'no' here, then ${PRODUCT_NAME} will not be " \
    " automatically restarted after a system reboot." \
    ""
  query_user "Would you like the Web Server to start on system boot" "terminal_mark=:" "n" "default=y"
  user_option=$query_result
  if [ "$user_option" != "y" -a "$user_option" != "yes" ]; then
    STARTONBOOT="no"
  else
    STARTONBOOT="yes"
  fi
else
  if [ -z "$STARTONBOOT" ]; then
    display_note \
      "" \
      " The provided STARTONBOOT variable '$STARTONBOOT' does not look anything like 'yes' or 'no'." \
      " Setup will default to $DEFAULT_STARTONBOOT and continue." \
    STARTONBOOT=$DEFAULT_STARTONBOOT
  fi
  validate_yesorno $STARTONBOOT
  result=$?
  if [ $result -eq 0 ]; then
    STARTONBOOT=no
  elif [ $result -eq 1 ]; then
    STARTONBOOT=yes
  elif [ $result -eq 2 ]; then
    display_note \
      "" \
      " The provided STARTONBOOT variable '$STARTONBOOT' does not look anything like 'yes' or 'no'." \
      " Setup will default to $DEFAULT_STARTONBOOT and continue." \
      ""
    STARTONBOOT=$DEFAULT_STARTONBOOT
  fi
fi

### Get admin system user
#####################################################################
if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
  have_valid_user=0
  while [ "$have_valid_user" = "0" ]; do
    menu \
      " $PRODUCT_NAME - Administration Server User/Group Configuration" \
      " The $PRODUCT_NAME's Administration Server configuration " \
      " is separate from other web servers running on the system " \
      " and should not be confused with the Mission Control " \
      " 'Admin' Server." \
      "" \
      " The Administration Server is used to manage the configurations " \
      " of user web server instances." \
      ""
    display_note \
      "" \
      " It is highly recommended that the Web Server Administration Server run with" \
      " a different user id than those used by other web servers on the machine." \
      " Running the Administration Server as root will allow the server to start " \
      " and stop other web server instances." \
      ""
    sys_echo -n "Enter a valid system user for the Administration Server [$DEFAULT_ADMIN_SYSUSER]: "
    read -r ADMINSYSUSER
    if [ -z "$ADMINSYSUSER" ]; then
      ADMINSYSUSER=$DEFAULT_ADMIN_SYSUSER
    fi
    validate_systemuser $ADMINSYSUSER
    result=$?
    if [ $result -eq 1 ]; then
      have_valid_user=0
      pause_error \
        "" \
        "The user ID $ADMINSYSUSER does not currently exist." \
        "Choose another user, or create this user and start again." \
        ""
        continue
    fi
    have_valid_user=1
    ## FIX ME: 
    ## GROUP INFO NEEDS TO BE ADDED.
  done
else
  if [ -z "$ADMINSYSUSER" ]; then
    display_error \
      "" \
      " Setup cannot continue without a valid user/group name." \
      " to run the administration server. " \
      " Enter a valid user/group name and try again." \
      ""
    exit 1
  fi
  validate_systemuser $ADMINSYSUSER
  result=$?
  if [ $result -eq 1 ]; then
    display_error \
      "The provided ADMINSYSUSER variable '$ADMINSYSUSER'"
      "is not a currently existing system user."
    exit 1
  fi
fi

### Get admin server username & password
#####################################################################
if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
  menu \
    "$PRODUCT_NAME - Administration User/Password Configuration." \
    " The Administration Server requires its own administrative user name" \
    " and password for web browser access. "\
    ""
  display_note \
    "" \
    " When you access the Administration Server GUI, it will prompt you " \
    " for this administrative user name and password." \
    ""
  sys_echo -n "Administration Server User Name [$DEFAULT_ADMIN_NAME]: "
  read -r ADMINNAME
  if [ -z "$ADMINNAME" ]; then
    ADMINNAME=$DEFAULT_ADMIN_NAME
  fi

  pass_match=0
  while [ $pass_match -eq 0 ]; do
    $WS_stty -echo
    sys_echo -n "Enter your Administration Server Password : "
    read -r ADMINPASS1
    sys_echo ""
    sys_echo -n "Enter (again) your Administration Server Password : "
    read -r ADMINPASS2
    $WS_stty echo
    sys_echo ""

    if [ x"$ADMINPASS1" = x"$ADMINPASS2" -a ${ADMINPASS1:-x} != "x" ]; then
      ADMINPASSWORD=$ADMINPASS1
      pass_match=1
    else
      if [ ${ADMINPASS1:-x} = "x" ]; then
        pause_error "Password cannot be blank. Please enter the password again."
      else
        pause_error "Passwords do not match. Please enter the password again."
      fi
    fi
  done
fi

### Get admin server port
#####################################################################
if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
  have_valid_admin_port=0
  while [ $have_valid_admin_port -eq 0 ]; do
    menu \
      " $PRODUCT_NAME - Administration Port Configuration" \
      " The $PRODUCT_NAME's Administration Server also listens to a different " \
      " port (with restricted access). Pick a port number between $DEFAULT_BASEPORT and 65535" \
      " upon which your Administration Server will listen to. " \
      ""
    display_note \
      "" \
      " It must be different than the Mission Control Admin Port and your web server port." \
      ""
    sys_echo -n " Enter your Administration Server Port [$DEFAULT_ADMIN_PORT]: "
    read -r ADMINPORT
    if [ -z "$ADMINPORT" ]; then
      ADMINPORT=$DEFAULT_ADMIN_PORT
    fi
    # Now, validate whether this port is a valid port or not.
    if [ x"$ADMINPORT" = x"$HTTPPORT" ]; then
      pause_error \
      "" \
      "Port:$ADMINPORT has been already used by this installation," \
      "Please try again by choosing a different port." \
      ""
      have_valid_admin_port=0
      continue
    fi
    # Continue, with more validation of the port.
    validate_serverPort $ADMINPORT
    result=$?
    if [ $result -eq 1 ]; then
      have_valid_admin_port=0
      pause_error \
        "" \
        "Port $ADMINPORT is already in use. The setup program requires an" \
        "available port to succeed. Please choose a port that is not" \
        "currently in use. You can change the port number later using" \
        "the Administration Server." \
        ""
      continue
    elif [ $result -eq 2 ]; then
      have_valid_admin_port=0
      pause_error \
        "" \
        " Setup requires that the port number be a number between $DEFAULT_BASEPORT and 65535" \
        " Please try again with a valid port number." \
        ""
      continue
    else
      have_valid_admin_port=1
    fi
  done
else
  if [ -z "$ADMINPORT" ]; then
    display_error \
      "" \
      " Administration server port number cannot be NULL or invalid." \
      " Please enter a valid Administration port number and try again." \
      ""
      exit 1
  fi
  validate_serverPort $ADMINPORT
  result=$?
  if [ $result -eq 1 ]; then
    display_error \
      "" \
      "The provided ADMINPORT variable '$ADMINPORT' is already in use." \
      ""
    exit 1
  elif [ $result -eq 2 ]; then
    display_error \
      "" \
      "The provided ADMINPORT variable '$ADMINPORT' is not a number bewteen $DEFAULT_BASEPORT and 65535." \
      ""
    exit 1
  fi
fi

###############################################################################
#------------------------------------------------------------------------------
#   Prepare files for SDK based configuration and then call setup
#------------------------------------------------------------------------------
###############################################################################

#------------------------------------------------------------
# Make sure that setup will install to $BASEDIR
#------------------------------------------------------------
$WS_touch -f $BASEDIR/.suitespot
$WS_chmod 644 $BASEDIR/.suitespot

#------------------------------------------------------------
# Create a new setup.inf file
#------------------------------------------------------------
$WS_mv -f $SETUP_INF_FILE $SETUP_INF_FILE_TEMP
$WS_echo "
#
# Sun ONE Web Server Package Information File
#

[General]
Name          = ${PRODUCT_NAME}
Vendor        = Sun Microsystems, Inc.
Description   = ${PRODUCT_NAME} Installation
Version       = 6.1

Components    = WebServer, Cleanup
Mode          = ALLMODES
SecurityCheck = False
RequireDomain = False
pkgadd        = True

InstallType             = 2
DefaultInstallDirectory = $BASEDIR
ServerRoot              = $BASEDIR
FullMachineName         = $FULLMACHINENAME
SuiteSpotUserID         = $SYSTEMUSER
SuitespotGroup          = $SYSTEMGROUP

# Package Contents
[WebServer]
############
ComponentInfoFile   = WebServer/WebServer.inf
CompVersions        = 2:2:1:1:0:
Components          = $DEFAULT_COMPONENTS
Upgrade             = False
############
HttpSysUser         = $SYSTEMUSER
HttpPort            = $HTTPPORT
HttpDocRoot         = $CONTENTROOT
StartOnBoot         = $STARTONBOOT
############
AdminName           = $ADMINNAME
AdminSysUser        = $ADMINSYSUSER
AdminPort           = $ADMINPORT
############
USE_JDK             = $DEFAULT_JDK_SUPPORT
JDK_DIR             = $DEFAULT_JDK_DIR
############
" >| ${SETUP_INF_FILE}

if [ x"$INTERACTIVE_MODE" = x"yes" ]; then
    echo "
    AdminPassword       = $ADMINPASSWORD
    " >> ${SETUP_INF_FILE}
else
    $WS_cat $ADMINPASSWORD_FILE >> $SETUP_INF_FILE
fi

#------------------------------------------------------------
# Update the Webserver.inf file for each supported platform.
#------------------------------------------------------------
if [ -f "$WEBSERVER_INF_FILE" ]; then
  :
else
  sys_echo "Error: Unable to locate the '$WEBSERVER_INF_FILE' file."
  exit 1
fi

$WS_mv -f $WEBSERVER_INF_FILE $WEBSERVER_INF_FILE_TEMP

$WS_sed "s/Components=.*/Components=$DEFAULT_COMPONENTS/" $WEBSERVER_INF_FILE_TEMP | $WS_sed "s/Archive=.*/#&/" >| $WEBSERVER_INF_FILE
if [ $? -eq 0 ]; then
  :
else
  display_error \
    "Unable to successfully generate the '$WEBSERVER_INF_FILE'. " \
    "Information on the failure may be found in $BASEDIR/setup/setup.log" \
    "or in the error messages above." \
    ""
  exit 1
fi

#------------------------------------------------------------
# Now, we are all set to go, silently run setup
#------------------------------------------------------------
$WS_echo "Preparing Web Server data..."

if [ x"$INTERACTIVE_MODE" != x"yes" ]; then
    password=`$WS_cat $ADMINPASSWORD_FILE | $WS_cut -d "=" -f 2`
    if [ -z "$password" ]; then
	    display_error \
	    "CAUTION" \
	    "The $PRODUCT_NAME Admin Password isn't specified in $WS_ASKFILE."
     	exit 1
    fi
fi

$BASEDIR/setup/setup -s -f $SETUP_INF_FILE
result=$?

# Did install go smoothly?
if [ $result -ne 0 ]; then
  display_error \
    "CAUTION" \
    "The $PRODUCT_NAME configuration did not complete successfully." \
    "Information on the failure may be found in $BASEDIR/setup/setup.log" \
    "or in the error messages above." \
    ""
  display_note \
    "The setup.inf file may contain Admin Server passwords," \
    "so be sure to delete it or protect it after setup succeeeds." \
    ""
  $WS_chmod 400 $SETUP_INF_FILE
  exit 1
else
  display \
    "$PRODUCT_NAME configuration setup completed sucessfully!. " \
    " Go to $BASEDIR and run \"startconsole\" to start managing the Web Server." \
    ""
  $WS_rm -f $SETUP_INF_FILE
  $WS_mv -f $SETUP_INF_FILE_TEMP $SETUP_INF_FILE
  $WS_rm -f $WEBSERVER_INF_FILE
  $WS_mv -f $WEBSERVER_INF_FILE_TEMP $WEBSERVER_INF_FILE
fi

sys_echo "Thanks for choosing ${PRODUCT_NAME}. "
exit 0
