#!/usr/bin/perl
use strict;
use Getopt::Long;
use IPC::Open2;
use IO::Handle;


# config parameters
my $bconsole = '/usr/sbin/bconsole';
my $volume_dir = '/mnt/mybook/bacula/';
my $scratch_pool = "Scratch";

# don't edit below here
my (%opts, @purged, $pid);

GetOptions(\%opts,
           'verbose|v',
           'test');

my ($IN, $OUT) = (IO::Handle->new(), IO::Handle->new());

$pid = open2($OUT, $IN, $bconsole);

if (scalar (@purged = check_volumes())) {
  printf("Bacula reports the following purged volumes:\n\t%s\n",
         join("\n\t", @purged)) if ($opts{verbose});
  my $deleted = delete_volumes(@purged);
  print "$deleted volumes deleted.\n" if ($opts{verbose});
} elsif ($opts{verbose}) {
  print "No purged volumes found to delete.\n";
}

print $IN "exit\n";
waitpid($pid, 0);

exit (0);


sub check_volumes {
  my $dividers = 0;
  my (@purged, @row);

  print $IN "list volumes pool=${scratch_pool}\n";
  for (;;) {
    my $resp = <$OUT>;
    last if ($resp =~ /No results to list./);
    $dividers++ if ($resp =~ /^[\+\-]+$/);
    last if ($dividers == 3);
    @row = split(/\s+/, $resp);
    push (@purged, $row[3]) if ($row[5] eq 'Purged');
  }

  return (@purged);
}


sub delete_volumes  {
    my $count = 0;

    foreach my $vol (@_) {
      my $l;
      my $file = $volume_dir.$vol;

      if (-f $file) {
        $count++;
        if($opts{test}) {
          print "In test mode, skipping delete of volume $vol\n";
        } else {
          print "Deleting volume $vol from catalog ... " if ($opts{verbose});
        
          print $IN "delete volume=$vol yes\n";
          $l = <$OUT>;
          $l = <$OUT>;
          print "Done.\nDeleting volume $file from disk ... " if ($opts{verbose});
          my $result = unlink ($file);
          if($result < 1) {
            print "Error deleting volume $file from disk\n";
          }
        }
      }
      print "Done.\n" if ($opts{verbose});
    }

    return ($count);
  }

