#!/usr/bin/perl
#
# File:  "$Id: check_daemons.pl,v 1.2 2009/07/16 09:25:00 webmail Exp $"
#
# Description:
#
# BUGS:
#
# CHANGES:
#
# NOTE:
#
# First Created on 2008/08/22 by jonas_liu@openfind.com.tw
# Last Modified on "$Date: 2009/07/16 09:25:00 $" by  $Author: webmail $
#
# Copyright (c)2008 Openfind Information Technology INC.
# All rights reserved.
#
use strict;

my $CVSREV = '$Revision: 1.2 $';
my $CVSID = substr($CVSREV, 11, -2);

my %hDaemonPidDef = (
	'mailerd' => '/webmail/mqueue/log/mailerd.pid',
	'smtpd' => '/webmail/mqueue/log/smtpd.pid',
	'pop3d' => '/webmail/pop3/pop3d.pid',
	'imap4d' => '/webmail/imap4d/imap4d.pid',
	'm2kcrond' => '/webmail/crond/log/m2kcrond.pid',
	'm2k_chkusrd' => '/webmail/m2k_chkusrd/m2k_chkusrd.pid',
	'sph_srv' => '/webmail/sophos/log/sph_srv.pid',
	'cav_srv' => '/webmail/ClamAV/log/cav_srv.pid',
	'milo' => '/mailgates/mg/run/milo.pid'
);

sub GetPidFromFile {
	my $szPIDFile = shift;
	my $nPID = -1;
      
	open(IN, $szPIDFile) || return 0;
	$nPID = <IN>;
	$nPID += 0;
	close(IN);

	return $nPID;
}

sub CheckDaemonByPID {
	return kill(0, shift);
}

sub CheckDaemon {
	my $szDaemon = shift;
	my $nPID;

	return if(!exists($hDaemonPidDef{$szDaemon}));
	
	$nPID = GetPidFromFile($hDaemonPidDef{$szDaemon});
	
	return ($nPID > 0 && CheckDaemonByPID($nPID));
}

sub main {
	my $bCheckAll = 0;
	
	map {$bCheckAll=1 if(/^all$/);} @ARGV;

	if($bCheckAll) {
		map {return 1 if(CheckDaemon($_));} keys %hDaemonPidDef;
	}
	else {
		map {return 1 if(CheckDaemon($_));} @ARGV;
	}
	
	return 0;
}

printf("%d", main());
