#!/usr/bin/perl -w
use Net::FTP;

###############################################################################

sub by_number{
	$a1=$a;
	$b1=$b;
	$a1=~tr/a-z,A-Z,.//d;
	$b1=~tr/a-z,A-Z,.//d;
  if ($a1 < $b1) {
		return -1;
  } elsif ($a1 == $b1) {
		return 0;
  } elsif ($a1 > $b1) {
		return 1;
	}
}

###############################################################################

my $ftp;
my $ftp_host="download.trendmicro.com";

# connect
print "Attempting to connect to ",$ftp_host,"...";
if ($ftp = Net::FTP->new("$ftp_host", Timeout=>30)){
	print "Connected!\nAttempting to log in...";
}else{
	print "Couldn't connect!\n";
	exit 5;
}

# login anonymously
if ($ftp->login()){
	print "Login successful!\n";
}else{
	print "Login failed!\n";
	exit 10;
}
# change dir
if ($ftp->cwd("/products/pattern/")) {
	print "Directory change successful.\n";
}else{
	print "Directory change failed!\n";
}
$ftp->binary;

# look for the files we're after
print("Looking for updates...\n");
@lines=$ftp->ls("l*zip");
if((scalar(@lines)!=0)){
	#foreach $line (@lines){
	#	$line=substr($line,55);
	#}

	@lines=sort by_number @lines;
	$length=@lines;
	$fileName=$lines[$length-1];
	print("Downloading $fileName...");
	if ($ftp->get($fileName,"/home/kynan/$fileName")){
		print "retrieved $fileName.\n"
	}else{
		print "couldn't retrieve $fileName!\n"
	}
}else{
	print("No files found!\n")
}

# done - disconnect
if ($ftp->quit){
	print "Disconnected!\n";
}else{
	print "Couldn't disconnect nicely!\n";
}
exit;