#!/usr/bin/perl
# 
# ***** BEGIN LICENSE BLOCK *****
# Zimbra Collaboration Suite Server
# Copyright (C) 2005, 2006, 2007, 2009, 2010, 2013, 2014, 2015, 2016 Synacor, Inc.
#
# This program is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software Foundation,
# version 2 of the License.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this program.
# If not, see <https://www.gnu.org/licenses/>.
# ***** END LICENSE BLOCK *****
# 

use strict;

use lib "/opt/zimbra/common/lib/perl5";
use Zimbra::Util::Common;
use Zimbra::Mon::Logger;

my $platform=qx(/opt/zimbra/libexec/get_plat_tag.sh);
chomp $platform;

my $MNTCMD;
my $DFCMD;
if ($platform eq "MACOSX") {
	$MNTCMD = "mount -t hfs";
	$DFCMD = "df -ml ";
} else {
	$MNTCMD = "mount -t ext3";
	$DFCMD = "df -ml ";
}

my $dt = qx(date "+%Y-%m-%d %H:%M:%S");
chomp $dt;

checkPid();
logQueue();
clearPid();

exit 0;

sub checkPid {
	if (-f "/opt/zimbra/log/zmqueuelog.pid") {
		my $P = qx(cat /opt/zimbra/log/zmqueuelog.pid);
		chomp $P;
		if ($P ne "") {
      system("kill -0 $P 2> /dev/null");
      if ($? == 0) {
        print "$0 already running with pid $P\n";
        exit 0;
      }
		}
	}
	qx(echo $$ > "/opt/zimbra/log/zmqueuelog.pid");
}

sub clearPid {
	unlink ("/opt/zimbra/log/zmqueuelog.pid");
}

sub logQueue {
	my @status = ();
	open STATUS, "/opt/zimbra/common/sbin/postqueue -p |" or die "Can't get status: $!";
	@status = <STATUS>;
	close STATUS;
	my $kb = 0;
	my $msgs = 0;
	my $s = $status[$#status];
	if ($s =~ /^--/) {
		my @foo = split (' ', $s);
		$kb = $foo[1];
		$msgs = $foo[4];
	}
	Zimbra::Mon::Logger::Log( "info", "$dt, QUEUE: $kb $msgs" );
}
