#!/usr/bin/perl 
use XML::LibXML;
use MIME::Base64;
my $parser = XML::LibXML->new();
my $file = $ARGV[0] or die "cant open input file\n";
my $doc = $parser->parse_file($file);

my $xpc = XML::LibXML::XPathContext->new($doc);
foreach my $h ( $xpc->findnodes('//items/item') ) {
	my $url
		= @{$h->getElementsByTagName('url')}[0]->textContent();
	my $port
		= @{$h->getElementsByTagName('port')}[0]->textContent();
	my $method
		= @{$h->getElementsByTagName('method')}[0]->textContent();
	my $host
		= @{$h->getElementsByTagName('host')}[0]->textContent();
	my $path
		= @{$h->getElementsByTagName('path')}[0]->textContent();
	my $request
		= @{$h->getElementsByTagName('request')}[0]->textContent();
	my $mimetype
		= @{$h->getElementsByTagName('mimetype')}[0]->textContent();
	if ($mimetype eq 'JSON'){
		$host =~ s/\./_/g;
		$path =~ s/\./_dot_/g;
		$path =~ s/\//_/g;
		my $filename = join('_',$host,$port,$path);
		print "Writing $filename\n";
		open(OUT,">json/$filename.json") or die "cant open filename for writing\n";
		print OUT decode_base64($request);
		close(OUT);
	}
}
