#!/usr/bin/perl

use strict;
no utf8;

use lib "/usr/share/backuppc/lib";

use BackupPC::Lib;
use BackupPC::XS qw ( :all );
use BackupPC::View;
use Data::Dumper;
use Getopt::Std;
use Sys::Hostname;

die("BackupPC::Lib->new failed\n") if ( !(my $bpc = BackupPC::Lib->new) );

my $TopDir = $bpc->TopDir();
my $BinDir = $bpc->BinDir();
my %Conf   = $bpc->Conf();

my($Hostname, $Num, $Share, $View, @Backups);
my ($BkpHostname) = split /\./, hostname();

my %opts;

if ( !getopts("ih:n:s:l:", \%opts)) {
    usageAndExit();
}
my $limit = $opts{l} || 5;

sub usageAndExit
{
    print(STDERR "usage: $0 [-i] [-h host] [-n bkupNum] [-s shareName] [-l limit] \n");
    print(STDERR "    -i: output format suitable for telegraf+influx line protocol\n");
    print(STDERR "    -l: maximum number of backups per client\n");
    exit(1);
}

my $Hosts = $bpc->HostInfoRead($opts{h});

foreach my $hostname ( keys %$Hosts ) {
    my @backups = $bpc->BackupInfoRead($hostname);
    my $linecount = 0;
    foreach my $bkp ( reverse sort {$a->{num} <=> $b->{num}} values @backups ) {
        my $sizeMiB = $bkp->{size} / 1024 / 1024;

        my $duration = $bkp->{endTime} - $bkp->{startTime}; # duration in seconds
        my $startDate = POSIX::strftime("%Y-%m-%d %H:%M", localtime($bkp->{startTime}));
        my $endDate = POSIX::strftime("%Y-%m-%d %H:%M", localtime($bkp->{endTime}));

        if ($linecount < $limit) {
            if ($opts{i}) {
                if ($bkp->{size}) {
                    printf("backuppc,host=$BkpHostname,client=$hostname size=$bkp->{size}i,sizenew=$bkp->{sizeNew}i,sizenewcomp=$bkp->{sizeNewComp}i,nfiles=$bkp->{nFiles}i,nfilesnew=$bkp->{nFilesNew}i,type=\"$bkp->{type}\",duration=${duration}i,xfererrs=$bkp->{xferErrs}i $bkp->{endTime}000000000\n");
                    $linecount++;
                }
            } else {
                printf("$hostname@%d %s -> %s (%4ds) % 6d MiB (%s)\n", $bkp->{num}, ${startDate}, ${endDate}, ${duration}, $sizeMiB, $bkp->{type});
                $linecount++;
            }
        }
    }
}

# vim: tabstop=4 shiftwidth=4 softtabstop=4 expandtab
