#!/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;
my $api = BackupMaster::API->new({'caller' => "CLI $ENV{'USER'}"});
my @valid_methods = $api->get_methods();
usage("") if (defined $method && $method =~ m/(help|usage)/);
usage("Bad method name given!") unless (defined $method && grep (/^$method$/, @valid_methods));

print pretty($api->do($method,\%args));

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:
    backupmaster_cli method \@args
    Available methods: $pretty_methods
);
    print "$help";
    print "\n$msg\n";
    exit;
}
