#!/usr/bin/perl
use strict;
use warnings;

my $vconfig = "/etc/bacula/vchanger.conf";
my $bconfig = "/etc/bacula/bconsole.conf";
my $bconsole = "/usr/sbin/bconsole";
my @magazines = ();
my $changer = "";

## Read the vchanger config from disk
if ( -e "$vconfig" ) {
	my $content;
	open(my $fh, '<', "$vconfig" ) or die "cannot open file $vconfig"; {
		local $/;
		$content = <$fh>;
	}
	close ($fh);
	my @lines = split(/\n/, $content);
	foreach ( @lines ) {
		my $line = $_;
	
		if ( $line =~ m/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/ ) {
			print "vconfig - UUID Found: $1\n";
			push @magazines,$1;
			next;
		}

		if ( $line =~ m/changer_name.+?([\w-]+)/i ) {
			print "vconfig - Changer Name: $1\n";
			$changer = $1;
			next;
		}
	}
	print "vconfig - " . scalar(@magazines) . " magazines found.\n";

	## If we have any magazines, check which ones are active.
	if ( scalar(@magazines) ) {
		my $i = 1;
		foreach (@magazines) {
			my $status;
			if ( -l "/dev/disk/by-uuid/" . $_ ) {
				print "Status - Magazine $_ Online!\n";
				$status = 1;
			} else {
				print "Status - Magazine $_ Offline!\n";
				$status = 0;
			}
			my $sql = "UPDATE Media SET Enabled='${status}' WHERE VolumeName LIKE '${changer}_" . sprintf("%04d",$i) . "_%';";
			open (BCONSOLE, "|${bconsole} -c ${bconfig} >&/dev/null");
			print BCONSOLE "sqlquery\n${sql}\n.\n";
			close BCONSOLE;
			$i++;
		}
	}

} else {
	print "vchanger config not found";
	exit 1;
}
