#!/usr/bin/perl

use Sys::Syslog;

# Note that there are shell bugs in the kavupdater.sh where they have used
# == instead of = for comparing numbers.
$PackageDir = shift || "/opt/AVP";
$KavUpdateBinary  = "$PackageDir/kavupdater.sh";
$KavUpdateCommand = "cat $KavUpdateBinary | sed -e 's/==/=/g' | sh";

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

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

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

# Code for Kasperkey 5.0 first
if (-x "$PackageDir/bin/keepup2date") {
  &Lock();
  system("$PackageDir/bin/keepup2date");
  &Unlock();
  Sys::Syslog::syslog('info', "Kaspersky-5.0 updated");
  Sys::Syslog::closelog();
  exit 0;
}

# Code for Kaspersky 4.5 first, it's much simpler
if (-x "$PackageDir/bin/kavupdater") {
  &Lock();
  system("$PackageDir/bin/kavupdater");
  &Unlock();
  Sys::Syslog::syslog('info', "Kaspersky-4.5 updated");
  Sys::Syslog::closelog();
  exit 0;
}

# Now the code for older versions.
if (-x $KavUpdateBinary) {
  &Lock();
  $Command = "$KavUpdateCommand";
  #$Command .= " --http-proxy $HTTPproxy" if $HTTPproxy;
  $result = system($Command);
  &Unlock();
  if ($result) {
    Sys::Syslog::syslog('err', "Kaspersky update failed. You may need to add 'UpdatePath=http://www.kaspersky-labs.com/updates/' to your /opt/AVP/AvpUnix.ini");
    print STDERR "Kaspersky update failed. You may need to add\nUpdatePath=http://www.kaspersky-labs.com/updates/\nto your /opt/AVP/AvpUnix.ini\n";
  } else {
    Sys::Syslog::syslog('info', "Kaspersky updated");
  }
} else {
  Sys::Syslog::syslog('err', "Kaspersky updater $KavUpdateCommand could not be run");
  print STDERR "Kaspersky updater $KavUpdateCommand could not be run";
}

Sys::Syslog::closelog();
exit $result;

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

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

