#!/usr/bin/perl
#
# $Cambridge: hermes/conf/exim/sbin/stats_MUA,v 1.5 2008/08/14 18:58:31 fanf2 Exp $

use strict;
use warnings;

use POSIX;

if (@ARGV != 1) {
	die "usage: $0 <log number>\n";
}

my $day = $ARGV[0];

my $date =
    strftime "%Y-%m-%d", localtime (time - $day * 86400);

my $file =
    sprintf "/spool/exim/log/mainlog.%02d%s", $day, $day > 1 ? ".gz" : "";

my %full_msgs;
my %full_users;
my %short_msgs;
my %short_users;

open my $log, "zegrep User-Agent: $file |"
    or die "open zegrep $file: $!\n";

while (<$log>) {
	next unless m{ F=<([^>]*)> User-Agent: (.*)\s+$};
	my $user = $1;
	my $mua = $2;
	$full_msgs{$mua}++;
	$full_users{$mua}{$user} = 1;
	$mua =~ s|[\[\(\/0-9,.].*||;
#	$mua =~ s|[0-9.,]||g;
	$mua =~ s|[- ]+| |g;
	$mua =~ s{ +(v|ver|version)? *$}{}i;
	$short_msgs{$mua}++;
	$short_users{$mua}{$user} = 1;
}

close $log;

printf "%-10s %6s %6s %s\n",
    "# date", "users", "msgs", "user agent";

print "\n";
for my $mua (keys %short_users) {
	$short_users{$mua} = scalar keys %{$short_users{$mua}};
}
for my $mua (sort { $short_users{$b} <=> $short_users{$a}
		  or $short_msgs{$b} <=> $short_msgs{$a} } keys %short_users) {
	printf "%-10s %6d %6d %s\n",
	    $date, $short_users{$mua}, $short_msgs{$mua}, $mua;
}

print "\n";
for my $mua (keys %full_users) {
	$full_users{$mua} = scalar keys %{$full_users{$mua}};
}
for my $mua (sort { $full_users{$b} <=> $full_users{$a}
		  or $full_msgs{$b} <=> $full_msgs{$a} } keys %full_users) {
	printf "%-10s %6d %6d %s\n",
	    $date, $full_users{$mua}, $full_msgs{$mua}, $mua;
}
