#!/usr/bin/perl

# bacula_maint-daily.pl
# C M Reinehr
# 2 May 2008
#
# This script is to run daily befor any disk-based backup jobs are started,
# including the daily catalog backup. It's purpose is to identify all catalog
# volume records which have been marked as purged, delete these volume records
# from the catalog, and then delete the associated disk volumes in the /archive
# directory.

# Preliminaries

use strict;
use warnings;
use Time::Local;

my $Logfile     = "/var/log/bacula/weekly_maintenance";
my $DateTime    = localtime(time);
my @Line        = ();
my $Line        = "";
my @Volumes     = ();
my $Volume      = "";
my $Volumes     = "";
my $VolumeCount = 0;

open( LOGFILE, ">> $Logfile" ) or die "Error: $! on opening $Logfile.\n";

print LOGFILE "\nBegin: $DateTime\n\n";

#1 Get a list of volumes from the catalog, excluding tape volumes.

open( SYSTEM,
    "echo \"list volumes\nquit\" | bconsole -c /etc/bacula/bconsole.conf |" )
  or die $!;

foreach (<SYSTEM>) {
    @Line = split;
    if ( defined $Line[1] ) {
        if ( $Line[1] =~ /\d+/ && $Line[3] !~ /Tape:/ ) {
            push( @Volumes, [ $Line[1], $Line[3], $Line[5] ] );
        }
    }
}

close(SYSTEM);

#2 Prune catalog volumes.

open( SYSTEM, "| bconsole -c /etc/bacula/bconsole.conf > /dev/null" ) or die $!;

foreach $Line (@Volumes) {
    print SYSTEM "prune volume=@$Line[1]\nyes\n";
}

print SYSTEM "quit\n";

close(SYSTEM);

#3A Get new list, of purged volumes, from the catalog, excluding tape volumes.

undef @Volumes;

open( SYSTEM,
    "echo \"list volumes\nquit\" | bconsole -c /etc/bacula/bconsole.conf |" )
  or die $!;

foreach (<SYSTEM>) {
    @Line = split;
    if ( defined $Line[1] ) {
        if ( $Line[1] =~ /\d+/ && $Line[3] !~ /Tape:/ && $Line[5] =~ /Purged/ )
        {
            push( @Volumes, $Line[3] );
        }
    }
}

close(SYSTEM);

$VolumeCount = $#Volumes + 1;

print LOGFILE $VolumeCount, " Purged Volumes to be Deleted:\n";

foreach $Volume (@Volumes) {
    print LOGFILE "\t$Volume\n";
}

#3B Delete purged volume files from /archive directory.

$Volumes = join( ' /archive/', " ", @Volumes );

open( SYSTEM, "|xargs /bin/rm" );

print SYSTEM $Volumes;

close(SYSTEM);

#4 Remove volume records from Bacula catalog.

open( SYSTEM, "|bconsole -c /etc/bacula/bconsole.conf > /dev/null" );

foreach $Volume (@Volumes) {
    print SYSTEM "delete volume=$Volume\n", "yes\n";
}

print SYSTEM "quit\n";

close(SYSTEM);

#5 Clean up.
#
$DateTime = localtime(time);

print LOGFILE "\nEnd: $DateTime\n\n";

close(LOGFILE);

