# Copyright 2000, Sun/AOL Alliance Messaging Divlet. All Rights Reserved.
#
# This MONITOR script is used by the VCS agent to start 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.
#
# succeed exit_code = 110.
# fail exit_code = 100.
#
eval 'exec $VCS_HOME/bin/perl5 -S $0 ${1+"$@"}'
        if 0;

# The InstanceName here is only pertinent to LDAP Server
($ResID, $State, $InstanceName, $LogHostName, $PrtStatus, $DebugMode) = @ARGV;

#
# Only print messages when the service is on-line.
# 
sub Log {
        if ($State != 2) {
        return;
        }
        print STDERR $_[0];
}

sub check_proc {
	my $Process = shift; 
	my $PID = shift;
	if ($DebugMode eq "true" || $DebugMode eq "True") {
		Log "$Process = $PID\n";
	}

	if (! $PID =~ /[0-9]/ ) {
		Log ("MONITOR: process $Process is offline.\n");
		exit 100; 
	}
}

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

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

$ServerRootPath = parse("RootPath", "", "");

if ($DebugMode eq "true" || $DebugMode eq "True") {
	#Log "MsgInstance = $MsgInstance, ServerRootPath = $ServerRootPath \n";
	Log "ServerRootPath = $ServerRootPath \n";
	}

# Preserve the init state:
 
$exit_code = 110; # online exit code.

#
# Check process status in the process table
#
foreach $PROC (watcher) {
	$pid = getproc("$PROC","$ServerRootPath");
	check_proc("$PROC", $pid);
}

#
# Assign the port numbers here: 
#
$WATCHERPORT = get_port("$ServerRootPath", "local.watcher.port");
$WATCHERCMD = "exit\n";

# 
# Check the connection via telnet
# If one of them fails, the exit code is 100.
#

$watcher_ret = connection("$LogHostName", "$WATCHERPORT", "WATCHER", "$WATCHERCMD");
	if ($watcher_ret == 100) {
		Log "MONITOR: bad connection to WATCHER port $WATCHERPORT \n"; 
  		$exit_code = 100; # offline exit code.
	}

if ($exit_code == 110 && ($PrtStatus eq "true" || $PrtStatus eq "True")) {
	Log "$InstanceName service $ResID online\n"; 
  	}

exit $exit_code; 
