#!/bin/false  # Must only be sourced in by utconfig or M20SRAS
#
# ident "@(#)sras_config.ksh	1.7 02/11/14 SMI"
#
# Copyright 2001-2002 Sun Microsystems, Inc.  All rights reserved.
#

# 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

  nawk -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"

  pkginfo -q $pkg || return 1
  SRAS_INSTALLED_VERSION="$(pkgparam $pkg VERSION 2>&-)"

  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() {
  pkginfo -q SUNWeutdo
  return $?
}

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

SRASInstalled() {
  pkginfo -q SUNWutws
  return $?
}

SSLInstalled() {
  pkginfo -q SUNWutss 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=$(nawk -F= '$1~"admin.http.cfile" {print $2}' $UTCONF_FILE)
      HTTP_CFG=$(echo $HTTP_CFG | sed -e 's/    //g')
   fi


  # Match this with running webserver instances

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

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

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

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

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

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

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

     # Grab the current remote admin

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

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

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

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

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

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

}

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

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

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

}

# Deprecated as Instance no longer prompted.
SetUT_INST() {
  typeset STATUS=0

  DEFAULT_UT_INST="utadmin"

  UT_INST_OK=false

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

            ;;
     esac
  done


  print ""

  return $STATUS
}

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
}

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

  CreateBeforeFile $CONF_FILE

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

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

  ReplaceFile $CONF_FILE $TMP_CONF_FILE

  return $STATUS
}

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

  DestroyBeforeFile $CONF_FILE

  return $STATUS
}

PrintLocalhostEntry() {
  typeset STATUS=0

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

  return $STATUS
}

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

  CreateBeforeFile $CONF_FILE

  DeleteUTEntry $CONF_FILE >$TMP_CONF_FILE

  PrintLocalhostEntry >>$TMP_CONF_FILE

  ReplaceFile $CONF_FILE $TMP_CONF_FILE

  return $STATUS
}

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

  CreateBeforeFile $CONF_FILE

  DeleteUTEntry $CONF_FILE >$TMP_CONF_FILE

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

  ReplaceFile $CONF_FILE $TMP_CONF_FILE

  return $STATUS
}

SetupCgiNodes() {

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

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


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

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

  return $STATUS
}

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

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

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

CreateUTTempDir() {
  

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

  # Add the utadmin group if it doesn't exist

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

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

ConfigRemoteAdmin() {

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

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

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

}

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

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

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

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

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

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

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

  UpdateAdminServerPort

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

  SetupCgiNodes

  CreateBeforeDir $UT_INST_SITE/public

  SymLinkForSure $UTA_BASEDIR/lib/locale $UT_INST_SITE/public

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

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

  AppendLocalhostRestriction
  AppendCgiUser
  SetupCgiTokens

  $UT_HTTP_BIN/htserver enable $UT_INST

  $UT_HTTP_BIN/htserver start $UT_INST

  return $STATUS
}

UnconfigSWS() {
  typeset STATUS=0

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

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

  TakedownCgiTokens

  DowndateAdminServerPort

  $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

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

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

InitSWSVars() {

  UT_ADMIN_WEB_S="Sun Ray Admin Server"
  DEFAULT_UT_INST="utadmin"
  DEFAULT_UT_PORT="1660"
  DEFAULT_CGI_USER="utwww"

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

  DELETE_CGI_USER=false

  TOKEN_DIR="${VAR_OPT_UT}/cgitokens"

  REMOTE_ENABLE="-"
  REMOTE_ENABLE_S="Disabled"

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

  return 0
}


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

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

Please consult the Administrator's Guide.

!
}

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

ssl_advise_MSG() {
cat <<-!

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