#!/usr/bin/env perl
#
# Script to look at the plugins registered within the Opsview database and 
# confirm they exist on filesystem.  This is to aid with migrations.
#
# Can only be used on the Primary Server (Orchestrator)
#
use 5.10.1;
use strict;
use warnings;
use autodie;

use lib '/opt/opsview/perl/lib/perl5';
use lib '/opt/opsview/corelibs/lib';

use Opsview::Schema;
use List::MoreUtils qw/ uniq /;

my $opsview=Opsview::Schema->my_connect;

my @missing;

push(@missing, check_plugins('Hostcheckcommands', 'plugin', '/opt/opsview/monitoringscripts/plugins'));
push(@missing, check_plugins('Servicechecks', 'plugin', '/opt/opsview/monitoringscripts/plugins'));
push(@missing, check_plugins('Hosts', 'event_handler', '/opt/opsview/monitoringscripts/eventhandlers', qr/(cluster|slave)_node_/));
push(@missing, check_plugins('Servicechecks', 'event_handler', '/opt/opsview/monitoringscripts/eventhandlers', qr/(cluster|slave)_node_/));
push(@missing, check_plugins('Notificationmethods', 'command', '/opt/opsview/monitoringscripts/notifications'));

for my $missing(sort (uniq(@missing))) {
	warn "$missing",$/;
}

sub check_plugins {
	my ($resultset, $field, $base, $ignore_regexp) = @_;

	my @result;

	my $checks = $opsview->resultset($resultset)->search;

	while(my $check=$checks->next) {
		next unless($check->$field);
		next if $ignore_regexp && $check->$field =~ m/$ignore_regexp/;

		# strip off any potential args, such as notifications options
		my ($command) = $check->$field =~ m/^(\S+)/;

		my $plugin=join('/', $base, $command);
		push(@result, $plugin) if ! -f $plugin;
	}

	return @result;
}
