#!/usr/bin/perl

#
# ClamAV updater. Original code by Julian Field. Timeout code by
# Alessandro Bianchi. Timeout code is not perfect but should be okay.
#

use Sys::Syslog;

# If you have a web proxy or cache server, put its value in the next line
# in the syntax "full.host.name:port".
$HTTPproxy = "";

$PackageDir = shift || "/opt/vba/vbacl";

$UpdateCommand = "$PackageDir/vbaupdx";

$LockFile = shift || "/var/spool/MailScanner/incoming/Locks/vba32Busy.lock";

$LOCK_SH = 1;
$LOCK_EX = 2;
$LOCK_NB = 4;
$LOCK_UN = 8;

eval { Sys::Syslog::setlogsock('unix'); }; # This may fail!
Sys::Syslog::openlog("vba32-autoupdate", 'pid, nowait', 'mail');

if (-x $UpdateCommand) {
  # Timeout prevention
  $SIG{ALRM} = sub { die "timeout"};

  &Lock();
  eval {
    alarm 300;
    $Command = "$UpdateCommand $PackageDir";
    $Command .= " --http-proxy $HTTPproxy" if $HTTPproxy;
    $retval = &Update($Command); # system($Command)>>8;
    &Unlock();
    alarm 0;
  };

  if ($@) {
    if ($@ =~ /timeout/) {
      # We timed out!
      &Unlock();
      Sys::Syslog::syslog('err', "WARNING vba32 update timed out");
      alarm 0;
    }
  } else {
    alarm 0;
    if ($retval == 0 ) {
      Sys::Syslog::syslog('info', "vba32 updated");
    }
  }
} else {
  Sys::Syslog::syslog('err', "vba32 updater $UpdateCommand cannot be run");
}

Sys::Syslog::closelog();
exit 0;

sub Lock {
	open(LOCK, ">$LockFile") or return;
	flock(LOCK, $LOCK_EX);
	print LOCK "Locked for updating vba32 definitions by $$\n";
}

sub Unlock {
	print LOCK "Unlocked after updating vba32 definitions by $$\n";
	flock(LOCK, $LOCK_UN);
	close LOCK;
}

sub Update {
  my($cmd) = @_;

  open(CMD, "$cmd 2>&1 |") or return $?;

  while(<CMD>) {
    chomp;
    Sys::Syslog::syslog('err', "vba32 update warning: $_")
      if /warning|error|fatal/i;
  }
  close CMD;

  return $?>>8;
}

