#!/usr/bin/perl
our $VERSION = '1.20140711'; # VERSION
use strict;
use warnings;

use Data::Dumper;
use Getopt::Long;
use HTTP::Request;
use JSON;
use LWP::UserAgent;

my %command_line_options = (
        'host:s' => \my $host,
        'port:s' => \my $port,
        'data:s' => \my $data,
        );
GetOptions (%command_line_options);

if (!$host) { $host = 'localhost'; warn "using default: --host=$host\n"; };
if (!$port) { $port = '8080'; warn "using default: --port=$port\n"; };
if (!$data) { $data = get_json_request(); warn "using sample --data\n"; };
if ($data eq '-') {
    $data = '';
    while ($_ = <>) { chomp; $data .= $_; };
}

my $url  = "http://$host:$port/dmarc/json/validate";
my $ua   = LWP::UserAgent->new;
my $req  = HTTP::Request->new(POST => $url);
   $req->content_type('application/json');
   $req->content($data);

my $response = $ua->request($req)->decoded_content;
#print Dumper($response);       # raw JSON response
my $result;
eval { $result = JSON->new->utf8->decode($response) };
if ($result) {
    print Dumper($result);      # pretty formatted struct
    exit;
};

die $response;

sub get_json_request {
    return JSON->new->encode ({
        source_ip     => '192.0.1.1',
        envelope_to   => 'example.com',
        envelope_from => 'cars4you.info',
        header_from   => 'yahoo.com',
        dkim          => [
            {   domain       => 'example.com',
                selector     => 'apr2013',
                result       => 'fail',
                human_result => 'fail (body has been altered)',
            }
        ],
        spf => [
            {   domain => 'example.com',
                scope  => 'mfrom',
                result => 'pass',
            }
        ],
    });
};

# ABSTRACT: an HTTP client for submitting a DMARC validation request
# PODNAME: dmarc_http_client

__END__

=pod

=head1 NAME

dmarc_http_client - an HTTP client for submitting a DMARC validation request

=head1 VERSION

version 1.20140711

=head1 SYNOPSIS

Send JSON encoded HTTP requests to the DMARC validation service provided by dmarc_httpd.

    dmarc_http_client --host=localhost
                      --port=8080
                      --data='{"envelope_from":"cars4you.info"...}'

The data option accepts a special '-' value that will read the JSON encoded data from STDIN. Use it like this:

   cat /path/to/data.json | dmarc_http_client --data=-

=head1 AUTHORS

=over 4

=item *

Matt Simerson <msimerson@cpan.org>

=item *

Davide Migliavacca <shari@cpan.org>

=back

=head1 COPYRIGHT AND LICENSE

This software is copyright (c) 2014 by ColocateUSA.com.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=cut