#!/usr/bin/perl --      -*- quick-hack -*-
#
# generate CSV output (actually, I'll use "|" as separator) for something
# like:
# hostname|date/time|size in MB|level|duration(min)
# almost as requested by John Rouillard.
# You might also want the backup number. See the comment below.

use lib '/usr/share/backuppc/lib'; # change to match your installation
use BackupPC::Lib;
use POSIX;

my $bpc = new BackupPC::Lib ('', '', '', 0)
  or die "Can't create BackupPC object!\n";
my @hosts;                         # array of hosts
my $hostinfo;                      # pointer to hash of per host information
my @backups;                       # info on all backups of one host
my $dt;                            # output fields for loop iteration: date/time
my $size;                          # ... size
my $level;                         # ... level
my $duration;                      # ... duration in minutes

$hostinfo = $bpc->HostInfoRead ();
@hosts = sort keys %$hostinfo;
# print 'hosts =>', (join '<, >', @hosts), "<=\n";

host:
foreach my $host (@hosts) {
  @backups = $bpc -> BackupInfoRead ($host)
    or die "Invalid hostname '$host' or other error!\n";
  foreach my $backup (@backups     ) {
    #                          [-1]   <- add that in the line above for only
    #                                    the most recent backup of each host
    # exploring the data structure:
    # print "$host=>", join (',', map { "$_=$backup->{$_}" } sort keys %$backup), "<=\n";
    $dt       = POSIX::strftime ('%Y-%m-%d %H:%M',
				 localtime $backup -> {startTime});
    $size     = int ($backup -> {size} / 1024 / 1024 + 0.5); # MB, rounded
    $level    = $backup -> {level};
    $duration = int (($backup->{endTime} - $backup->{startTime}) / 60 + 0.5);
#     printf "[%4d] %-20.20s %-16.16s %10d %3d %4d\n",
# 	   $backup -> {num}, $host, $dt, $size, $level, $duration;
#          ^^^^^^^^^^^^^^^^ Backup number. This is the comment below.
    print +(join '|', $host, $dt, $size, $level, $duration), "\n";
  }
}
