#!/bin/sh
#  $Id: webserver.sh,v 1.6 2005/07/28 15:00:42 billwe Exp $
#  Copyright (C) 2003-2005 Sun Microsystems, Inc.
#  This software code contains proprietary information 
#  and should be treated as confidential.

# This is a generic product script used to establish an environment
# before starting/stopping a product or component.
# This script was built from shell library
#   $Id: startup.shlib,v 10.165.6.1 2006/04/03 09:51:35 billwe Exp $
# This script has to run on every platform we support.  Any suggestions
# for improvement are welcome (but must be portable!)

# Version numbers
PRODUCT_VERSION="4.2"
PRODUCT_VERSION_FULL="4.20.983"
PRODUCT_VERSION_MAJOR=4
PRODUCT_VERSION_FEATURE=2
PRODUCT_VERSION_BUG=0
PRODUCT_VERSION_BUILD=983
PRODUCT_VERSION_CAB=4,2,0,983

# Product names
PRODUCT_FULL_NAME="Sun Secure Global Desktop Software"
PRODUCT_SHORT_NAME="Secure Global Desktop"
PRODUCT_SHORT_FILENAME="Tarantella"
TSP_FULL_NAME="Sun Secure Global Desktop Security Pack"
TSP_SHORT_NAME="Security Pack"
WCP_FULL_NAME="Sun Secure Global Desktop Windows Connectivity Pack"
WCP_SHORT_NAME="Windows Connectivity Pack"
TN3270_FULL_NAME="Sun Secure Global Desktop Mainframe Connectivity Pack"
TN3270_SHORT_NAME="Mainframe Connectivity Pack"
AS400_FULL_NAME="Sun Secure Global Desktop AS/400 Connectivity Pack"
AS400_SHORT_NAME="AS/400 Connectivity Pack"
S1PSTK_FULL_NAME="Sun Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_FULL_NAME="Sun Secure Global Desktop Integration Pack for Sun ONE Portal Server"
S1PSTK_SHORT_NAME="Secure Global Desktop Channel for Sun ONE Portal Server"
S1PSIP_SHORT_NAME="Secure Global Desktop Integration Pack for Sun ONE Portal Server"

OBJECT_MGR_NAME="Object Manager"
ARRAY_MGR_NAME="Array Manager"
NATIVE_WIN16_FULL_NAME="Sun Secure Global Desktop Native Client for Windows 3.1"
NATIVE_WIN16_SHORT_NAME="Native Client for Windows 3.1"
NATIVE_WIN32_FULL_NAME="Sun Secure Global Desktop Native Client for Windows 95, 98 and NT"
NATIVE_WIN32_SHORT_NAME="Native Client for Windows 95, 98 and NT"
NATIVE_WYSE_FULL_NAME="Sun Secure Global Desktop Native Client for Wyse"
NATIVE_WYSE_SHORT_NAME="Native Client for Wyse"
NATIVE_FULL_NAME="Sun Secure Global Desktop Native Client"
NATIVE_SHORT_NAME="Native Client"
NATIVE_REGISTRY_NAME="Tarantella Native Client"
TCC_FULL_NAME="Sun Secure Global Desktop Client"
TCC_HELPER_NAME="Sun Secure Global Desktop Client Helper"
TCC_ACTIVEX_NAME="Sun Secure Global Desktop ActiveX Control"
TCC_PLUGIN_NAME="Sun Secure Global Desktop Netscape Plug-in"
T3COMPONENT_WIN_NAME="Sun Secure Global Desktop Enhancement Module for Windows"
T3COMPONENT_UNIX_NAME="Sun Secure Global Desktop Enhancement Module for UNIX/Linux"
T3COMPONENT_SHORT_UNIX_NAME="tem"
T3COMPONENT_NAME="Sun Secure Global Desktop Enhancement Module"

# Watch the length of these names: IE refuses to remove packages if
# the name is too long.
ARCHIVE_NAME_ttalw="TCC Helper, version"
ARCHIVE_NAME_asad="3.x Framework Java Archive"
#ARCHIVE_NAME_tta="3.x Java Archive"
#ARCHIVE_NAME_tta="3.x Combined Java Archive"
ARCHIVE_NAME_tta="Client, "
ARCHIVE_NAME_tsp="3.x Security Java Archive"
ARCHIVE_NAME_proxy="3.x Proxy Java Archive"

ARCHIVE_SUFFIX="F"

NS_REGKEY="java/download/com/tarantella/tta"

PRODUCT_VENDOR="Sun Microsystems, Inc."
PRODUCT_SHORT_VENDOR="Sun"

# Capabilities:
# The format for the capabilities required by the client end of a
# connection is: CAPABILITIES_protocol_type_REQUIRED="expression"

# The format for the capabilities provided by the server end of a
# connection is: CAPABILITIES_protocol_type_PROVIDED="c1 c2 ... c3"

# Asad between a webtop client and server:
CAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"

# Asad between two peer servers, or an admin tool and a server:
# 1.1 is core E3 array functionality.
# 1.2 is 3.01 array interoperability functionality.
# 2.1 is core Pisa client device mapping functionality (not a requirement)
CAPABILITIES_ASAD_PEER_REQUIRED="(1.1 || 1.2)"
CAPABILITIES_ASAD_PEER_PROVIDED="1.1 1.2 2.1"

# Client versions of server strings; same format, name prefixed by CLIENT
# Asad between a webtop client and server:
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_REQUIRED="(1.1 || 1.2)"
CLIENTCAPABILITIES_ASAD_WEBTOPCLIENT_PROVIDED="1.1 1.2"


N=""
C=""
if echo -n | grep n > /dev/null
then
  C="\c"
else
  N="-n"
fi
case "$MACHINEARCH" in
i3li*|ppli*) N="$N -e" ;;
esac
_ss_headlines="--------------------------------------------------------------------------"

u="`LANG=C LC_ALL=C id | sed 's/.*uid=\([0-9][0-9]*\).*/\1/'`"
if [ "$u" = "0" ]
then
  : # all is okay
else
  echo "You must be root to run this program"
  exit 15
fi

if [ -f $TTAMSG/common -a -f $TTAMSG/tta_webserver ]; then
  . $TTAMSG/common
  . $TTAMSG/tta_webserver
else
  echo "Unable to open message file: $TTAMSG/tta_webserver"
  exit 1
fi

GetPrivUsrGrp()
{
    cat $TTAINSTDIR/var/serverconfig/global/array.properties 2>/dev/null | awk -F= \
	'BEGIN { u="ttasys"; wu="ttaserv"; g="ttaserv" }
	$1 == "tarantella.config.array.privilegeduser" { u = $2 }
	$1 == "tarantella.config.array.webserveruser" { wu = $2 }
	$1 == "tarantella.config.array.privilegedgroup" { g = $2 }
	END { print u " " wu " " g }'
}
_privusrgrp=`GetPrivUsrGrp`
privusr=`expr "$_privusrgrp" : '\([^ ]*\) .*'`
webservusr=`expr "$_privusrgrp" : '.* \([^ ]*\) .*'`
privgrp=`expr "$_privusrgrp" : '.* \([^ ]*\)$'`


# We need this on SuSE SLES 9 (and it doesn't do any harm on other platforms)
CATALINA_OPTS=""
CATALINA_OPTS="${CATALINA_OPTS}
-Djava.net.preferIPv4Stack=true"

export CATALINA_OPTS

case $trace in x|X) set -x ;; esac

# Where are they?
webdir=$TTAINSTDIR/webserver
apachedir=$webdir/apache
tomcatdir=$webdir/tomcat

A_VER=`cat "${TTAINSTDIR}/var/info/apacheversion"`
T_VER=`cat "${TTAINSTDIR}/var/info/tomcatversion"`

secfile=$webdir/.TWS_secure

apachepath="${apachedir}/${A_VER}"
apachebin=$apachepath/bin/apachectl
if [ ! -x $apachebin ]; then
    # whinge
    :
fi

tomcatpath="${tomcatdir}/${T_VER}"
tomcatbin=$tomcatpath/bin/catalina.sh
if [ ! -x $tomcatbin ]; then
    # whinge
    :
fi

suAttr="login-thirdparty-superusers"
tpAttr="login-thirdparty"

if [ -z "$1" -o "$1" = "--help" ]; then
    echo "$lf_webserver_usage"
    exit 0
fi

tomcat_delay () {
    # must not start apache before tomcat has started up
    logfile=$tomcatpath/logs/catalina.out
    cat $logfile >>$logfile.sav 2>/dev/null
    :>$logfile
    chown $webservusr $logfile
    chgrp $privgrp $logfile
    x=0
    while [ -z "`tr -d '\000' <$logfile | grep 'Starting service Tomcat-Standalone'`" ]; do 
        sleep 1 
        x=`expr $x + 1`
        if [ $x -gt 30 ]; then
            # failed to start, let tomcat tell them what's happening
            cat $logfile
            return 1
        fi
    done
    # wait until we think it might have *really* started ...
    sleep 10
    return 0
}

tomcat_fn () {
case $1 in 
    stop)
        echo "$l_tomcat_stop"
        $tomcatbin stop
        res=$?
    ;;
    start)
        echo "$l_tomcat_start"
        su $webservusr -c "$tomcatbin start"
        res=?
        tomcat_delay
        res=$?
    ;;
esac
case $res in
    0) echo "$l_ok";;
    *) echo "$l_failed";;
esac
}

apache_fn () {
case $1 in 
    stop)
        echo "$l_apache_stop"
        $apachebin stop
    ;;
    start)
        echo "$l_apache_start"
        [ -f $secfile ] && start_cmd="startssl" || start_cmd="start"
        $apachebin $start_cmd
    ;;
    restart)
        echo "$l_apache_restart"
        $apachebin restart
    ;;
esac
case $? in
    0) echo "$l_ok";;
    *) echo "$l_failed";;
esac
}

get_config()
{
    oldtrace="$trace"
    unset trace
    ${TTAINSTDIR}/bin/tarantella config list --${tpAttr} --${suAttr} 2>/dev/null | 
    awk 'BEGIN {
	tpla="'"${tpAttr}"': 0"
	su="'"${suAttr}"': \"\""
    }
    /^'"${tpAttr}"':/ {
	tpla = $0
    }
    /^'"${suAttr}"':/ {
	su = $0
    }
    END {
	print tpla "\n" su
    }'
    [ -n "$oldtrace" ] && trace="$oldtrace"
    return 0
}

add_trusted_user()
{
    case "$1" in
    ''|help|--help) echo "${l_add_trusted_user_usage}"; return 1
    esac
    [ $# -ne 1 ] && { echo "${l_add_trusted_user_usage}"; return 1; }
    trustedUsername="$1"
    config=`get_config`
    superusers=`echo "${config}" | sed "1d;s/.*: *//"`
    case "${superusers}" in
    ${trustedUsername} | ${trustedUsername},* | *,${trustedUsername},* | *,${trustedUsername})
	echo "${trustedUsername}${l_already_trusted}" >&2
	return 1
	;;
    esac
    gotpasswd=""
    while [ -z "${gotpasswd}" ]; do
	echo $N "${l_password1}${trustedUsername}${l_password2}" $C
	stty -echo; read trustedPassword; stty echo
	case "${trustedPassword}" in
	??????*)
	    echo $N "${l_password_again}" $C
	    stty -echo; read try2; stty echo
	    if [ "${trustedPassword}" != "${try2}" ]; then
		echo "${l_password_nonmatch}" >&2
	    else
		echo
		gotpasswd=t
	    fi
	    ;;
	*)  echo "${l_password_too_short}" >&2
	esac
    done
    ${TTAINSTDIR}/bin/tarantella config edit --${suAttr} `echo "${superusers}" | tr ',' ' '` ${trustedUsername}
    . ${TTAINSTDIR}/var/javaenv
    t=${TMPDIR:-/tmp}/ttatomcat$$
    trap 'rm -f $t; exit' 1 2 3 15
    rm -f $t >/dev/null 2>&1
    tomcatUsers="${tomcatpath}/conf/tomcat-users.xml"
    CP=".:catalina.jar"
    for EXTRA1 in `ls ${TTAINSTDIR}/bin/java/commons-logging*.jar 2>/dev/null`; do
	[ -r "${EXTRA1}" ] && CP="${CP}:${EXTRA1}"
    done
    digestedPassword=`cd ${tomcatpath}/server/lib;${JHOME}/bin/java -cp "${CP}" org.apache.catalina.realm.RealmBase -a SHA "${trustedPassword}" | sed 's/.*://'`
    awk '/^ *<role rolename="SGDExternalAuth"/ {
	print
	print "  <user username=\"'"${trustedUsername}"'\" password=\"'"${digestedPassword}"'\" roles=\"SGDExternalAuth\" />"
	next
    }
    {
	print
    }' "${tomcatUsers}" >$t 2>/dev/null
    [ `wc -c <$t` -gt 0 ] && cp $t "${tomcatUsers}"
    rm -f $t >/dev/null 2>&1
    echo "${l_todo1}"
    [ "`echo \"${config}\" | sed -n '1s/.*: *//p'`" = "0" ] && echo "${l_todo2}${tpAttr}${l_todo3}"
    return 0
}

delete_trusted_user()
{
    case "$1" in
    ''|help|--help) echo "${l_delete_trusted_user_usage}"; return 1
    esac
    [ $# -ne 1 ] && { echo "${l_delete_trusted_user_usage}"; return 1; }
    trustedUsername="$1"
    config=`get_config`
    superusers=`echo "${config}" | sed "1d;s/.*: *//"`
    case "${superusers}" in
    ${trustedUsername})
	${TTAINSTDIR}/bin/tarantella config edit --${suAttr}
	;;
    ${trustedUsername},* | *,${trustedUsername},* | *,${trustedUsername})
	${TTAINSTDIR}/bin/tarantella config edit --${suAttr} `echo "${superusers}" | tr ',' ' ' | sed "s/^${trustedUsername} //;s/ ${trustedUsername} / /g;s/ ${trustedUsername}\$//"`
	;;
    *)  echo "${trustedUsername}${l_not_trusted}" >&2
	return 1
    esac
    t=${TMPDIR:-/tmp}/ttatomcat$$
    trap 'rm -f $t; exit' 1 2 3 15
    rm -f $t >/dev/null 2>&1
    tomcatUsers="${tomcatpath}/conf/tomcat-users.xml"
    grep -v "^ *< *user *username=\"${trustedUsername}\".*roles=\"SGDExternalAuth\"" "${tomcatUsers}" >$t 2>/dev/null
    [ `wc -c <$t` -gt 0 ] && cp $t "${tomcatUsers}"
    rm -f $t >/dev/null 2>&1
    return 0
}

list_trusted_users()
{
    case "$1" in
    help|--help) echo "${l_list_trusted_users_usage}"; return 1
    esac
    [ $# -ne 0 ] && { echo "${l_list_trusted_users_usage}"; return 1; }
    get_config
    return $?
}

action=""
target=""
secure=""
quiet=""
while [ ! -z "$1" ]; do
    case $1 in
        stop|start|restart)
            [ -z "$action" ] && action="$1" || { echo "$lf_webserver_usage"; exit 0; }
            shift
        ;;
        add_trusted_user)
	    shift; add_trusted_user "$@"
	    exit $?
        ;;
        delete_trusted_user)
	    shift; delete_trusted_user "$@"
	    exit $?
        ;;
        list_trusted_users)
	    shift; list_trusted_users "$@"
	    exit $?
        ;;
        --servlet|--http)
            [ -z "$target" ] && target="$1" || target="both"
            shift
        ;;
        --quiet)
            quiet=t
            shift
        ;;
        --ssl)
            secure=t
            shift
        ;;
        *help )
            [ -z "$action" ] && echo "$lf_webserver_usage" || eval echo "\"\$l_${action}_usage\""
            exit 0  
        ;;
        * )
            echo "$lf_badarg $1"
            [ -z "$action" ] && echo "$lf_webserver_usage" || eval echo "\"\$l_${action}_shortusage\""
            exit 1
        ;;
    esac
done
[ -z "$target" ] && target="both"

case $target in
    *http|both)
        case $action in
            *start)
                if [ "$secure" = "t" ]; then
                    touch $secfile
                else
                    _ans="$a_no"
                    if [ -f $secfile ]; then
                        if [ -n "$quiet" ]; then
                            # don't prompt, just act as if --ssl was specified on command line
                            secure=t
                            touch $secfile
                        else
echo "$p_tws_sec"
echo # blank line between prompt and question
_valid=false
while [ $_valid = false ]
do
  echo $N "$q_tws_sec [$_ans] $C"
  read _answer
  if [ -z "$_answer" ]
  then
    _answer="$_ans"   # default
  fi
  case "$_answer" in
    [${a_case_yes}]* )
	    _answer=$s_yes
	    _valid=true
	    ;;
    [${a_case_no}]* )
	    _answer=$s_no
	    _valid=true
	    ;;
  esac
done
_ans="$_answer"

                            if [ "$_ans" =  "$s_yes" ]; then
                                rm -f $secfile
                            else
                                echo "$lf_tws_sec_no"
                                exit 1
                            fi
                        fi
                    fi
                fi
            ;;
        esac
    ;;
esac

case $action in
    restart)
        case $target in
            both)
                tomcat_fn stop
                apache_fn stop
                tomcat_fn start
                apache_fn start
             ;;
             --http)
                apache_fn restart
             ;;
             --servlet)
                tomcat_fn stop
                tomcat_fn start
             ;;
        esac
    ;;

    start)
        [ -d /var/lock/subsys ] && touch /var/lock/subsys/TarantellaWebServer
        case $target in
            both)
                tomcat_fn start
                apache_fn start
             ;;
             --http)
                apache_fn start
             ;;
             --servlet)
                tomcat_fn start
             ;;
        esac        
    ;;

    stop)
        case $target in
            both)
                tomcat_fn stop
                apache_fn stop
             ;;
             --http)
                apache_fn stop
             ;;
             --servlet)
                tomcat_fn stop
             ;;
        esac    
    ;;
esac

exit 0
