#!/usr/bin/perl -w
#
# $Id: AVUpdate,v 1.1 2002/06/22 18:33:31 cvs Exp $
#
# AVUpdate: Check (and update) Antivirus databases
#
# Miguel Armas <kuko@maarmas.com>
#

#--------------------------------------------[ Initialization Section ]----

use strict;
use Getopt::Std;
use pifia;

#--------------------------------------------[ Configuration Section ]----- 
my $priority = "Warning";
my $alarm = "AVUpdate";

# Directory where we have the antivirus software
my $avdir = '<#$avdir#>';

# Update URL
my $avupdateurl = '<#$avupdateurl#>';

#--------------------------------------------[ Code Section ]----

# proactive flag indicates if we should take proactive measures, that is, 
# install/upgrade packages or just notify. Default is 0 but the global 
# variable proactive takes precedence
my $proactive='<#$proactive#>';

# Set a safe PATH
$ENV{'PATH'} = "/bin:/sbin:/usr/bin:/usr/sbin:/root/bin";

# Option declaration
use vars qw($opt_v $opt_n $opt_p $opt_q);
getopts('vnpq');

# Verbosity level. If not verbose, we shouldn't write any output unless 
# there is a problem. If quiet is set, we won't write ANY output (even if 
# there where errors). verbose has precedence
my $quiet = 1 if ($opt_q);
my $verbose = 1 if ($opt_v);
$quiet = 0 if ($verbose);

# proactive flag handling (parameters has precedence over global variable)
$proactive=1 if ($opt_p);
$proactive=0 if ($opt_n);

# THIS ALARM IS ALWAYS PROACTIVE!!!
$proactive=1;

# Flag to show that the situation was corrected (in the output)
my $corrected=($proactive ? "CORRECTED" : "");

if ($verbose) {
   print "\n\n";
   print "####################\n";
   print " Running kavupdater \n";
   print "####################\n";
}

my $cmd;
my $reload=0;

$cmd="cd $avdir; ./kavupdater -uik=$avupdateurl -o -y";

my @out=`$cmd 2>&1`;
if ($?) {
   print "ERROR: kavupdater exited with errors \n";
   print @out if ($verbose);
   exit 1;
}

print @out if ($verbose);

my @files = grep(!/identical/,grep(/^file/i,@out));
my $rulefiles="";
foreach (@files) {
    $_ =~ /file (.*?) /i;
    $rulefiles .= "$1 ";
}

if ($rulefiles) {
    print "CHANGES: $rulefiles $corrected\n";
    # If we have changes, and in proactive mode, we must reload service
    $reload = 1 if ($proactive);
    # Fix permissions
    system "chmod a+r /opt/AVP/bases/*";
}
else {
   print "NO CHANGES\n" if ($verbose);
}

# Restart service if needed
if ($reload) {
   if ($verbose) {
      print "Reloading avpd \n";
      $cmd="/etc/init.d/avpd restart";
   }
   else {
      $cmd="/etc/init.d/avpd restart >/dev/null 2>&1";
   }
   system("$cmd");
}
