#!/usr/bin/perl

use lib "/usr/share/BackupPC/lib";
use lib "/usr/local/BackupPC/lib";
use BackupPC::Lib;
use BackupPC::CGI::Lib;
use POSIX;
use JSON;
use Getopt::Long;

my $hosts    = 1;
my $entities = 0;
my $pretty   = 0;

GetOptions(
  "hosts"    => \$hosts,
  "entities" => \$entities,
  "pretty"   => \$pretty
);

# We need to switch to backuppc UID/GID
my $uid = getuid();
my $gid = getgid();
my (undef,undef,$bkpuid,$bkpgid) = getpwnam('backuppc');
setuid($bkpuid) if ($uid ne $bkpuid);
setgid($bkpgid) if ($gid ne $bkpgid);

my $bpc      = BackupPC::Lib->new();
my $hosts    = $bpc->HostInfoRead();
my $mainConf = $bpc->ConfigDataRead();

my $json;
@{$json->{data}} = ();

if ($entities) {
  my %entities = ();
  foreach my $host ( keys %$hosts ){
    if ( $host =~ m/^(?:vm_)?([^_]+)_.*/ and $1 ne 'vm' ) {
      $entities{$1}= 1;
    }
  }
  push @{$json->{data}}, { '{#BPC_ENTITY}' => $_ } foreach ( keys %entities );
} elsif ($hosts){
  foreach my $host ( keys %$hosts ){
    my $hostConf           = $bpc->ConfigDataRead($host);
    my $conf               = { %$mainConf, %$hostConf };
    my $warning            = $conf->{EMailNotifyOldBackupDays};
    my $errors             = ( defined $conf->{MaxXferError} ) ? $conf->{MaxXferError} : '0';
    my $monitoring         = $conf->{ZabbixMonitoring} || 1;
    my $sizeTooBigFactor   = $conf->{ZabbixSizeTooBigFactor} || 6;
    my $sizeTooSmallFactor = $conf->{ZabbixSizeTooSmallFactor} || 3;
    my $status             = ( $conf->{BackupsDisable} gt 0 or $monitoring eq '0' ) ? '0' : '1';
    push @{$json->{data}},
        {
            "{#BPCHOST}"              => $host,
            "{#BPCNOBACKUPWARNING}"   => $warning,
            "{#BPCMAXERROR}"          => $errors,
            "{#BPCSTATUS}"            => $status,
            "{#BPC_TOO_BIG_FACTOR}"   => $sizeTooBigFactor,
            "{#BPC_TOO_SMALL_FACTOR}" => $sizeTooSmallFactor,
        };
  }
}
print to_json( $json, { pretty => $pretty } );
exit(0);
