#!/bin/bash
# # Copyright (C) 2004 Networks Associates Technology Inc. All rights reserved.
#
if [ -f $NETAWSS/.profile.vars ]; then 
 . $NETAWSS/.profile.vars 
else 
 . /var/NAIENV/.profile.vars 
fi 

. ${WSMGMT}/spam-functions


RC="$WSMGMT/rc"
SPAMFLAGS=

[[ "$PATH" == "$wsPATH":* || -z "$wsPATH" ]] || PATH=$wsPATH:$PATH
shopt -s extglob

logger -t webshield Starting protocol proxies
start_proxy()
{
    EXECUTABLE=${WSPROXY}/${1}
    PROXY=${2}
    shift;shift;

    test -x ${EXECUTABLE}
    if [ $? != 0 ]
    then
         return 1
    fi
    test -f ${XMLCONFDIR}/${PROXY}.xml
    if [ $? != 0 ]
    then
         return 1
    fi

    xsltproc --stringparam name ${PROXY} --stringparam executable ${EXECUTABLE} --stringparam protocol ${PROXY} --stringparam parameters "$*" ${WSMGMT}/start_proxy.xsl ${XMLCONFDIR}/${PROXY}.xml | /bin/bash
    return $?
}

run_proxy()
{
    start_proxy $*
    if [ $? != 0 ]
    then
        logger -t webshield Error starting ${2}
    fi
}
read_bind_addresses()
{
xsltproc  - ${XMLCONFDIR}/ls.xml <<-END
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text"/>

<xsl:template match="/">
    <xsl:for-each select="/PolicySet/GlobalSettings[@name='base']/Policy[@ID='base']/PolicyStatement/Settings[@name='network']/List[@name='BindAddress']/Attr">
        <xsl:value-of select="@value"/>
        <xsl:text>&#10;</xsl:text>
    </xsl:for-each>
</xsl:template>
</xsl:stylesheet>
END
}
is_ls_enabled()
{
   # Check if the kernel driver is present
   if [ -d /proc/wsrmgr ]
   then
       return 0
   fi
   
   # need to check for the bind-ports
   BIND_ADDRESS=`read_bind_addresses`
   for f in $BIND_ADDRESS
   do
	if [ "${f}" != "127.0.0.1" ]
        then
             return 0
        fi
   done
   return 1
}
run_ls()
{
    is_ls_enabled
    if [  $? = 0 ]
    then
	run_proxy $*
    fi
}
# now restart the proxies
# proxymgr restart doesn't do what we need at the moment

killall -q -HUP ws_ftp ws_http ws_pop3 ws_ls ws_smtp ws_icap
sleep 1

# Determine if anti spam is enabled for smtp
antispam=`/usr/sbin/webshield smtp_anti_spam.xsl`
if [ "${antispam}" = "1" ]
then
     SPAMFLAGS="-a"
fi

# Take a note of the versions of everything
/usr/sbin/webshield ws_scanner_versions

# restart all of the proxies
run_proxy ws_ftp ftp
run_proxy ws_http http
run_proxy ws_pop3 pop3
#run_proxy ws_icap icap
run_ls ws_ls ls ${SPAMFLAGS}
run_proxy ws_smtp smtp ${SPAMFLAGS}
${WSBIN}/ws_smtp -s retryer -t log smtp smtp

NO_QUARANTINE=`find /quarantine/smtp -name \*.rmd | wc -l`
NO_DEFERRED=`find /deferred/smtp -name \*.rmd | wc -l`

if [ $NO_DEFERRED -gt 0 -o $NO_QUARANTINE -gt 0 ]
then
	${WSBIN}/ws_smtp -s retryer -t quarantine smtp smtp
	${WSBIN}/ws_smtp -s retryer -t smtp smtp smtp
else
	run_proxy ws_smtp smtp -s retryer -t quarantine
	run_proxy ws_smtp smtp -s retryer -t smtp
fi


exit 0
