use v5.10;
use strict;
use warnings;

use aliased "HTTP::Tiny" => "HTTP";
use aliased "Path::Tiny" => "Path";
use aliased "Path::Iterator::Rule";
use aliased "JSON::PP" => "JSON";

my $config = do
{
	my $file = Path->new(
		$^O eq 'MSWin32'
			? do { require Win32; Win32::GetFolderPath(Win32::CSIDL_LOCAL_APPDATA(), 1) }
			: $ENV{HOME}
	)->child('perl5')->child("popcon.conf");
	$file->parent->mkpath;
	$file->exists or die "'$file' not found!\n";
	
	JSON->new->decode($file->slurp);
};

my @dists;
my $rule = Rule->new->file->name(".packlist");

for my $inc (@INC)
{
	my $auto = Path->new($inc)->child("auto");
	my $iter = $rule->iter($auto);
	while (my $f = $iter->())
	{
		my $file = Path->new($f);
		
		my $dist = $file->relative($auto);
		next unless $dist =~ s{.\.packlist$}{};
		$dist =~ s{/}{-}g;
		
		push @dists, $dist;
	}
}

my $response = HTTP->new->request(
	POST => $config->{service_url} => {
		headers => {
			"Content-Type" => "application/json",
		},
		content => JSON->new->pretty(1)->canonical(1)->encode({
			distributions => [sort @dists],
			perl_version  => "$^V",
			platform      => "$^O",
			service_key   => $config->{service_key},
		}),
	},
);

printf(
	"%d %s\n",
	$response->{status},
	$response->{reason},
);

print $response->{content} unless $response->{success};
