#!/bin/sh
# Copyright 2003 Sun Microsystems, Inc.  All rights reserved.
# PROPRIETARY/CONFIDENTIAL.  Use of this product is subject to license terms.

###############################################
# Sourcing macros
. ${BASE_DIR}/${PRODUCT_DIR}/lib/psmacros
###############################################

PATH=/bin:/usr/bin:/sbin:/usr/sbin

#
PS_HOME=${BASE_DIR}/$PS_PRODUCT_DIR
IS_HOME=${IDSAME_BASE_DIR}/$IDSAME_PRODUCT_DIR

FILE_GW_INSTANCE_SETUP=$PS_CONFIG_DIR/platform.conf
FILE_RWP_LOG=$PS_VAR_DIR/debug/rwproxy.log
FILE_VERSION=${BASE_DIR}/$PS_PRODUCT_DIR/lib/SRAversion.properties

FILE_RWP_PID=$PS_VAR_DIR/.rp.pid  # Rewriter Proxy pid
FILE_RWP_PORT=$PS_VAR_DIR/.rp.               # Rewriter Proxy port

IS_CHROOT=0            # Running from chroot env? 1=yes 0=no
CHROOT_DIR=CHROOT_DIR  # Chroot directory

TEXTDOMAIN=gwscripts
TEXTDOMAINDIR=${BASE_DIR}/$PS_PRODUCT_DIR/locale
export TEXTDOMAIN
export TEXTDOMAINDIR
export LANG
NEWLINE='\n'

# Shared components, utilities
NOHUP=/usr/bin/nohup
GETTEXT=/usr/bin/gettext
JSS_NSS_NSPR_LIBPATH=$JSS_NSS_NSPR_LIB_DIR
JSS_JAR=$JSS_JAR_LIB_DIR/jss3.jar

###############################################################################

###############################################
#
###############################################
GrabConfig() {
    ANSWER=`grep "^$2$3" $1 | uniq | sed -e "s/$2$3//"`
}
GrabConfigSingle() {
    ANSWER=`grep "^$2$3" $1 | uniq | sed -e "s/$2$3//" | tr -d "\t " `

}

###############################################
#
###############################################
GetJDKVersion() {
    AWK=/usr/bin/awk

    if [ -x ${JAVA_HOME}/bin/java ]; then
        ANSWER_VERSION=`${JAVA_HOME}/bin/java -fullversion 2>&1 | ${AWK} '{print $4}' | sed -e "s/\"//g"`
    else
        ANSWER_VERSION=""
    fi

    INDEX1_4=`echo ${ANSWER_VERSION} | ${AWK} '{print index($0,"1.4")}'`
    INDEX1_3=`echo ${ANSWER_VERSION} | ${AWK} '{print index($0,"1.3")}'`

    if [ "${INDEX1_4}" = "1" ]; then
        JDK_VERSION="1.4"
    else
        if [ "${INDEX1_3}" = "1" ]; then
            JDK_VERSION="1.3"
        fi
    fi
}

###############################################
#
###############################################
getUmask() {
    GrabConfigSingle $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "rwproxyd.umask" "="
    REQUIRED_UMASK=$ANSWER
    if [ -z "$REQUIRED_UMASK" ]; then
        REQUIRED_UMASK=000
    fi
}

###############################################
#
###############################################
GearUp() {
    # cd Out of CDROM dir, otherwise CDROM can't eject
    cd $PS_VAR_DIR/debug

    # Grab configuration
    GrabConfig $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "gateway.jdk.dir" "="
    JAVA_HOME=$ANSWER
    GetJDKVersion

    GrabConfigSingle $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "gateway.host" "="
    RWP_HOST=$ANSWER
    GrabConfigSingle $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "gateway.port" "="
    RWP_PORT=$ANSWER
    GrabConfigSingle $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "gateway.protocol" "="
    RWP_PROTOCOL=$ANSWER
    GrabConfigSingle $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "gateway.notification.url" "="
    RWP_NOTIFICATION_URL=$ANSWER
    IDENTITY_NOTIFICATION_URL=$GATEWAY_PROTOCOL://$GATEWAY_HOST:$GATEWAY_PORT/$RWP_NOTIFICATION_URL

    GrabConfigSingle $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "portal.server.instance" "="
    IS_CONFIG_NAME=$ANSWER

    GrabConfigSingle $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "portal.server.host" "="
    PORTAL_HOST=$ANSWER
    GrabConfigSingle $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "portal.server.port" "="
    PORTAL_PORT=$ANSWER
    GrabConfigSingle $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "gateway.retries" "="
    TRY_COUNT=$ANSWER

    GrabConfig $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE "gateway.certdir" "="
    DIRECTORY_CERT_DB=$ANSWER
    FILE_CERT_DB_PASSWORD=$DIRECTORY_CERT_DB/.jsspass
    FILE_CERT_NICKNAME=$DIRECTORY_CERT_DB/.nickname

    getUmask

     #To workaround JDK JNI bug on Linux
    OSTYPE=`/bin/uname -s`
    if [ "$OSTYPE" = "Linux" ]; then
        EXTRA_LIBS="$JAVA_HOME/jre/lib/i386/native_threads"
        LD_LIBRARY_PATH="$LD_LIBRARY_PATH:$EXTRA_LIBS"
        export LD_LIBRARY_PATH
    fi
}

###############################################
#
###############################################
CheckPortalInstance() {
    index=1
    while [ $index -le $TRY_COUNT ]; do
        $PS_HOME/bin/checkport $PORTAL_HOST $PORTAL_PORT 3
        if [ $? -eq  0 ]; then
            break;
        fi
        echo "`$GETTEXT 'RewriterProxy is waiting for Portalserver to start first!'`"
        index=`expr $index + 1`
        sleep 10
    done

    index=`expr $index - 1`
    if [ $index -eq $TRY_COUNT ]; then
        # Last try ...
        $PS_HOME/bin/checkport $PORTAL_HOST $PORTAL_PORT 3
        if [ $? -ne  0 ]; then
           echo "`date`..." >> $FILE_RWP_LOG.$GW_INSTANCE 2>&1
           echo "`$GETTEXT 'RewriterProxy cannot get started. Portalserver has to start first.'` " >> $FILE_RWP_LOG.$GW_INSTANCE 2>&1
           exit 1
        fi
    fi
}

###############################################
# Set CLASSPATH and LD_LIBRARY_PATH
###############################################

SetPath() {

    # Classpath
    IS_CLASSPATH="$IDSAME_CONFIG_DIR/config:$IS_HOME/lib:$IS_HOME/locale:$IS_HOME/lib/am_sdk.jar:$IS_HOME/lib/am_services.jar:$IS_HOME/lib/am_logging.jar:$IS_HOME/lib/servlet.jar"
    JCE_CLASSPATH="$IS_HOME/lib/jce1_2_1.jar:$IS_HOME/lib/local_policy.jar:$IS_HOME/lib/US_export_policy.jar:$IS_HOME/lib/sunjce_provider.jar"
    # Classpath is w.r.t. working directory that is $PS_HOME
    RWP_CLASSPATH="lib:locale:lib/rwproxy.jar:lib/gateway.jar:lib/rewriter.jar:lib/certadmin.jar:lib/ssl.jar:lib/x509v1.jar"
    RWP_CLASSPATH="$IS_CLASSPATH:$JCE_CLASSPATH:$JSS_JAR:$RWP_CLASSPATH"

    if [ -z "$CLASSPATH" ] ; then
	    CLASSPATH="$RWP_CLASSPATH"
    else
	    CLASSPATH="$RWP_CLASSPATH:$CLASSPATH"
    fi
    export CLASSPATH

    # LD_LIBRARY_PATH
    if [ -z "$LD_LIBRARY_PATH" ] ; then
	    LD_LIBRARY_PATH="$JSS_NSS_NSPR_LIBPATH:$PS_HOME/lib/solaris/sparc"
    else
	    LD_LIBRARY_PATH="$JSS_NSS_NSPR_LIBPATH:$PS_HOME/lib/solaris/sparc:$LD_LIBRARY_PATH"
    fi
    export LD_LIBRARY_PATH
}

###############################################
#
###############################################
Start() {
    cd $PS_HOME

    echo "`$GETTEXT 'Starting RewriterProxy... '`\c"
    echo "`date`..." >> $FILE_RWP_LOG.$GW_INSTANCE 2>&1
    echo "`$GETTEXT 'RewriterProxy started.'` " >> $FILE_RWP_LOG.$GW_INSTANCE 2>&1

    CMD="$JAVA_HOME/bin/java $NATIVE_THREAD -ms64m -mx128m -classpath $CLASSPATH -DSRAP_CONFIG_DIR=$PS_CONFIG_DIR $DEFINES1 $DEFINES2 $DEFINES3 $DEFINES4 $DEFINES5 $BOOT_CLASSPATH com.sun.portal.rproxy.rewriterproxy.HTTPProxy"
    if [ "$IS_CHROOT" -eq 1 ] ; then
        ($NOHUP chroot $CHROOT_DIR ${CMD}) \
	    > $log 2>&1 &
    else
        ($NOHUP ${CMD}) > $log 2>&1 &
    fi

    echo $! > ${FILE_RWP_PID}.${GW_INSTANCE}
    chmod 400 ${FILE_RWP_PID}.${GW_INSTANCE}
    echo "`$GETTEXT 'done.'`"
}

###############################################
#
###############################################
DoDebug() {
    if [ "$1" = "debug" ]; then
        echo "`$GETTEXT 'RewriterProxy debugging on'`"
        log=/dev/stdout
        NOHUP=""
    else
        log=/dev/null
    fi
}

###############################################
#
###############################################
StartRewriterProxy() {
    # Use native threads if JDK supports '-native' option
    native_test1=`${JAVA_HOME}/bin/java -native 2>&1 | grep -i "illegal\ argument"`
    native_test2=`${JAVA_HOME}/bin/java -native 2>&1 | grep -i "not\ supported"`
    if [ -z "$native_test1" ] && [ -z "$native_test2" ]; then
        NATIVE_THREAD=-native
    else
        NATIVE_THREAD=""
    fi

    # Defines or Java system properties
    DEFINES1="-Dsun.net.inetaddr.ttl=0 -Djava.protocol.handler.pkgs=com.iplanet.services.comm"
    DEFINES2="-Dcom.iplanet.am.notification.url=$IDENTITY_NOTIFICATION_URL -Dgateway.notification.url=$RWP_NOTIFICATION_URL"
    DEFINES3="-Dgateway.keybase=$DIRECTORY_CERT_DB -Dgateway.pass=$FILE_CERT_DB_PASSWORD -Dgateway.nickname=$FILE_CERT_NICKNAME"
    DEFINES4="-Djava.util.logging.manager=com.sun.identity.log.LogManager -Djava.util.logging.config.file=$IS_HOME/lib/LogConfig.properties"

    DEFINES5="-Dgateway.profilename=$GW_INSTANCE -Dconf.suffix=$GW_INSTANCE"
    if [ "$IS_CONFIG_NAME" -ne "" ]; then
        DEFINES5="$DEFINES5 -Dserver.name=$IS_CONFIG_NAME"
    fi

    if [ "${JDK_VERSION}" = "1.3" ]; then
        BOOT_CLASSPATH="-Xbootclasspath:$JAVA_HOME/lib/tools.jar:$JAVA_HOME/jre/lib/rt.jar:$JAVA_HOME/jre/lib/i18n.jar:$IS_HOME/lib/jdk_logging.jar"
    fi

    # Verify if Portal Server is up
    CheckPortalInstance

    # Start
    Start
}

###############################################
#
###############################################
StopRewriterProxy() {
    getUmask
    umask $REQUIRED_UMASK

    if [ -s $FILE_RWP_PID.$GW_INSTANCE ]; then
	    pid=`cat $FILE_RWP_PID.$GW_INSTANCE`
	    echo "`$GETTEXT 'Stopping RewriterProxy... '`\c"
	    kill $pid > /dev/null 2>&1
        rm -f $FILE_RWP_PID.$GW_INSTANCE
    	echo "`$GETTEXT 'done.'`"
    elif [ "$1" = "warn" ]; then
	    eval echo "`$GETTEXT 'RewriterProxy is not running. If this is not correct,'`" \
	        "`$GETTEXT 'please check whether $NEWLINE$FILE_RWP_PID.$GW_INSTANCE exists. If this file does'`"\
	        "`$GETTEXT 'not exist, $NEWLINEyou will have to manually kill the RewriterProxy processes.'`"
    fi
}

###############################################
#
###############################################
ParseArguments() {
    while getopts n: name
    do
        case $name in
            n)  nflag=1
                GW_INSTANCE="$OPTARG"
                ;;

            ?)  echo "`$GETTEXT 'Usage:'` $0 { -n <instance-name> start | -n <instance-name> stop | watchdog <on|off>}"
                exit 2
                ;;
        esac
    done
}

###############################################################################
# Main
###############################################################################

if test `id | /usr/bin/awk '{print $1}'` != "uid=0(root)"
then
	echo "`$GETTEXT 'You must be root user to run'` $0."
	exit 0
fi

umask 000
ulimit -n 10240

SetPath

nflag=
GW_INSTANCE=

ParseArguments $*
shift `expr $OPTIND - 1`

case "$1" in
    'start')
        if [ -z "$nflag" ]; then
            for x in $FILE_GW_INSTANCE_SETUP.*; do
                if [ -r $x ]; then
                    GW_INSTANCE=`echo $x | sed -e "s#$FILE_GW_INSTANCE_SETUP.##"`

                    GearUp
                    umask $REQUIRED_UMASK
                    StopRewriterProxy nowarn

#                    if [ ! -s $FILE_CERT_DB_PASSWORD ] ; then
#                        eval echo "`$GETTEXT '$0: Cannot auto-start without $FILE_CERT_DB_PASSWORD file.'`"
#                        exit 0
#                    fi

                    DoDebug
                    StartRewriterProxy
                fi
            done
        else
            if [ ! -f $FILE_GW_INSTANCE_SETUP.$GW_INSTANCE ]; then
                echo "`$GETTEXT 'Rewriter Proxy cannot get started. Configuration for specified profile does not exist!'`"
                exit 1
            fi

            GearUp
            umask $REQUIRED_UMASK
            StopRewriterProxy nowarn

#            if [ ! -s $FILE_CERT_DB_PASSWORD ] ; then
#                eval echo "`$GETTEXT '$0: Cannot auto-start without $FILE_CERT_DB_PASSWORD file.'`"
#                exit 0
#            fi

            DoDebug $2
            StartRewriterProxy
        fi
        ;;

    'stop')
        if [ -z "$nflag" ]; then
            for x in $FILE_RWP_PID.*; do
                if [ -r $x ]; then
                    GW_INSTANCE=`echo $x | sed -e "s#$FILE_RWP_PID.##"`
                    StopRewriterProxy nowarn
                fi
            done
        else
            StopRewriterProxy warn
        fi
        ;;

    'watchdog')
        CRONTAB="/var/spool/cron/crontabs/root"
        CRON="/etc/init.d/cron"
        getUmask
        umask $REQUIRED_UMASK
        if [ "$2" = "on" ]; then
            if  grep checkrp $CRONTAB >/dev/null ; then
                echo "`$GETTEXT 'Rewriter Proxy watchdog already enabled'`"
                exit
            fi

            echo "`$GETTEXT 'Enabling RewriterProxy watchdog... '`"
            echo "0-59 * * * * ${PS_HOME}/bin/checkrp $FILE_RWP_PORT 5 > /dev/null 2>&1" >> $CRONTAB
            $CRON stop
            $CRON start
            echo "`$GETTEXT 'done.'`"
        else
            if [ "$2" = "off" ]; then
                echo "`$GETTEXT 'Disabling RewriterProxy watchdog... '`"
                cp $CRONTAB /tmp/.cron
                sed -e '/checkrp/d' /tmp/.cron > $CRONTAB
                rm -f /tmp/.cron
                $CRON stop
                $CRON start
                echo "`$GETTEXT 'done.'`"
            else
                echo "`$GETTEXT 'Usage:'` $0 { [-n <instance-name>] start | [-n <instance-name>] stop | watchdog <on|off> | version }"
            fi
        fi
        ;;

    'version')
        if [ -f $FILE_VERSION ]; then
            GrabConfig $FILE_VERSION "build" "="
            BUILD=$ANSWER
            GrabConfig $FILE_VERSION "productname" "="
            PNAME=$ANSWER
            GrabConfig $FILE_VERSION "productversion" "="
            echo "$BUILD $PNAME $ANSWER"
        fi
        ;;

    *)
        echo "`$GETTEXT 'Usage:'` $0 { -n <instance-name> start | -n <instance-name> stop | watchdog <on|off> | version}"
        ;;
esac

