#!/usr/bin/perl

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 = "";

$LogFile = "/tmp/ClamAV.update.log";

$ClamUpdateCommand = "/usr/bin/freshclam";

$LockFile = "/tmp/ClamAVBusy.lock";

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

Sys::Syslog::openlog("ClamAV-autoupdate", 'pid, nowait', 'mail');

if (-x $ClamUpdateCommand) {
  &LockClamAV();
  $Command = "$ClamUpdateCommand --quiet -l $LogFile";
  $Command .= " --http-proxy $HTTPproxy" if $HTTPproxy;
  system($Command);
  &UnlockClamAV();
  Sys::Syslog::syslog('info', "ClamAV updated");
} else {
  Sys::Syslog::syslog('err',
                      "ClamAV updater $ClamUpdateCommand cannot be run");
}

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

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

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

