#!/bin/false  # Must only be sourced in by utconfig or M20SRAS
#
# ident "@(#)sras_config.ksh	1.34 05/06/28 SMI"
#
# Copyright 1999-2005 Sun Microsystems, Inc.  All rights reserved.
# Use is subject to license terms.
#
# NOTE: the following variables must be set by utconfig or M20SRAS
#	before invoking any functions in this file.
#
# G_MEDIA_DIR	: pathname of the install directory on the media (CD,...)
#		  used to execute utprodinfo
#

#
# Platform dependencies set here
#
__AWK=$(whence nawk)
if [[ -z $__AWK ]] ; then
  __AWK=$(whence gawk)
  if [[ -z $__AWK ]] ; then
      HttpFatal "No recognized awk implementation found on this host"
  fi
fi

# Set the specified key in ${UT_ETC_DIR}/utadmin.conf
# If key not found, it is added at end.
SetUtAdminKey() {

  typeset key=$1
  typeset value=$2

  CreateBeforeFile ${UT_ETC_DIR}/utadmin.conf

  $__AWK -F= '
    BEGIN {
      foundkey = 0
    }
    /^'"$key"'/ {
      print "'"$key"'   = '"$value"'"
      foundkey = 1
      next
    }
    {
      print $0;
    }
    END {
      if (foundkey == 0) {
        print "'"$key"'	= '"$value"'"
      }
    }
  ' ${UT_ETC_DIR}/utadmin.conf >$TMP_FILE


  ReplaceFile ${UT_ETC_DIR}/utadmin.conf $TMP_FILE

  chgrp utadmin ${UT_ETC_DIR}/utadmin.conf
  chmod a+r ${UT_ETC_DIR}/utadmin.conf
}

#
# SRASVersion()
#
# Description:
#     Checks the version of SRAS installed. 
#
# Parameters:
#    
#
# Globals used:
#
SRASVersion() {
  typeset -r pkg="SUNWutws"

  $G_MEDIA_DIR/utprodinfo -t installed $pkg || return 1
  SRAS_INSTALLED_VERSION="$($G_MEDIA_DIR/utprodinfo -p $pkg VERSION)"

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


############
# Reviewer note:
# This following functions are copied directly from utconfig.
# No aspect has been changed other than loaction variables.
#
EnglishDocsInstalled() {
  $G_MEDIA_DIR/utprodinfo -t installed SUNWeutdo
  return $?
}

JapaneseDocsInstalled() {
  $G_MEDIA_DIR/utprodinfo -t installed SUNWjutdo
  return $?
}

SRASInstalled() {
  $G_MEDIA_DIR/utprodinfo -t installed SUNWutws
  return $?
}

SSLInstalled() {
  $G_MEDIA_DIR/utprodinfo -t installed SUNWutss
  if [[ $? -ne 0 ]]; then
    return $?
  fi
  $G_MEDIA_DIR/utprodinfo -t installed SUNWutssd
  return $?
}

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

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

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

  # Match this with running webserver instances

  if [[ -n $HTTP_CFG && -f $HTTP_CFG ]]; then
    UT_PORT=$($__AWK '$1~"port" { print $2 }' $HTTP_CFG)
    SSLENABLE=$($__AWK '$1~"ssl_enable" { print $2 }' $HTTP_CFG)
     UTADMIN_MATCH=$($UT_HTTP_BIN/htserver list |\
           $__AWK -F: -v CFG="$HTTP_CFG" \
          '$1~"Config file" && CFG~substr($2,3) { print $2 }')

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

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

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

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

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

     # Grab the current remote admin

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

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

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

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

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

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

}

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

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

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

DeleteUTEntry() {
  sed '
    /^# SUNWut begin/,/^# SUNWut end/d
  ' $1

  return $?
}

ReplaceFile() {
  typeset STATUS=0

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


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

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

  return $STATUS
}

SetupCgiTokens() {
  mkdir -p -m 770 $TOKEN_DIR
  chgrp $UTADMIN_GROUP $TOKEN_DIR
  EditCgiTokensCronEntry add
  return $?
}

TakedownCgiTokens() {
  rm -rf $TOKEN_DIR
  EditCgiTokensCronEntry delete
  return $?
}

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

CreateUTTempDir() {
  

  if [[ ! -d $TMP_DIR_PATH ]]; then
    mkdir -m 770 -p $TMP_DIR_PATH
  fi
  if [[ ! -d ${TMP_DIR_PATH}/pipes ]]; then
    mkdir -m 770 -p ${TMP_DIR_PATH}/pipes
  fi

  # Add the utadmin group if it doesn't exist

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

  # XXX This coupling needs to be reviewed when configuration is
  # adapted to framework. The group check needs to be included
  # both at SRAS configuration time and following configuration
  # of any web admin related area. Both can happen independently.
  if [[ -d /var/opt/SUNWut/kiosk ]]; then
    # Only attempt group change if kiosk is configured.
    chgrp -R $UTADMIN_GROUP /var/opt/SUNWut/kiosk
  fi
}

SetupCgiNodes() {

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

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

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

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

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

}

ConfigRemoteAdmin() {

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

   if [[ "${REMOTE}" == "yes" ]] then
       REMOTE_ENABLE="+"
   fi
}

PrintWarningMessage() {
    print "\nWarning: if you choose to configure Apache, the existing" \
	  "\nApache configuration file will be over-written.  If this server" \
	  "\nis presently configured as a Webserver and you want to preserve" \
	  "\nyour current configuration, you must answer \"NO\" and merge the" \
	  "\nconfiguration file manually by following the instructions in the" \
	  "\nAdministration Guide on how to configure the Apache server."
}


#
# PromptForHttpParameters()
#
# Return Values:
# 0 - Use user prompted values and apply the config to Apache installation.
# 1 - Use user prompted values but do not apply to Apache.
# 2 - Use existing config and apply to Apache.
# 3 - Use existing config but do not apply to Apache.
# 4 - Do not config.
# 5 - Error.
#

PromptForHttpParameters() {
        typeset STATUS=0
        SKIP_HTTP=false

        # Only prompt Apache config if not autoconfigure
        if ! $FORCE; then
	    #Retrieve current webserver settings
	    InitHttpVars
	    HttpInfo $HTTPTMP

	    if ReplyIsYes "\nConfigure Sun Ray Web Administration?" ; then
		CONFIG_APACHE=true

		# Normal configuration - use prompted parameters and apply to Apache.
		STATUS=0
		if [[ $APACHE_INSTALLED == "none" ]]; then
                        print "\nWarning: Apache is not installed on this system." \
                              "\nConfiguration parameters will be stored in the file" \
                              "\n${APACHETMPCFG}.  Please refer to the Installation Guide to" \
			      "\ncomplete configuration of Apache."

			# Do not apply configuration to Apache.
			STATUS=1
		else
			if [[ $APACHE_INSTALLED == "both" ]]; then
				if [[ $OS == "Linux" ]]; then
					if ! ReplyIsYes "\nThere is an instance of Apache detected in both" \
				      	      "\n/etc/httpd and /usr/apache.  The default is /etc/httpd." \
				      	      "\nWould you like to use this instance?  Answering \"no\"" \
				      	      "\nwill configure the /usr/apache instance." ; then
						APACHETMP="$ETC_OPT_UT"/http/templates/apache.tpl
  						APACHECTL="/usr/apache/bin/apachectl"	
						APACHEDIR="/usr/apache/conf"
						APACHECFG="$APACHEDIR"/httpd.conf
					fi
					UT_LOCATION=$APACHEDIR
				fi
				print "\nThis script can configure the Apache server on this server for you."
				PrintWarningMessage
				if ReplyIsYes "\nWould you like to apply this configuration?"; then
                                	COMPLETE_CONFIG=true
				else
					COMPLETE_CONFIG=false
				fi
			else
				ApacheVersion
				print "\nAn installation of Apache Web Server version " \
				      "$APACHE_VERSION has been" \
				      "\ndetected at ${APACHEDIR%%\/conf}.  This script can configure" \
				      "\nthe Apache server on this server for you."
				PrintWarningMessage
				if ReplyIsYes "\nWould you like to configure this" \
				      "\nserver to host the Sun Ray Web Administration?" ; then
					COMPLETE_CONFIG=true
				else
					COMPLETE_CONFIG=false
				fi
			fi
			if ! $COMPLETE_CONFIG; then
				print "\nWarning: You chose not to configure Apache.  The Configuration" \
				      "\nparameters will be stored in the file ${APACHETMPCFG}." \
				      "\nPlease refer to the Administration Guide to complete configuration of Apache."
				COMPLETE_CONFIG=false

				# Do not apply configuration to Apache.
				STATUS=1
			fi
                fi

                if ApacheConfigured; then
                        if ReplyIsYes "\nA configuration of Apache already" \
                        "exists.\n" "Do you wish to preserve it?" ; then
                                SKIP_HTTP=true
				CONFIG_APACHE=false
				STATUS=4
                        fi
		elif HttpConfigured; then
			if ReplyIsYes "\nA configured template exists for" \
			"Apache.\n" "Do you wish to use this configuration?" ; then
				USE_EXISTING_HTTP_CFG=true
				SKIP_HTTP=true
				if [[ $STATUS == "0" ]]; then
                                        STATUS=2
                                else
                                        STATUS=3
                                fi
			fi
		fi
	    else
		SKIP_HTTP=true
		CONFIG_APACHE=false

		# Do not configure
		STATUS=4
	    fi

                if ! $SKIP_HTTP; then
                        if $CONFIG_APACHE; then
                                # Instance is now fixed to DEFAULT_UT_INST
                                UT_INST="$DEFAULT_UT_INST"

                                # Enquire user for Webserver port ; re-query if port is already
                                # in use.

                                PORT_OK=false
                                while ! $PORT_OK
                                do
                                        print -n "Enter port number [$DEFAULT_UT_PORT]: "
                                        read -r
                                        case "$REPLY" in
                                        "") UT_PORT="$DEFAULT_UT_PORT";;
                                        *)  UT_PORT="$REPLY";;
                                        esac
        				echo $UT_PORT >> $LOGFILE

                                        netstat -na | grep LISTEN | grep -w "$UT_PORT" >> /dev/null

                                        if [[ $? -eq 0 ]]; then
                                                print "Port specified already in use. Please re-enter"
                                                continue
                                        fi
                                        ( (( UT_PORT+=0)) ) 2>/dev/null
                                        if [[ $? -eq 0 ]]; then
                                                PORT_OK=true
                                        else
                                                print "Port specified must be numeric. Please re-enter"
                                        fi
                                done
                                SetCGI_USER
                                ConfigRemoteAdmin
                        fi
                fi
        fi
	return $STATUS
}

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

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

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

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

        if ! $USE_EXISTING_HTTP_CFG ; then
		# This resets the HTTPCFG file.
                UpdateHttpCfg $HTTPCFG
		ConfigApacheTempl
                if [[ $APACHE_INSTALLED == "none" ]]; then
                        print "\nThe Admin GUI has not been configured." \
                        "\nYour parameters have been stored in a" \
                        "\ntemporary file."
                fi
	else
		ConfigApacheTempl
        fi

	mkdir -p $UT_INST_SITE/cgi-bin

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

	SymLinkForSure $UTA_BASEDIR/lib/locale $UT_INST_SITE/public
	CreateUTTempDir
	SetupCgiTokens

	if [[ $APACHE_INSTALLED != "none" && $COMPLETE_CONFIG == "true" ]]; then
		SetUtAdminKey admin.http.cfile $APACHECFG
		mv -f $APACHECFG "$APACHECFG".sunray 2>/dev/null 
		cp $APACHETMPCFG $APACHECFG
		SetAutoStart
		$APACHECTL restart
	else
		SetUtAdminKey admin.http.cfile ""
	fi

        return $STATUS
}

SetAutoStart()
{
	if [[ -f /etc/opt/SUNWut/http/auto.start ]]; then
		rm -f /etc/opt/SUNWut/http/auto.start
	fi
	print ${APACHECTL} > /etc/opt/SUNWut/http/auto.start
}

RemoveAutoStart()
{
	rm -f /etc/opt/SUNWut/http/auto.start
}

UpdateHttpCfg()
{
        file=$1
        SetApacheKey "Port" "$UT_PORT" $file
        SetApacheKey "User" "$CGI_USER" $file
        SetApacheKey "Group" "$UTADMIN_GROUP" $file
        UT_HOSTNAME=`hostname`
        SetApacheKey "ServerName" "$UT_HOSTNAME" $file
        SetApacheKey "RemoteAdmin" "$REMOTE" $file
	SetApacheKey "ApacheDir" "$UT_LOCATION" $file
}

InitHttpVars() {
        UT_ADMIN_WEB_S="Apache Web Server"
        DEFAULT_UT_INST="utadmin"
        DEFAULT_UT_PORT="1660"
        DEFAULT_CGI_USER="utwww"
	DEFAULT_HOSTNAME="localhost"

        UT_INST_SITE=$UT_HTTP_VAR/docroot

        UT_INST="${DEFAULT_UT_INST}"
        UT_PORT="${DEFAULT_UT_PORT}"
        CGI_USER="${DEFAULT_CGI_USER}"
	UT_HOSTNAME="${DEFAULT_HOSTNAME}"
	UT_LOCATION=""

        TOKEN_DIR="${VAR_OPT_UT}/cgitokens"

        REMOTE_ENABLE="-"
        REMOTE="no"

        USE_EXISTING_HTTP_CFG=false
	COMPLETE_CONFIG=true

        return 0
}

HttpInfo()
{
	CFG=$1
        if [[ ! -f $CFG ]]; then
                HttpFatal "$CFG does not exist."
        fi
        if [[ ! -f $APACHETMP ]]; then
                HttpFatal "Missing template file $APACHETMP."
        fi

        # Grab the port number
        UT_PORT=$($__AWK '$1~"Port" { print $2 }' $CFG)

        REMOTE=$($__AWK '$1~"RemoteAdmin" { print $2 }' $CFG)

	UT_LOCATION=$($__AWK '$1~"ApacheDir" { print $2 }' $CFG)

	UT_HOSTNAME=`hostname`

        # Grab the cgi user id
        CGI_USER=$($__AWK '$1~/^'"User"'/ {
        if (length($1) == 4) {
                print $2
        }
        }' $CFG)
}

UnconfigHttp()
{
	if [[ $APACHE_INSTALLED != "none" ]]; then
		$APACHECTL stop 2>/dev/null
	fi

        TakedownCgiTokens

	if [[ -f $HTTPCFG ]]; then
        	# Grab the cgi user id
        	CGI=$($__AWK '$1~/^'"User"'/ {
		if (length($1) == 4) {
			print $2
		}
        	}' $HTTPCFG)

		print "\nDeleting user account for '$CGI' ..."

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

	if [[ -f ${UT_ETC_DIR}/utadmin.conf ]]; then    
                SetUtAdminKey admin.http.cfile ""
        fi

	rm -rf $UT_HTTP_VAR/docroot

        print "\nDeleting UNIX group $UTADMIN_GROUP ..."
        groupdel $UTADMIN_GROUP

        rm -f $UT_INST_SITE/cgi-bin/admincgi
        rm -f $UT_INST_SITE/cgi-bin/desktop
        rm -f $UT_INST_SITE/cgi-bin/gstatus
        rm -f $UT_INST_SITE/cgi-bin/log
        rm -f $UT_INST_SITE/cgi-bin/main
        rm -f $UT_INST_SITE/cgi-bin/nav
        rm -f $UT_INST_SITE/cgi-bin/status
        rm -f $UT_INST_SITE/cgi-bin/smartcard
        rm -f $UT_INST_SITE/cgi-bin/start
        rm -f $UT_INST_SITE/cgi-bin/user
        rm -f $UT_INST_SITE/cgi-bin/mhstatus
	rm -rf ${TMP_DIR_PATH}/pipes

        if ApacheConfigured;
        then
                rm -f $APACHECFG
                mv -f "$APACHECFG".sunray $APACHECFG 2>/dev/null 
        fi

	RemoveAutoStart

	rm -f $APACHETMPCFG
	if ! $USE_EXISTING_HTTP_CFG ; then
        	rm -f $HTTPCFG
	fi
}

UnconfigSWS() {
  typeset STATUS=0

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

  $UT_HTTP_BIN/htserver stop $UT_INST 2>/dev/null

  TakedownCgiTokens

  $UT_HTTP_BIN/htserver delete $UT_INST 2>/dev/null

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

  rm -rf $UT_HTTP_VAR/$UT_INST
  rm -f $UT_HTTP_ETC/$UT_INST.httpd.conf

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

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

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

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

  return $STATUS
}

UnconfigOldSWS() {
  typeset STATUS=0

  /usr/bin/htserver stop $UT_INST 2>/dev/null

  /usr/bin/htserver delete $UT_INST 2>/dev/null

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

  #
  # remove SunRay related entries from the configuration files
  #

	ed - /etc/http/${HTTP_INST_FILE} <<-! 2>/dev/null 1>&2
	g/^$UT_INST/d
	.
	w
	q
	!

  return $STATUS
}

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

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

Please consult the Installation & Configuration Guide.

!
}

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

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

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

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

### Apache Configuration functions

# Given a key, value, and file replace the value
# associated with the given key with the given
# value.
SetApacheKey() {

        typeset key=$1
        typeset value=$2
        typeset file=$3

        $__AWK -F= '
        BEGIN {
                foundkey = 0
        }
        /^[     ]*'"$key"'/ {
                print "'"$key"' '"$value"'"
                foundkey = 1
        next
        }
        {
                print $0;
        }
        END {
        if (foundkey == 0) {
                print "'"$key"' '"$value"'"
        }
        }
        ' $file >$TMP_FILE

        rm $file
        mv $TMP_FILE $file
}

ConfigApacheTempl()
{
        cp $APACHETMP $APACHETMPCFG
        APACHE_PORT=$($__AWK '$1~"Port" { print $2 }' $HTTPCFG)
        APACHE_USER=$($__AWK '$1~"User" { print $2 }' $HTTPCFG)
        APACHE_GROUP=$($__AWK '$1~"Group" { print $2 }' $HTTPCFG)
        APACHE_HOST=$($__AWK '$1~"ServerName" { print $2 }' $HTTPCFG)
        APACHE_REMOTE=$($__AWK '$1~"RemoteAdmin" { print $2 }' $HTTPCFG)
        SetApacheKey "Listen" "$APACHE_PORT" $APACHETMPCFG
        SetApacheKey "User" "$APACHE_USER" $APACHETMPCFG
        SetApacheKey "Group" "$APACHE_GROUP" $APACHETMPCFG
        SetApacheKey "ServerName" "$APACHE_HOST" $APACHETMPCFG
        if [[ "${APACHE_REMOTE}" == "yes" ]] then
                SetApacheKey "Allow from" "all" $APACHETMPCFG
        else
                SetApacheKey "Allow from" "$APACHE_HOST" $APACHETMPCFG
        fi
}

ApacheVersion()
{
	HTTPD_SCRIPT=/usr/apache/bin/httpd
	OS=`/bin/uname -s`
	if [[ $OS == "Linux" ]]; then
		if [[ -f /etc/httpd/conf/magic || -f /etc/httpd/magic ]]; then
			HTTPD_SCRIPT=/usr/sbin/httpd
		fi
	fi

        if [[ -f $HTTPD_SCRIPT ]]; then
                APACHE_VERSION=$($HTTPD_SCRIPT -v |
                $__AWK '
                $2 == "version:" {
                        print $3
                }
                ' -)
                APACHE_VERSION=${APACHE_VERSION#*/}
                APACHE_VERSION=${APACHE_VERSION%.*}
                if [[ $APACHE_VERSION != "1.3" && $APACHE_VERSION != "2.0" ]]; then
                        print -u2 "Warning: Invalid version of Apache.  Must be 1.3 or 2.0."
                fi
        else
                APACHE_VERSION="Not installed"
        fi
}

ApacheConfigured()
{
	if [[ -z $APACHECFG ]]; then
		return 1
	fi
	grep "#SRApacheConfig" $APACHECFG 2>/dev/null 1>&2
	return $?
}

ApacheInstalled()
{
	OS=`/bin/uname -s`

	case "$OS" in
        	SunOS)      
		BUNDLED_MAGIC=/etc/apache/magic
		;;
		Linux)
		if [[ -f /etc/httpd/conf/magic ]]; then
			BUNDLED_MAGIC=/etc/httpd/conf/magic
		elif [[ -f /etc/httpd/magic ]]; then
			BUNDLED_MAGIC=/etc/httpd/magic
		fi
		;;
	esac

	if [[ -f $BUNDLED_MAGIC && -f /usr/apache/conf/magic ]]; then
		APACHE_INSTALLED="both"	
	# the -k in the check if for handling the bundled RedHat Apache case.
	elif [[ -f ${APACHECTL} ]];
        then
		APACHE_INSTALLED="one"
		return
	else
		APACHE_INSTALLED="none"
	fi
}

HttpConfigured()
{
	if [[ -f $HTTPCFG ]];
	then
		return 0
	fi
	return 1
}

# Authoritative test to ensure that there is configuration to preserve
# Note: 1.0 does not have this entry, however, no preserve of configuration
# is supported from 1.0.
SRASConfigured(){

  if grep 'utadmin.httpd.conf' ${UT_ETC_DIR}/utadmin.conf 1>&- 2>&-; then
    return 0
  else
    return 1
  fi
}

# Sets all of the necessary configuration and executable paths based on the OS and
# what versions of Apache are installed.  Returns 0 when there is only Apache installed
# and 1 when there are two.
SetPlatformSpecs()
{
  STATUS=0
  APACHETMP="$ETC_OPT_UT"/http/templates/apache.tpl
  APACHECTL="/usr/apache/bin/apachectl"
  OS=`/bin/uname -s`
	
  case "$OS" in
        SunOS)      # Define Solaris specific parameters

        # On a normal Apache install, if you install the packages into
        # /usr/apache, the configuration files will exist in /usr/apache/conf.
        # However, the Apache bundled with Solaris puts the config files into
        # /etc/apache.  

        if [[ -f /etc/apache/magic && -f /usr/apache/conf/magic ]]; then
		STATUS=1
        fi
	if [[ -f /usr/apache/conf/magic ]]; then
                APACHEDIR="/usr/apache/conf"
	
	# Handle the case for Apache bundled with Solaris.
        elif [[ -f /etc/apache/magic ]]; then
                APACHEDIR="/etc/apache"
                APACHETMP="$ETC_OPT_UT"/http/templates/apache.tpl.solaris
        fi
	;;
        Linux)

	# On a normal Apache install, if you install the packages into
        # /usr/apache, the configuration files will exist in /usr/apache/conf.
        # However, the Apache bundled with RedHat puts the config files into
        # /etc/httpd/conf and SuSE puts it into /etc/httpd.

	# Check for Apache in /usr/apache/conf.

	if [[ -f /usr/apache/conf/magic ]]; then
                APACHEDIR="/usr/apache/conf"
	fi

	# Now see if there is a bundled version.

	if [[ -d /etc/httpd ]]; then
		# Handle the case for Apache bundled with RedHat.
        	if [[ -f /etc/httpd/conf/magic ]]; then
                	APACHEDIR="/etc/httpd/conf"
                	APACHETMP="$ETC_OPT_UT"/http/templates/apache.tpl.redhat
                	APACHECTL="/etc/init.d/httpd"

		# Handle the case for Apache bundled with SuSE.
		elif [[ -f /etc/httpd/magic ]]; then
			APACHEDIR="/etc/httpd"
			APACHETMP="$ETC_OPT_UT"/http/templates/apache.tpl.suse
			APACHECTL="/etc/init.d/apache"
		fi

		# If both exist then check to see which one we should be using 
		# if /etc/opt/SUNWut/http/http.conf exists.  Otherwise default to
		# the bundled version.
        	if [[ -f $APACHEDIR/magic && -f /usr/apache/conf/magic ]]; then
			if [[ -f $HTTPCFG ]]; then
				HttpInfo $HTTPCFG
				if [[ $UT_LOCATION == "/usr/apache/conf" ]]; then
					APACHEDIR="/usr/apache/conf"
					APACHETMP="$ETC_OPT_UT"/http/templates/apache.tpl
  					APACHECTL="/usr/apache/bin/apachectl"					
				fi
			fi
                	STATUS=1
        	fi
	fi
        ;;
  esac
  if [[ -n $APACHEDIR ]]; then
  	APACHECFG="$APACHEDIR"/httpd.conf
  fi
  ApacheInstalled

  return $STATUS
}

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