#!/usr/bin/env perl
use warnings;
use strict;
use FindBin;
use lib "$FindBin::RealBin/../lib";
use BackupMaster::API;
use BackupMaster::Pretty 'pretty';

my ($method, %args) = @ARGV;
usage("no method provided") if ! defined $method;

my $user = defined($ENV{USER}) ? $ENV{USER} : "user.$<";
my $api = BackupMaster::API->new({'caller' => "CLI $user"});
my @valid_methods = $api->get_methods();

usage("") if ( $method =~ m/^(help|usage|methods)$/);

if( grep (/^$method$/, @valid_methods)){
    print pretty($api->do($method,\%args));
    exit;
}

my $modules = $api->get_modules();
if(grep (/^$method$/, keys %$modules)){
    print pretty($api->do('describe', { method => $method }));
    exit;
}

usage("Bad method name given!");

sub usage {
    my $msg = shift // "";
    my $pretty_methods = "";
    my $sorted_methods;
    foreach my $method (@valid_methods){
        my $category = $method =~ m/([\w_]+)(_\w+)$/ ? $1 : "znone";
        push @{$sorted_methods->{$category}}, $method;
    }
    foreach my $category (sort(keys %{$sorted_methods})){
        $pretty_methods .= "\n       ";
        foreach my $method (@{$sorted_methods->{$category}}){
            $pretty_methods .= " $method";
        }
    }
    my $help  = qq(Usage:
    $0 method \@args
    Available methods: $pretty_methods
);
    print "$help";
    print "\n$msg\n";
    exit;
}
