#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long qw(:config pass_through);
use Pod::Usage;
use Config::General;
use Data::Dumper;
use WWW::ManageWP;
my %options;
GetOptions(
	# credentials
	'apiKEY=s'  => \$options{apiKEY},
	'apiURL=s'  => \$options{apiURL},
	# api method
	'method=s'  => \$options{method},
	'request=s' => \$options{request},
	# help
	'help|?'    => \$options{help},
	man         => \$options{man},
) or die("Error in command line arguments\n");
pod2usage(1) if $options{help};
pod2usage(-exitval => 0, -verbose => 2) if $options{man};
pod2usage(1) if (
	!$options{method}
	|| !$options{request}
);
if (!$options{apiKEY} || !$options{apiURL}) {
	my $potential_cfg = "$ENV{HOME}/.managewp-client.cfg";
	if (-r $potential_cfg) {
		my $config = Config::General->new($potential_cfg);
		my %config = $config->getall;
		if ($config{apiKEY} && $config{apiURL}) {
			$options{apiKEY} = $config{apiKEY};
			$options{apiURL} = $config{apiURL};
		}
	}
	else {
		pod2usage(1);
	}
}
my %method_options;
foreach my $method_option (@ARGV) {
	if (!$method_option =~ m/^--/) {
		pod2usage(1);
	}
	if ($method_option =~ m/=(.*)=/) {
		die("Multiple equals [=] in method argument\n");
	}
	my ($key, $val) = map {s/^--//; $_} split('=', $method_option);
	$method_options{$key} = $val;
}
my $response;
eval {
	my $managewp = WWW::ManageWP->new(
		apiKEY => $options{apiKEY},
		apiURL => $options{apiURL}
	);
	my $method   = $options{method};
	my $request  = $options{request};
	$response    = $managewp->$request(
		method         => $method,
		request_params => \%method_options,
	);
};
if ($@) {
	die "ERROR! [$@]\n";
}
if ($response->{status} > 0) {
	die "ERROR! status [$response->{status}] message [$response->{message}]\n";
}
print "$response->{message}\n";

1;

__END__

=head1 NAME

managewp-client

=head1 DESCRIPTION

A command line interface to the ManageWP API. https://managewp.com/

=head1 SYNOPSIS

managewp-client [--method=path/to/method] [options...]

	Options:
	  -help		brief help message
	  -man		full documentation

=head1 OPTIONS

=over 8

=item B<-help>

Print a brief help message and exits.

=item B<-man>

Prints the manual page and exists

=item B<--method>

=over 8

=item B<EXAMPLE: partner/users/register>

Takes an email address as the argument, and attempts to register that user
with the ManageWP API.

	Options:
	  --user_email="user@example.com"	(required)
	  --user_pass="password"		(optional(default:random))
	  --additional_data="JSON"		(optional)
	  --plan_id="ID"			(optional)

	(http://managewp.com/docs/api/#registeruser)

THIS IS AN EXAMPLE: you can use any method available in the API this way.

=back

=back

=cut

