#!/usr/bin/perl

use strict;
use File::Temp ":mktemp";

my $basedir = mkdtemp("/tmp/rsnapshot-zfs-collect-data-XXXXXXXXXX");
my $cfgdir  = "/etc/rsnapshot-backup.d/enabled";

sub writefile ($$) {
	my ( $filename, $content ) = @_;
	my $outfile = $basedir ."/". $filename;
	open O,">",$outfile or do {
		warn "Can't open output file '$outfile': $!";
		return;
	};
	print O $content;
	close O;
}
sub readcommand ($) {
	my ( $cmd ) = @_;
	open F,"-|",@{$cmd} or die "Can't run '@{$cmd}': $!";
	my @F = <F>;
	close F;

	return @F;
}

opendir D,$cfgdir or die "Can't open config directory '$cfgdir': $!";
my @Jobs = sort map { s/^conf\.//; $_ } grep { /^conf\./ } readdir D;
closedir D;

##
## extract begin and end per backup job
##
for my $j ( @Jobs ) {
    my $logdir = "/var/log/rsnapshot-backup/".$j;
    opendir D,$logdir or do {
    	warn "Can't open log directory '$logdir': $!";
	next;
    };
    my $outfile = $basedir ."/b.". $j;
    open O,">",$outfile or do {
    	warn "Can't open output file '$outfile': $!";
	next;
    };
    my @Runs = sort grep { /^log-\d/ } readdir D;
    closedir D;
    for my $r ( @Runs ) {
	my $logfile = $logdir ."/". $r;
	open F,$logfile or do {
		warn "Can't open log file '$logfile': $!";
		next;
	};
	my @Log = map { s/^\[//; s/\].*$//; $_ } <F> ;
	chomp(@Log);
	my $newline = $Log[0] ." ". $Log[$#Log] ."\n";
	print O $newline;
    }
}

my @Plots = ();
my $cnt   = 0;
for my $j ( @Jobs ) {
    $cnt += 1;
    push @Plots,"'b.$j' using 1:($cnt) with linespoints title '$j'";
}
my $plots = join ",",@Plots;

writefile("b.CMD", << "EOF");
set title "backup log timestamps / end of rsnapshot run"
set grid mxtics
set terminal png medium size 1600,800
set output "b.CMD.png"
set xlabel "Date [y-m-d]"
set ylabel "Serial"
set xdata time
set timefmt "%Y-%m-%dT%H:%M:%S"
set format x "%Y\\n%m-%d"
set key outside
plot $plots
#pause -1
EOF

# end timestamps from log filenames
my @Out = readcommand([qw[ find /var/log/rsnapshot-backup -name log-2* ]]);
# sed | uniq 
my %OUT = map { s#.*/log-##; s/-/ /; $_ => 1 } @Out;
# sort | awk 'printf'
my @Out = map { # YYYYmmdd HHMMSS -> YYYYmmdd DECIMAL(HH:MM)
	my ($f1, $f2) = split / /;
	$_ = sprintf"%s %d.%02d", $f1, substr($f2,0,2), int (substr($f2,2,2)*5/3);
} sort keys %OUT;

writefile("b.ENDtimes", join("\n",@Out,""));
#OLD# find /var/log/rsnapshot-backup -name "log-2*" |
#OLD#     sed 's#.*/log-##;s/-/ /' |
#OLD#     sort | uniq |
#OLD#     awk '{ printf("%s %d.%02d\n",$1, substr($2,1,2),int (substr($2,3,2)*5/3)) } ' >  $BASEDIR/b.ENDtimes

writefile( "b.CMDtimes", << "EOF" );
set title "backup log filename timestamps / end of rsnapshot-backup run"
set grid mxtics
set terminal png medium size 1600,400
set output "b.ENDtimes.png"
set xdata time
set timefmt "%Y%m%d %H%M%S"
set format x "%Y\\n%m-%d"
#set key outside
# 23.58 == 23:35
plot "b.ENDtimes" using 1:2 with impulses, 23.58 title "23:35"
#pause -1
EOF
close O;

# init, start & end timestamps from log-error
my @Out = readcommand([qw[ /usr/local/bin/rsnapshot-zfs-parse-errorlog ]]);
writefile("b.CMDSTART+ENDtimes", join("",@Out) );

# zfs-snapshot timestamps
my @Out = readcommand([qw[ zfs list -t all ]]);
# sed | uniq 
my %OUT = map { 's#.*@[^.]*\.##;s/T/ /;s/Z .*$//'; $_ => 1 } grep { m#^/backup/hosts/# } @Out;
# sort | awk 'printf'
my @Out = map { # YYYYmmdd HHMMSS -> YYYYmmdd DECIMAL(HH:MM)
        my ($f1, $f2) = split / /;
	$_ = sprintf("%s %s %d.%02d\n",$1, $2, substr($2,0,2),int (substr($2,3,2)*5/3));
} sort keys %OUT;

writefile("b.ENDzfs", join "\n",@Out,"");
#OLD# zfs list -t all |
#OLD#     grep /backup/hosts/ |
#OLD#     sed 's#.*@[^.]*\.##;s/T/ /;s/Z .*$//' |
#OLD#     sort | uniq |
#OLD#     awk '{ printf("%s %s %d.%02d\n",$1, $2, substr($2,1,2),int (substr($2,4,2)*5/3)) } ' > $BASEDIR/b.ENDzfs

writefile("b.ENDzfs", << "EOF" );
set title "ZFS snapshot timestamps / end of rsync run"
set grid mxtics
set xdata time
set terminal png medium size 1600,400
set xlabel "Date [y-m-d]"
set ylabel "Duration [s]"
set output "b.ENDzfs.png"
set timefmt "%Y-%m-%d %H:%M:%S"
set format x "%Y\\n%m-%d"
#set key outside
# 23.58 == 23:35
plot "b.ENDzfs" using 1:3 with impulses, 23.58 title "23:35"
#pause -1
EOF

chdir $basedir or die "Can't chdir to basedir '$basedir': $!";
my @Cmd = "tar -czf - b.* | base64 | tee d";
system(@Cmd) and warn "Can't run '@Cmd': $!";

my @Cmd  = ("rm","-rf",$basedir); 
#system(@Cmd) and die "Can't run cleanup '@Cmd': $!";
