# Copyright 2000, Sun/AOL Alliance Messaging Divlet. All Rights Reserved.
#
# This CLEAN script is used by the VCS agent to stop a data service.
# The script is known to be compatiable with VCS 1.1.1. agent API but
# not guaranteed to be working with other versions of VCS. In which
# case modification may be required.

eval 'exec $VCS_HOME/bin/perl5 -S $0 ${1+"$@"}'
        if 0;

($ResID, $CleanReason, $State, $InstanceName, $LogHostName, $PrtStatus, $DebugMode) = @ARGV;

if ($DebugMode eq "true" || $DebugMode eq "True") {
	print "$ResID, $InstanceName, $LogHostName \n";
	}

require ("/opt/VRTSvcs/bin/MsgSrv/sub.pl");

$ServerRootPath = parse("RootPath", "", "");
$LDAPInstance = "${ServerRootPath}/slapd-${InstanceName}";
$AdminServInstance = get_admin_server_root("$ServerRootPath");

$PS	= "/usr/bin/ps";	
$KILL 	= "/usr/bin/kill -9";
$GREP   = "/bin/grep";
$FAILED = 0;

#
# Must stop Admin Server first. 
#
if ( -f "${AdminServInstance}/stop-admin" ) { 
	$admin_serv = getproc("ns-admin","$AdminServInstance");
	if ($DebugMode eq "true" || $DebugMode eq "True") { 
 		print "${AdminServInstance}/stop-admin \n";
	}
  	if ($admin_serv =~ /[1-9]/ && system("${AdminServInstance}/stop-admin") != 0) { 
    	  print "CLEAN ERROR: Admin Server stop failed.\n";
	} else {
    	  print "CLEAN: Admin Server stopped successfully.\n";
	}
  } else {
  	print "CLEAN ERROR: Admin Server not found.\n"; 
}

#
# Stop LDAP Server.
#
if ( -f "${LDAPInstance}/stop-slapd" ) { 
  	if (system("${LDAPInstance}/stop-slapd") != 0) { 
    	  print "CLEAN ERROR: LDAP Server stop failed.\n";
  	} else {
    	  print "CLEAN: LDAP Server stopped successfully.\n";
  	}
  } else {
    	print "CLEAN NOTICE: LDAP Server not found locally.\n"; 
}

#
# Stop Msg Server will stop the following Messaging Server components:
# IMAP, POP, HTTP, LMTP, job controller, dispatcher, ENS, SMS Gateway Server
#

if ( -f "${ServerRootPath}/sbin/stop-msg" ) { 
  	if (system("${ServerRootPath}/sbin/stop-msg ha") != 0) { 
    	  print "CLEAN ERROR: Messaging Server stop failed...or daemon already stopped.\n";
	  $FAILED = 1;
	} else {
    	  print "CLEAN: Messaging Server stopped successfully.\n";
	}
  } else {
  	print "CLEAN ERROR: Messaging Server not found.\n"; 
}
if ( $FAILED == 1 ) {
        open(FP, "$PS -ea -o pid,args | $GREP $ServerRootPath | $GREP -v grep |");
        while(<FP>) {
                if(/imapd|popd|tcp_smtp|job_cont|dispatch|mshttpd|stored|tcp_lmtp|enpd/) {
                        ($pid, $process) = split;
                        print "CLEAN: process $process is still alive. Killing it ... \n";
                        if (system("$KILL $pid") != 0) {
                        	"CLEAN ERROR: could not kill process $process\n";
                		exit 1;
			}
                }
	}
	close(FP);
}
exit 0;
