#! /bin/ksh
#
#
#pragma ident "@(#)nsmail_fm_stop.shi	1.1 97/06/12 SMI"
#
#ident "@(#)nsmail_fm_stop.shi   1.1     96/10/21 SMI"
#
#	Copyright 10/21/96 Sun Microsystems, Inc.  All Rights Reserved.
#

#
# Stop fault monitoring.
#

#
#	Copyright 11/18/96 Sun Microsystems, Inc.  All Rights Reserved.
#
#
#pragma ident "@(#)ds_boiler	1.1 97/06/12 SMI"
#
#ident "@(#)ds_boiler		1.7	96/11/18 SMI"
#
# common boiler for HA Internet Pro data services
#
#


ARGV0=`basename $0`
LOGGER=logger
HA_SLOGFACILITY=`haget -f syslog_facility`
HA_SLOGTAG=hadf
prog_path=`dirname $0`

# source in ha-services common utilities
. ds_utilities

# add the ha-service specific clust_progs
expr "$prog_path" : '.*/clust_progs' >/dev/null 2>&1
if [ $? -eq 0 ]; then
	PATH=${prog_path}:${PATH}
else
	PATH=${prog_path}:${prog_path}/../clust_progs:${PATH}
fi

# add the ha-service specific fault_progs
expr "$prog_path" : '.*/fault_progs' >/dev/null 2>&1
if [ $? -eq 0 ]; then
    PATH=${prog_path}:${PATH}
else
    PATH=${prog_path}:${prog_path}/../fault_progs:${PATH}
fi

#
# for use by subsequent hactl command, get hostnames of local and remote hosts
#
REMOTEHOSTS=
LOCALHOST=`uname -n`

if [ $? -ne 0 ]; then
	logerr `gettext "Cannot obtain name of local host"`
	exit 1
fi
# compute hostnames of remote nodes
PHYS_HOSTS="`haget -f all_physical_hosts`"
for i in $PHYS_HOSTS; do
	if [ "$i" != "$LOCALHOST" ]; then
		REMOTEHOSTS="$REMOTEHOSTS $i"
	fi
done
#
#	Copyright 11/20/96 Sun Microsystems, Inc.  All Rights Reserved.
#
#
#pragma ident       "@(#)do_service 1.12     01/06/08 SMI"
#
# do_service 
# Standard-name file that defines the standard-name routine bundle_do_svc(), 
# which implements the HA framework-defined methods for this data service.
# The _boiler file in this directory sources this file when the data
# service method scripts execute.
#
#

SYSLOG_PREFIX="SUNWcluster.ha.nsmail"
prefix=""
IS4X=

#
# help function
#

setNSM_PROG()
{
        typeset tnsm_conf
        tnsm_conf=$1

        if [ "${tnsm_conf}" = "/etc/netscape.mail.conf" ]; then
                IS4X=0
                NSM_PROG=NscpMail
        else
                IS4X=1
                NSM_PROG=NscpMsg
        fi
}

# Read in and interpret the data service environment configuration
source_env NSMAIL

if [ $? -ne 0 ]; then
	# source_env logs error message if it fails.
	# No need to log another; just exit.
	exit 1
fi

#
# export_conf_file_i InstanceName
# export SERVERROOT, UID, GID, SMTP/POP3/IMAP Ports
#
# Only for NMS 4.1 (i.e. not for NMS 3.5)

export_conf_file_i()
{
        #set -x
        instanceName=$1
        typeset rows i str

        rows=$(get_all NSMAIL4_CONF)

        if [[ -n "${rows}" ]]; then
                for r in ${rows}; do
                        r="`echo ${r} | tr ':' ' '`"
                        let i=0
                        let j=0
                        for str in ${r}; do
                                if [ i -eq 1 ]; then
                                        if [ "${str}" = "${instanceName}" ]; then
                                                let j=j+1
                                        fi
                                fi
                                if [ i -eq 2 ] && [ j -eq 1 ]; then
                                        variable_name=${str}
                                elif [ i -eq 3 ] && [ j -eq 1 ]; then
                                        variable_val=${str}
                                fi
                                #i=`expr $i + 1`
                                let i=i+1
                        done
                        if [[ -n "${variable_name}" ]]; then
                                export ${variable_name}=${variable_val}
                        fi
                done
        fi
        return 0
}

# Global variables

SMTP_PORT=25
POP3_PORT=110
IMAP4_PORT=143

DEF_PROBE_TIMEOUT=120

#
# After installation and setup, sendmail is a symlink , and sendmail.bk
# is Sun's sendmail
#
SENDMAIL=/usr/lib/sendmail
SENDMAIL_SUN=/usr/lib/sendmail.bk

#
# The following variables potentially can go to the config file private
# section, to allow the flexibility of which channel to probe.
#
CHECK_SMTP=y
CHECK_POP3=y
CHECK_IMAP4=y
CHECK_MSHTTP=y
CHECK_STORE=y  

#
# This is a place holder for a future parameter to tune
# the timeout period. Currently not used in the config file,
# so we default to 15 secs.
#
STOP_TIMEOUT=`get_config_param $INST_NAME PRIV_STOP_TIMEOUT`
if [ -z "$STOP_TIMEOUT" ]; then
	STOP_TIMEOUT=15
fi

#
# proto_connect  <host> <port>
#
# Attempt to connect to the mail server using telnet to a specified port.
# Will run under the probe time out.
#
# Retrun: 0 - success, 1 - failure.
#
proto_connect ()
{
	tmpfile=/var/opt/SUNWcluster/run/nsmail_probe.$$
	PROBE_TIMEOUT=`get_config_param $INST_NAME PROBE_1_TIMEOUT`
	[ -z "$PROBE_TIMEOUT" ] && PROBE_TIMEOUT=$DEF_PROBE_TIMEOUT

	hatimerun -t  $PROBE_TIMEOUT /usr/bin/telnet $1 $2 <<EOF >$tmpfile 2>&1

EOF
	if [ $? -eq 99 ]; then
		#
		# telnet had timed out
		#
		conn_err=1
	else
		#
		# we don't check the return code from telnet
		# since it returns 1 even when the connection succeeded.
		#
		grep refused  $tmpfile > /dev/null 2>&1
		if [ $? -eq 0 ]; then
			conn_err=1
		else
			conn_err=0
		fi
	fi

	rm -f $tmpfile >/dev/null 2>&1
	return $conn_err
	
} 



#
# export_conf_file
#
# export /etc/nsserver.cfg file
#

# check_ns_file
#
# Check if we have access to the Netscape config file and
# if it can be sourced in
#
# Can be called by any host in the cluster, since the conf file
# is on the private disk
#
check_ns_file ()
{


	#
	# Netscape Mail config file is pointed by CONF_FILE entry in the
	# hadsconf file.
	# The Netscape file is a collection of shell variables that we
	# check their validity below
	#
	CONF_FILE=`get_config_param $INST_NAME CONF_FILE`

	if [ -z "$CONF_FILE" ]; then
	   	logerr "$prefix.4000" \
		  `gettext "Configuration file is missing entry for CONF_FILE"`
		exit 1
	fi

	if [[ ${IS4X} = 0 ]]; then
		if [ ! -f "$CONF_FILE" ] ; then
			logerr "$prefix.4001" \
			   `gettext "4. Couldn't find $CONF_FILE file. Maybe Netscape Mail was not installed properly, or you didn't run hainetconfig(1m)"`
			exit 1
		fi

		. $CONF_FILE

		if [ $? -ne 0 ]; then
			logerr "$prefix.4002" \
		   	`gettext "Error in Netscape Mail configuration file, $CONF_FILE"`
			exit 1
		fi
	else
		export_conf_file_i  ${INST_NAME}
	fi

	return 0
}

#
# verify_conf 
#
# Verify the configuration of Netscape mail.
# Check existance of Netscape config file, and verify it's content.
#
# It should be called only from a host that owns the mail server logical
# diskset, since it is trying to access directories and files on this diskset.
#
verify_conf ()
{

	check_ns_file

	# Check for existence of the directories pointed by the config file

	if [[ ${IS4X} = 1 ]]; then
		export_conf_file_i ${INST_NAME}
		if [ ! -d $SERVERROOT ]; then
			logerr "$prefix.4003" \
			   `gettext "Netscape Messaging Server improperly installed, missing $SERVERROOT"`
			exit 1
		fi

		if [ ! -d $SERVERROOT/bin/msg/admin/bin ]; then
			logerr "$prefix.4004" \
			   `gettext "Netscape Messaging Server improperly installed, missing $SERVERROOT/bin/msg/admin/bin"`
			exit 1
		fi
	else
		if [ ! -d $PostOffice ]; then
                        logerr "$prefix.4003" \
                           `gettext "Netscape Mail improperly installed, missing $PostOffice"`
                        exit 1
                fi

                if [ ! -d $ProgramDir ]; then
                        logerr "$prefix.4004" \
                           `gettext "Netscape Mail improperly installed, missing $ProgramDir"`
                        exit 1
                fi

                if [ ! -d $MailboxDir ]; then
                        logerr "$prefix.4005" \
                           `gettext "Netscape Mail improperly installed, missing $MailboxDir"`
                        exit 1
                fi
	fi

	return 0

}

#
# do_symlink <to_sun>
#
# If to_sun is 0, create a symbolic link from sendmail to sendmail.bk,
# otherwise, create a symbolic link to NscpMail
#
do_symlink ()
{
	to_sun=$1

	if [[ ${IS4X} = 1 ]]; then
		export_conf_file_i ${INST_NAME}
		NS_SENDMAIL=$SERVERROOT/bin/msg/admin/bin/sendmail
	else
		NS_SENDMAIL=$ProgramDir/bin/sendmail
        fi

	if [ ! -h "$SENDMAIL" ]; then
		logerr "$prefix.4006" \
		   `gettext "$SENDMAIL should be a symbolic link. The system is not properly configured"`
		return 1
	fi
	
	if [ ! -f "$SENDMAIL_SUN" ]; then
		logerr "$prefix.4007" \
		   `gettext "Could not find the file $SENDMAIL_SUN"`
		return 1
	fi

	if [ $to_sun -eq 0 ]; then
		ls -l $SENDMAIL | grep $SENDMAIL_SUN >/dev/null 2>&1
		if [ $? -ne 0 ]; then
			# XXX
			#lognotice "linking $SENDMAIL_SUN to $SENDMAIL"
			/etc/init.d/sendmail stop >/dev/null 2>&1
			rm $SENDMAIL >/dev/null 2>&1
			ln -s $SENDMAIL_SUN $SENDMAIL
			/etc/init.d/SUNWscnsm start >/dev/null 2>&1
		fi
	else
		if [[ ${IS4X} = 1 ]]; then
			ls -l $SENDMAIL |grep $SERVERROOT >/dev/null 2>&1
		else
			ls -l $SENDMAIL |grep $ProgramDir >/dev/null 2>&1
                fi
		if [ $? -ne 0 ]; then
			# XXX
			#lognotice "linking $NS_SENDMAIL to $SENDMAIL"
			/etc/init.d/sendmail stop >/dev/null 2>&1
			rm $SENDMAIL >/dev/null 2>&1
			ln -s $NS_SENDMAIL $SENDMAIL
			/etc/init.d/SUNWscnsm start >/dev/null 2>&1

			if [[ ${IS4X} = 1 ]]; then
				mtagid=`/usr/xpg4/bin/id -g $MAILSRV 2>/dev/null`
			else
				mtagid=`/usr/xpg4/bin/id -g $MailUserName 2>/dev/null`
                        fi
			if [ -z "$mtagid" ]; then
				if [[ ${IS4X} = 1 ]]; then
					logerr "$prefix.4008" \
					`gettext "Couldn't get the group id of \"$MAILSRV\" "`
				else
					logerr "$prefix.4008" \
                                        `gettext "Couldn't get the group id of \"$MailUserName\" "`
                                fi
				return 1
			fi
			chgrp -h $mtagid $SENDMAIL
		fi
	fi

	return 0

}

#
# start_nsmail
#
# Start the Netscape mail daemon
#
start_nsmail ()
{
	#
	# Verify that the variables in the Netscape mail config
	# file matches the reality
	#
	verify_conf

	if [[ ${IS4X} = 1 ]]; then
		NSMAIL_PROG=$SERVERROOT/bin/msg/admin/bin/NscpMsg
	else
		NSMAIL_PROG=$ProgramDir/NscpMail
        fi

	#
	# If needed, create symlink from sendmail to NscpMail
	#
	do_symlink 1 || return 1

	#
	# Do the idempotency check
	#
	ha_svc_not_running $INST_NAME
	if [ $? -eq 0 ]; then
		#
		# launch the daemon using the process monitor
		#
		if [[ ${IS4X} = 1 ]]; then
                        iname="`echo ${INST_NAME} | sed 's/SUNWscnsm_//g'`"
                        NSMAIL_PROG=$SERVERROOT/msg-${iname}/start-msg
                        pmfadm -c $INST_NAME $NSMAIL_PROG >/dev/null 2>&1
			#pmfadm -c $INST_NAME $NSMAIL_PROG start >/dev/null 2>&1
		else
			pmfadm -c $INST_NAME $NSMAIL_PROG >/dev/null 2>&1
		fi
			# XXX If pmfadm failed because the instance was already there, 
			# XXX ignore the error. Otherwise, log an error message.
			# XXX currently, pmfadm doesn't support different error codes.
		start_code=$?
		if [ $start_code -ne 0 ]; then
			logerr "$prefix.4009" \
			   `gettext "Failed to start Netscape Mail instance $INST_NAME"`
		else
			lognotice "$prefix.2000" \
			   `gettext "Started Netscape Mail instance $INST_NAME"`
		fi
		return $start_code
	else
		return 0
	fi
	
}

#
# stop_nsmail
#
# Stop Netscape Mail. We do so by sending a TERM signal to the mail daemon
# and waiting for it to exit, using the process monitor. If after the
# waiting period it did not exit, we'll send it a KILL signal.
# 
stop_nsmail ()
{

	#
	# source in the Netscape config file
	#
	check_ns_file

	#
	# If needed, create symbolic link from sendmail to sendmail.bk
	#
	do_symlink 0 || return 1


	ha_svc_not_running $INST_NAME
	if [ $? -ne 0 ]; then
		# Send TERM and wait for the daemon to exit
		pmfadm -w $STOP_TIMEOUT -s $INST_NAME TERM || \
			pmfadm -s $INST_NAME KILL 
		stop_code=$?
		if [ $stop_code -ne 0 ]; then
			logerr "$prefix.4010" \
			   `gettext "Failed to stop Netscape Mail instance $INST_NAME"`
		else
			lognotice "$prefix.2001" \
			   `gettext "Stopped Netscape Mail instance $INST_NAME"`
		fi
		return $stop_code
	fi

	return 0
	
}

function do_setup
{
	#set -x

	CONF_FILE=`get_config_param $INST_NAME CONF_FILE`
 
    if [ -z "$CONF_FILE" ]; then
		logerr "$prefix.4000" \
          `gettext "Configuration file is missing entry for CONF_FILE"`
        exit 1
    fi

   if [[ ${IS4X} = 0 ]]; then
      if [ ! -f "$CONF_FILE" ] ; then
         ROW=$(get NSMAIL $INST_NAME)
         nsmail_sync DO_SETUP ${ROW}
      fi
   else
      if [ ! -d "$CONF_FILE" ] ; then
         ROW=$(get NSMAIL $INST_NAME)
         nsmail_sync DO_SETUP ${ROW}
      fi
   fi
}

#
# bundle_do_svc <action>
#
# called for each instance
#
bundle_do_svc ()
{

# XXX
#set -x
	typeset tconf_file

	action=$1
	# XXX
	INST_NAME=$_INST_NAME
	PROBE_TAG=$INST_NAME.probe

	prefix="$SYSLOG_PREFIX.$action"

	LOGICAL_HOST=`get_config_param $INST_NAME LOGICAL_HOST`
	tconf_file=`get_config_param $INST_NAME CONF_FILE`

	setNSM_PROG ${tconf_file}
	#export_conf_file_i ${INST_NAME}


	# XXX
	#lognotice "bundle_do_svc: called with action '$action' for instance '$INST_NAME' "

	ret_code=0

	NODE_LIST=`haget -f physical_hosts -h $LOGICAL_HOST`
	MYHOST=`uname -n`

	# Check if this node is a potential master; if not just exit.
	is_member "${MYHOST}" "${NODE_LIST}"
	if [[ "$?" -ne 0 ]]; then
		exit 0
	fi

	case $action in
	'start')
		do_setup
		start_nsmail
		ret_code=$?
		;;

	'start_net')
		;;

	'stop' )
		stop_nsmail
		ret_code=$?
		;;

	'stop_net' )
		;;

	'abort' )
		#
		# source in the Netscape config file
		#
		check_ns_file

		#
		# If needed, create symbolic link from sendmail to sendmail.bk
		#
		do_symlink 0 
		pmfadm -s $INST_NAME KILL >/dev/null 2>&1
		# XXX If pmfadm failed because the instance was not there, 
		# XXX ignore the error. Otherwise, log an error message.
		# XXX currently, pmfadm doesn't support different error codes.
		;;

	'abort_net')
		;;

	'fm_init')
		;;

	'fm_start')

		need_to_run_probe ${_INST_LOGICAL_HOST} ${LOCALHOST}

		if [ $? -ne 0 ]; then
			exit 0
		fi

		#
		# Check if we are about to probe a logical host we master (local
		# probe),  or one which another host masters (remote probe), or
		# one in maintenance mode (don't probe)
		#
		maint=`haget -f is_maint -h $LOGICAL_HOST`
		if [ $? -ne 0 ]; then
			"haget(1M) failed for logical host $LOGICAL_HOST"
			ret_code=1
		elif  [ $maint -eq 0 ]; then
			if is_member "$LOGICAL_HOST" "$MASTERED_LOGICAL_HOSTS" ; then
				local=y
			else
				local=n
			fi
			#
			# Launch a probe using the process monitor.
			# We are using the process monitor just to start and tag
			# the probe, without the retry feature of the process monitor.
			#
			PROBE_PROG=`get_config_param $INST_NAME PROBE_1_PROG`
			pmfadm -c $PROBE_TAG \
				$PROBE_PROG $INST_NAME $local >/dev/null 2>&1
			if [ $? -ne 0 ]; then
			logerr "$prefix.4011" \	
			   `gettext "Failed to start Netscape Mail probe instance $PROBE_TAG"`
				ret_code=1
			else
				lognotice "$prefix.2002" \
	`gettext "Started Netscape Mail probe instance $PROBE_TAG"`
			fi
		fi
		;;

	'fm_stop')
		# If probe not running, do nothing
		ha_svc_not_running $PROBE_TAG && exit 0
		#
		# Kill the probe that is associated with this instance.
		#
		pmfadm -s $PROBE_TAG -w $STOP_TIMEOUT TERM || \
			pmfadm -s $PROBE_TAG KILL
		if [ $? -ne 0 ]; then
			logerr "$prefix.4012" \	
				`gettext "Failed to stop Netscape Mail probe instance $PROBE_TAG"`
			ret_code=1
		else
			lognotice "$prefix.2003" \
				`gettext "stopped Netscape Mail probe instance $PROBE_TAG"`
		fi

		;;

	'fm_check_this_host_ok')
		#
		# Verify that we have access to the netscape config file
		#
		check_ns_file
		ret_code=$?
		;;

	esac

# XXX
#set +x
	return $ret_code

}
#include_boiler

# Pass args explicitly to preserve null ones.
# The return code of generic_svc will be the exit code of the method
generic_svc fm_stop "$1" "$2" "$3"
