#!/bin/ksh -p
#
# ident "@(#)srwa_config.ksh	1.12	11/03/10 Oracle"
#
# Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
#

#set -vx

UTDIALOG="/etc/opt/SUNWut/basedir/lib/utdialog"

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

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

function InitWebParameters {
    if [ -f ${CONFIG_FILE} ]; then
        DEFAULT_TOMCAT_PATH=`grep '^catalina.home=' ${CONFIG_FILE} | cut -f2 -d'='`
        DEFAULT_HTTP_PORT=`grep '^http.port=' ${CONFIG_FILE} | cut -f2 -d'='`
        DEFAULT_HTTPS_PORT=`grep '^https.port=' ${CONFIG_FILE} | cut -f2 -d'='`
        DEFAULT_TOMCAT_USERNAME=`grep '^process.username=' ${CONFIG_FILE} | cut -f2 -d'='`
        DEFAULT_TOMCAT_REMOTE=`grep '^remote.access=' ${CONFIG_FILE} | cut -f2 -d'='`
    fi

    if [ ! -n "${DEFAULT_TOMCAT_PATH}" ]; then
        DEFAULT_TOMCAT_PATH="/opt/apache-tomcat"
    fi
    if [ ! -n "${DEFAULT_HTTP_PORT}" ]; then
        DEFAULT_HTTP_PORT="1660"
    fi
    if [ ! -n "${DEFAULT_HTTPS_PORT}" ]; then
        DEFAULT_HTTPS_PORT="1661"
    fi
    if [ ! -n "${DEFAULT_TOMCAT_USERNAME}" ]; then
        DEFAULT_TOMCAT_USERNAME="utwww"
    fi
    if [ ! -n "${DEFAULT_TOMCAT_REMOTE}" ]; then
        DEFAULT_TOMCAT_REMOTE="127.0.0.1"
    fi
    if [ ${DEFAULT_HTTPS_PORT} -eq 0 ]; then
        DEFAULT_HTTPS_PORT=`expr ${DEFAULT_HTTP_PORT} + 1`
    fi
}

function WriteWebParameters {
    cp -f "${CONFIG_FILE}" "${CONFIG_FILE_TMP}"
    SetPropertyValue "catalina.home" "$TOMCAT_PATH"
    SetPropertyValue "http.port" "$HTTP_PORT"
    SetPropertyValue "https.port" "$HTTPS_PORT"
    SetPropertyValue "process.username" "$TOMCAT_USERNAME"
    SetPropertyValue "remote.access" "$TOMCAT_REMOTE"
}

function ResetWebParameters {
    cp -f "${CONFIG_FILE}" "${CONFIG_FILE_TMP}"
    SetPropertyValue "jre.home" "/etc/opt/SUNWut/jre"
    SetPropertyValue "catalina.home" ""
    SetPropertyValue "log.file" "/var/opt/SUNWut/log/utwebadmin.log"
    SetPropertyValue "auto.start" "false"
    SetPropertyValue "process.username" "utwww"
    SetPropertyValue "process.groupname" "utadmin"
    SetPropertyValue "https.port" "1661"
    SetPropertyValue "http.port" "1660"
    SetPropertyValue "remote.access" "127.0.0.1"
    SetPropertyValue "shutdown.port" "50505"
    mv -f "${CONFIG_FILE_TMP}" "${CONFIG_FILE}"
}

function AddUser {
    OLD_USER_COMMENT="ut admin web server cgi user"
    PROCESS_USERNAME=`grep '^process.username=' ${CONFIG_FILE} | cut -f2 -d'='`
    PROCESS_GROUPNAME=`grep '^process.groupname=' ${CONFIG_FILE} | cut -f2 -d'='`

    # delete possible 3.x old web admin user
    OLD_USERNAME=`grep "${OLD_USER_COMMENT}" /etc/passwd | cut -f1 -d':'`
    if [ -n "${OLD_USERNAME}" ]; then
        print -n "Deleting old web admin cgi user account '${OLD_USERNAME}'... "
        userdel ${OLD_USERNAME}
        print "done"
    fi

    # delete possible old web admin user
    OLD_USERNAME=`grep "${USER_COMMENT}" /etc/passwd | cut -f1 -d':'`
    if [ -n "${OLD_USERNAME}" ]; then
        if [ "${OLD_USERNAME}" != "${PROCESS_USERNAME}" ]; then
            print -n "Deleting old web admin user account '${OLD_USERNAME}'... "
            userdel ${OLD_USERNAME}
            print "done"
        fi
    fi

    # create new admin user 
    getent passwd $PROCESS_USERNAME >> /dev/null
    STATUS=$?
    if [ $STATUS -ne 0 ] ; then
        # User does not exist
        print -n "Adding user account for '$PROCESS_USERNAME' ($USER_COMMENT) ..."
        useradd -c "$USER_COMMENT" -s /bin/sh -d /tmp -g $PROCESS_GROUPNAME $PROCESS_USERNAME
        print "done" 
    else
        # User exists
        OLDGROUPS=`groups $PROCESS_USERNAME`
        HAS_GROUP="false"
        for GROUP_RUNNER in $OLDGROUPS ; do
            if [ $GROUP_RUNNER = "$PROCESS_GROUPNAME" ]; then
                HAS_GROUP="true"
            fi
        done
        if [ "$HAS_GROUP" = "false" ] ; then
            # User is not a member of the group
            USER_ENTRY=`grep "^${PROCESS_USERNAME}:" /etc/passwd` 
            if [ -n "${USER_ENTRY}" ]; then
                # User is a local user
                GROUP_ENTRY=`grep "^${PROCESS_GROUPNAME}:" /etc/group`
                if [ -n "${GROUP_ENTRY}" ]; then
                    # Group is a local group
                    print -n "Adding user account '$PROCESS_USERNAME' to group '$PROCESS_GROUPNAME'... "
                    SECONDARY_GROUPS=`echo ${OLDGROUPS} | sed -e 's/ /,/g'`
                    SECONDARY_GROUPS=`echo ${SECONDARY_GROUPS} | cut -d"," -f2- -s`
                    if [ $SECONDARY_GROUPS ] ; then
                        usermod -G ${SECONDARY_GROUPS},${PROCESS_GROUPNAME} $PROCESS_USERNAME 2>/dev/null
                    else
                        usermod -G ${PROCESS_GROUPNAME} $PROCESS_USERNAME 2>/dev/null
                    fi
                    print "done" 
                else 
                    # Group is not a local group
                    print "Error: User '$PROCESS_USERNAME' cannot be added to group '$PROCESS_GROUPNAME'."
                    print "       User '$PROCESS_USERNAME' already exists as local user and group '$PROCESS_GROUPNAME' is not a local group."
                    return $EXIT_FAILURE
                fi
            else
                # User is not a local user
                print "Error: User '$PROCESS_USERNAME' cannot be added to group '$PROCESS_GROUPNAME'."
                print "       User '$PROCESS_USERNAME' is not a local user."
                return $EXIT_FAILURE
            fi
        fi
    fi
}

function DeleteUser {
    PROCESS_USERNAME=`grep '^process.username=' ${CONFIG_FILE} | cut -f2 -d'='`

    if [ -n "${PROCESS_USERNAME}" ]; then
    
        USER_ENTRY=`grep "^${PROCESS_USERNAME}:" /etc/passwd | grep "${USER_COMMENT}"`
    
        if [ -n "${USER_ENTRY}" ]; then
            print -n "\nDeleting user account for '$PROCESS_USERNAME'... "
            userdel $PROCESS_USERNAME
            print "done"
        else
            print "\nWarning: User account not deleted." \
                  "\n         User account '$PROCESS_USERNAME' was not found in /etc/passwd."
        fi
    fi
}

function SetPropertyValue {
    sed 's|^'"${1}"'=.*|'"${1}"'='"${2}"'|' <"${CONFIG_FILE_TMP}" >/tmp/pllconfig.$$
    mv /tmp/pllconfig.$$ "${CONFIG_FILE_TMP}"
}

function IsJavaRuntimeEnvAvailable {
   JAVA_HOME=`grep '^jre.home=' ${CONFIG_FILE} | cut -f2 -d'='`
   if [ ! -n "${JAVA_HOME}" ]; then
          JAVA_HOME=$UT_ETC_OPT/jre
   fi
   if [ -d "${JAVA_HOME}" ]; then
          export JAVA_HOME
          return 0
   else 
          return 1
   fi
}

function PromptForWebParameters {
    # query tomcat path; re-query if directory does not exist

    TOMCAT_PATH_OK=false
    while ! $TOMCAT_PATH_OK
    do
	REPLY=$($UTDIALOG -D $DEFAULT_TOMCAT_PATH $UTDIALOG_OPTS \
	    utconfig.srwa.TomcatInstallDirectory)
        case "$REPLY" in
        "") TOMCAT_PATH="$DEFAULT_TOMCAT_PATH";;
        *)  TOMCAT_PATH="$REPLY";;
        esac
        
        echo $TOMCAT_PATH >> $LOGFILE

        if [[ -f ${TOMCAT_PATH}/bin/bootstrap.jar ]]; then
            TOMCAT_PATH_OK=true
        else 
            print "\nAn Apache Tomcat webserver does not exist at the given location" \
"\n(${TOMCAT_PATH}/bin/bootstrap.jar is missing)." \
"\nYou can either reenter the path or skip the configuration of the" \
"\nSun Ray Web Administration component to continue with the configuration" \
"\nof the remaining SRSS components." \
"\nIf you skip the configuration of this component then the admin GUI will not work." \
"\nYou can retry the configuration of this component later by calling" \
"\n'utconfig -w'. As a prerequisite you need to install a Tomcat webserver." \
"\nIt is available in the SRSS Image 'Supplemental/Apache_Tomcat' directory.\n"
            ENTER_SKIP_OK=false
            while ! $ENTER_SKIP_OK
            do
		REPLY=$($UTDIALOG $UTDIALOG_OPTS utconfig.srwa.ReEnterTomcatLocation)
                case "$REPLY" in
                    [rR]) ENTER_SKIP_OK=true;;
                    [sS]) return 1;; 
                esac
            done
	    # clear any potential pre-existing bad response, to force dialog with user
	    $UTDIALOG -w -c SRSS "utconfig.srwa.TomcatInstallDirectory="
        fi
    done
    
    # query HTTP port; re-query if port is already in use
    
    HTTP_PORT_OK=false
    while ! $HTTP_PORT_OK
    do
	REPLY=$($UTDIALOG -D $DEFAULT_HTTP_PORT $UTDIALOG_OPTS \
	    utconfig.srwa.HTTPPortNumber)
        case "$REPLY" in
        "") HTTP_PORT="$DEFAULT_HTTP_PORT";;
        *)  HTTP_PORT="$REPLY";;
        esac
        echo $HTTP_PORT >> $LOGFILE

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

        if [[ $? -eq 0 ]]; then
            print "\nPort specified already in use. Please re-enter.\n"
	    # clear any potential bad response
	    $UTDIALOG -w -c SRSS "utconfig.srwa.HTTPPortNumber="
            continue
        fi
        ( (( HTTP_PORT+=0)) ) 2>/dev/null
        if [[ $? -eq 0 ]]; then
            HTTP_PORT_OK=true
        else
            print "\nPort specified must be numeric. Please re-enter.\n"
	    # clear any potential bad response
	    $UTDIALOG -w -c SRSS "utconfig.srwa.HTTPPortNumber="
        fi
    done
    
    # query HTTPS port; re-query if port is already in use
    
    if ReplyYesOrNo srwa.EnableSecureConnectionsYN Y; then
        HTTPS_PORT_OK=false
        while ! $HTTPS_PORT_OK
        do
	    REPLY=$($UTDIALOG -D $DEFAULT_HTTPS_PORT $UTDIALOG_OPTS \
		utconfig.srwa.HTTPSPortNumber)
            case "$REPLY" in
            "") HTTPS_PORT="$DEFAULT_HTTPS_PORT";;
            *)  HTTPS_PORT="$REPLY";;
            esac
            echo $HTTPS_PORT >> $LOGFILE
    
            if [[ $HTTPS_PORT -eq $HTTP_PORT ]]; then
                print "\nSecure port equals HTTP port. Please re-enter.\n"
	        # clear any potential bad response
		$UTDIALOG -w -c SRSS "utconfig.srwa.HTTPSPortNumber="
                continue
            fi
            
            netstat -na | grep LISTEN | grep -w "$HTTPS_PORT" >> /dev/null
    
            if [[ $? -eq 0 ]]; then
                print "\nPort specified already in use. Please re-enter.\n"
	        # clear any potential bad response
		$UTDIALOG -w -c SRSS "utconfig.srwa.HTTPSPortNumber="
                continue
            fi
            ( (( HTTPS_PORT+=0)) ) 2>/dev/null
            if [[ $? -eq 0 ]]; then
                HTTPS_PORT_OK=true
            else
                print "\nPort specified must be numeric. Please re-enter.\n"
	        # clear any potential bad response
		$UTDIALOG -w -c SRSS "utconfig.srwa.HTTPSPortNumber="
            fi
        done
    else
        HTTPS_PORT=0;
    fi    
        
    # query run user name port
    
    TOMCAT_USERNAME_OK=false
    while ! $TOMCAT_USERNAME_OK
    do
	REPLY=$($UTDIALOG -D $DEFAULT_TOMCAT_USERNAME $UTDIALOG_OPTS \
	    utconfig.srwa.TomcatProcessUsername)
        case "$REPLY" in
        "") TOMCAT_USERNAME="$DEFAULT_TOMCAT_USERNAME" ;;
        *)  TOMCAT_USERNAME="$REPLY" ;;
        esac
        
        echo $TOMCAT_USERNAME >> $LOGFILE 
        if IsValidAlphanumeric $TOMCAT_USERNAME ; then
            PROCESS_GROUPNAME=`grep '^process.groupname=' ${CONFIG_FILE} | cut -f2 -d'='`
            USER_COMMENT="ut admin web server cgi user"
            getent passwd $TOMCAT_USERNAME >> /dev/null
            STATUS=$?
            if [ $STATUS -ne 0 ] ; then
                # User does not exist
                TOMCAT_USERNAME_OK=true
            else
                # User exists
                OLDGROUPS=`groups $TOMCAT_USERNAME`
                HAS_GROUP="false"
                for GROUP_RUNNER in $OLDGROUPS ; do
                    if [ $GROUP_RUNNER = "$PROCESS_GROUPNAME" ]; then
                        HAS_GROUP="true"
                    fi
                done
                if [ "$HAS_GROUP" = "true" ] ; then
                    TOMCAT_USERNAME_OK=true
                else
                    # User is not a member of the group
                    USER_ENTRY=`grep "^${TOMCAT_USERNAME}:" /etc/passwd` 
                    if [ -n "${USER_ENTRY}" ]; then
                        # User is a local user
                        GROUP_ENTRY=`grep "^${PROCESS_GROUPNAME}:" /etc/group`
                        if [ -n "${GROUP_ENTRY}" ]; then
                            # Group is a local group
                            TOMCAT_USERNAME_OK=true
                        else 
                            # Group is not a local group
                            print "\nUser '$TOMCAT_USERNAME' already exists as local user and is not in" \
                                  "\ngroup '$PROCESS_GROUPNAME' which is not a local group." \
                                  "\nPlease re-enter.\n"
                        fi
                    else
                        # User is not a local user
                        print "\nUser '$TOMCAT_USERNAME' is not a local user and is not in " \
                              "\ngroup '$PROCESS_GROUPNAME'. Please re-enter.\n"
                    fi
                fi
            fi
        else
            print "\nTomcat user name must be alphanumeric. Please re-enter.\n"
        fi
	if ! $TOMCAT_USERNAME_OK; then
	    # clear any potential bad response
	    $UTDIALOG -w -c SRSS "utconfig.srwa.TomcatProcessUsername="
	fi
    done
    
    # query remote admin
    
#    typeset SSL=false
    if ReplyYesOrNo srwa.EnableRemoteServerAdministrationYN N; then
        TOMCAT_REMOTE=".*"
    else
        TOMCAT_REMOTE="127.0.0.1"
    fi
}

#
# m a i n 
#


# Source the utility library
. /opt/SUNWut/lib/support_lib/config_lib

UT_ETC_OPT="/etc/opt/SUNWut"
UT_WEBADMIN_CMD="/opt/SUNWut/lib/utwebadmin"
ETC_WADMIN_CMD="/etc/init.d/utwadmin"

CONFIG_FILE="${UT_ETC_OPT}/webadmin/webadmin.conf"
CONFIG_FILE_TMP="${UT_ETC_OPT}/webadmin/webadmin.conf.tmp"

USER_COMMENT="ut admin web server user"

case "$1" in
'info')
    if [[ -f "${CONFIG_FILE_TMP}" ]]; then
        if IsJavaRuntimeEnvAvailable ; then
            CATALINA_HOME=`grep '^catalina.home=' ${CONFIG_FILE_TMP} | cut -f2 -d'='`
            CATALINA_CMD=${CATALINA_HOME}/bin/catalina.sh
            if [[ -f "${CATALINA_CMD}" ]]; then
                INFO_STRING=`${CATALINA_CMD} version | grep 'Server version' | cut -f2 -d':' | cut -c2-`
            fi
        fi
        if [ -n "${INFO_STRING}" ]; then
            print "Sun Ray Web Administration hosted at ${INFO_STRING}"
        else 
            print "Sun Ray Web Administration"
        fi
    else 
	return 1
    fi
    ;;
'display')
    if [[ -f "${CONFIG_FILE_TMP}" ]]; then
        CATALINA_HOME=`grep '^catalina.home=' ${CONFIG_FILE_TMP} | cut -f2 -d'='`
        SECURE_PORT=`grep '^https.port=' ${CONFIG_FILE_TMP} | cut -f2 -d'='`
        UNSECURE_PORT=`grep '^http.port=' ${CONFIG_FILE_TMP} | cut -f2 -d'='`
        USER_NAME=`grep '^process.username=' ${CONFIG_FILE_TMP} | cut -f2 -d'='`
        TOMCAT_REMOTE=`grep '^remote.access=' ${CONFIG_FILE_TMP} | cut -f2 -d'='`
        print "    Apache Tomcat installation directory: $CATALINA_HOME"
        print "    HTTP port number: $UNSECURE_PORT"
        if [ $SECURE_PORT -eq 0 ]; then 
            print "    HTTPS port: Disabled"
        else 
            print "    HTTPS port number: $SECURE_PORT"
        fi
        print "    Tomcat process username: $USER_NAME"
        if [ "${TOMCAT_REMOTE}" = ".*" ]; then 
            print "    Remote server administration: Enabled"
        else 
            print "    Remote server administration: Disabled"
        fi
    else 
	return 1
    fi
    ;;
'prompt')
    # preserve current UTDIALOG_OPTS, even though currently srwa_config is exec'd
    # because it seems like we should fix it to be sourced like kiosk_lib in future
    # to take better advantage of utconfig environment
    OLD_UTDIALOG_OPTS=$UTDIALOG_OPTS
    UTDIALOG_OPTS="$UTDIALOG_OPTS -c SRSS"
    if [[ $2 == "-l" ]]; then
	LOGFILE=$3
	print -- ""
	if ReplyYesOrNo srwa.ConfigureWebAdminYN N; then
	    InitWebParameters
	    if ! PromptForWebParameters; then
		    return 1
	    fi
	    WriteWebParameters
	else
	    UTDIALOG_OPTS=$OLD_UTDIALOG_OPTS
	    return 1
	fi
    else 
	UTDIALOG_OPTS=$OLD_UTDIALOG_OPTS
	return 2
    fi
    UTDIALOG_OPTS=$OLD_UTDIALOG_OPTS
    ;;
'update')
    mv -f  ${CONFIG_FILE_TMP} ${CONFIG_FILE}
    AddUser
    $UT_WEBADMIN_CMD enable
    if IsJavaRuntimeEnvAvailable ; then
        $UT_WEBADMIN_CMD restart
    fi
    ;;
'unconfig')
    $UT_WEBADMIN_CMD disable
    $ETC_WADMIN_CMD stop

    print "\nResetting configuration ..."
    DeleteUser
    ResetWebParameters
    ;;
esac

