#!/usr/bin/perl

use strict;
use warnings;

# $Id: count_recps.pl 78 2007-11-02 19:37:21Z ed $
# $URL: svn+ssh://fw/repos/code/perl/qmail/count_recps.pl $

# count_recps.pl - copyright ed neville
# Counts the number of recipients for a given message number
# 2006-05-14 ed AT s5h DOT net - beta code
# Use at your own risk. Author not responsible for use.
#
# Updates at http://www.s5h.net
#
# 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; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
#

# badly formatted

# A=0 ; 
# for j in $( 
# 	for i in $( 
# 		qmailctl queue 
# 			| grep sales@example.test
# 			| sed 's/^.*#\([0-9]\+\).*$/\1/g' ) ; 
# 	do 
# 		perl count_recps.pl $i ; 
# 	done ; 
# ) ; 
# do 
# 	A=$(( $A+$j )) ; 
# done ; 
# echo $A
#
# what's key in the above is that you must:
# 
#  1) find a message number to feed into this script
#  2) use grep and qmailctl to list the messages that are bouncing
#  3) extact the message number from those that are listed
#

my %config;

sub get_env {
	my @ctl = `/var/qmail/bin/qmail-showctl`;
	foreach( @ctl ) {
		if( $_ =~ /subdirectory split: ([0-9]+)\./ ) {
			$config{'split'} = $1;
			next;
		}

		if( $_ =~ /qmail home directory: (.+)\./ ) {
			$config{'home'} = $1;
			next;
		}
	}
}


sub count_recps {
	my $file = shift;
	my $c = 0;

	open( F, "<$file" );
	my @lines =<F>;
	my $l = join( '\0', @lines );
	my @a = split( /\0/, $l );
	$c += scalar( @a );
	close(F);
	return( $c );
}

sub main {
	my $message_id = $ARGV[0];

	if( !defined( $message_id ) ) {
		print( STDERR "Usage: count_recps.pl <message id>\n" );
		exit;
	}

	print( count_recps( $config{'home'} . "/queue/remote/" . 
		( $message_id % $config{'split'} ) . "/$message_id" ) . 
		"\n" ); 
}

get_env();
main()

