#!/usr/bin/perl

use lib "/opt/rt3/lib";
use strict;

use constant PAGE_SIZE => 100;

use RT;
RT::LoadConfig;
RT::Init;

use RT::Tickets;
use RT::Queue;

sub usage
{
	print "\tusage: perl $0 QUEUE\n";
	exit(1);
}


my $queue_name = shift;
unless( $queue_name ) {
	usage();
}

my $queue = new RT::Queue( $RT::SystemUser );
$queue->Load( $queue_name );
unless( $queue->id ) {
	print STDERR "Can't find queue '$queue_name'\n";
	exit(1);
}
$queue_name = $queue->Name;

my $Tickets = new RT::Tickets( $RT::SystemUser );
$Tickets->LimitQueue( VALUE => $queue->id );
# we should be sure that order is allways the same between pages
$Tickets->OrderByCols( { FIELD => 'id', ORDER => 'ASC' } );
my $total = $Tickets->Count;

print "info: $total tickets in queue '$queue_name'\n";
$Tickets->RowsPerPage( PAGE_SIZE );

do {
	while( my $t = $Tickets->Next ) {
		walk_attachments($t, \&cb_attachment);
	}
} while( $Tickets->NextPage < $total );

sub cb_attachment
{
	my %args = (
			Ticket => undef,
			Transaction => undef,
			Attachment => undef,
			@_
		   );
	printf "ticket: %d\ttransaction: %d\tattachment: %d\n",
		map { $_->id }
		@args{qw(Ticket Transaction Attachment)};

# GetHeaders is crappy shit in RT API and doesn't return fields with
# more then one value
	my $headers = $args{'Attachment'}->Headers;
	my $last_received = '';
	foreach my $l ( reverse( split /\n(?=\w|\z)/, $headers ) ) {
		next unless $l =~ /^Received:/i;
		$last_received = $l;
		last;
	}
	unless( $last_received ) {
		print "no received\n";
		return;
	}

	my ($ip) = ($last_received =~ m/\[(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\]/);
	unless( $ip ) {
		print "no IP\n";
		return;
	}
	
	print "ip: $ip\n";
	
	return;
}





sub walk_attachments
{
	my $ticket = shift;
	my $callback = shift;
	my $txns = $ticket->Transactions;
	while( my $txn = $txns->Next ) {
		my $as = $txn->Attachments;
		while( my $a = $as->Next ) {
			$callback->(
				Ticket => $ticket,
				Transaction => $txn,
				Attachment => $a
			);
		}
	}
}
