#
# AVG Anti-Virus client/server mode
#
use IO::Socket;

if ($avgd) {
    my $port = 55555;
    my $inetaddr = inet_aton( "127.0.0.1" );
    $inetaddr = sockaddr_in( $port, $inetaddr );
    
    do_log( 2, "Using AVG Client/Server" );
    socket( \*sock, AF_INET, SOCK_STREAM, 6 )
      or die "Can't open socket: $!";
    connect( \*sock, $inetaddr )
      or die "Can't connect to AVG Anti-Virus daemon: $!";

    # now we read Greatings message: 220 Ready
    do {
	sysread( \*sock, $output, 256)
	  or die "sysread from AVG Anti-Virus daemon failed: $!";
    } while( not $output =~ /220 / );

    # then we set some parameters 
    my $command = "PARM -arc -rt -heur\r\n";
    syswrite(\*sock, $command, length($command))
      or die "syswrite to AVG Anti-Virus daemon failed: $!";
    sysread(\*sock, $output, 256)
      or die "sysread from AVG Anti-Virus daemon failed: $!";
    chomp($output);
    if ( substr($output,0,3) !=  "200" ) {
	do_log(2, "Can't set AVG Anti-Virus daemon parameters continue with defaults: $output");
    }

    opendir(DIR, "$TEMPDIR/parts/")
      or die "Can't open directory $TEMPDIR/parts/: $!";
    my @files = grep { -f "$TEMPDIR/parts/$_" } readdir(DIR);
    closedir(DIR) or die "Can't close directory: $!";
    chomp(@files);
    foreach my $file (@files) {
	$file = "$TEMPDIR/parts/$file";
	$command = "SCAN $file\n";
	syswrite(\*sock, $command, length($command))
	  or die "syswrite to AVG Anti-Virus daemon failed: $!";
	sysread(\*sock, $output, 256)
	  or die "sysread from AVG Anti-Virus daemon failed: $!";

	chomp($output);
	$output =~ s/[\n|\r]+//g;
	do_log(2,"AVG Anti-Virus daemon: $file - $output");
	last if ( substr($output,0,3) ==  "403" ); 
    }

    # tell server that's all
    $command = "QUIT\n";
    syswrite(\*sock, $command, length($command))
      or die "syswrite to AVG Anti-Virus daemon failed: $!";
    my $output2;
    sysread(\*sock, $output2, 256)
      or die "sysread from AVG Anti-Virus daemon failed: $!";

    close(\*sock) or die "AVG Anti-Virus daemon socket close failed: $!";

    if ( substr($output,0,3) ==  "403") {
	@virusname = ( $output =~ /infected: (.+)/g );
	$scanner_errors = 0;  # no errors, a virus was found
	do_virus();
    } elsif (substr($output,0,3) ==  "200") {
	$scanner_errors = 0;  # no errors, no viruses
    } elsif ($output == -1) {
	do_log(0,"Virus scanner failure: AVG Anti-Virus daemon - UNKNOWN STATUS (error code: $output)");
    } else {
	do_log(0,"Virus scanner failure: AVG Anti-Virus daemon - OOOPS (error code: $output)");
    }
}
