#!/usr/bin/perl --      -*- quick-hack -*-
#
# run manually:
# su backuppc -c ./BackupPC_daily.pl | mail -s 'BackupPC daily stats' admin@domain.tld
#
# or add to crontab:
# 0 8 *	* *	su backuppc -c /*path to script here*/BackupPC_daily.pl | mail -s 'BackupPC daily stats' admin@domain.tld

use lib '/usr/local/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

my $xferErrs;
my $xferBadShare;
my $xferBadFile;
my $tarErrs;

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

print join(' ', POSIX::strftime ('%Y-%m-%d %H:%M',localtime(time))), "\n";

printf "%-6s %-22.22s %-16.16s %6s %5s %8s %1s %4s %5s %4s %3s\n",
    "", "", "", size, "", duration, "|", xfer, Share, File, tar;
printf "%-6s %-22.22s %-16.16s %6s %5s %8s %1s %-4s %-5s %-4s %3s\n",
    "number", "hostname", "date/time", "(MB)", "level", "(min)", "|", Err, Err, Err, Err;

host:
foreach my $host (@ARGV ? @ARGV : @hosts) {
  @backups = $bpc -> BackupInfoRead ($host)
    or die "Invalid hostname '$host' or other error!\n";
  foreach my $backup (@backups [-1]) {
    #                          [-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);

    $xferErrs = $backup -> {xferErrs};
    $xferBadShare = $backup -> {xferBadShare};
    $xferBadFile = $backup -> {xferBadFile};
    $tarErrs = $backup -> {tarErrs};

     printf "[%4d] %-22.22s %-16.16s %6d %5d %8d %1s %4d %5d %4d %3d\n",
 	   $backup -> {num}, $host, $dt, $size, $level, $duration, "|", $xferErrs, $xferBadShare, $xferBadFile, $tarErrs;

    if ((time-$backup->{endTime})>86400){		#i.e endIime older than 1d
	printf "*WARNING* Backup is outdated!\n";
    }

    if (($xferErrs+$xferBadShare+$xferBadFile+$tarErrs)!=0){
	printf "*WARNING* Backup with ERRORs!\n";
        # XferLOG addition would go here, probably add some \n's above
    }
  }
$hostcount+=1;
}
print "\n$hostcount hosts\n";
