#!/usr/bin/perl

use strict;

my %urls = (
	 Linux 	      => 'https://www.zend.com/free_download/download?product=optimizer&version=3.0.1&binary=ZendOptimizer-3.0.1-linux-glibc21-i386.tar.gz',
#	 Linux 	      => 'http://www.zend.com/store/getfreefile.php?pid=13&zbid=919&iagree=1',
         Linux64      => 'http://www.zend.com/store/getfreefile.php?pid=13&zbid=855&iagree=1',
	'FreeBSD 5.x' => 'http://www.zend.com/store/getfreefile.php?pid=13&zbid=847&iagree=1',
	'FreeBSD 4.x' => 'http://www.zend.com/store/getfreefile.php?pid=13&zbid=846&iagree=1'
);

system("/scripts/phpini");

if (! -e "/usr/bin/lynx" && ! -e "/usr/local/bin/lynx") {
	system("/scripts/ensurerpm","lynx","wget");
}

my $dc;
if (-e "/usr/bin/wget" || -e "/usr/local/bin/wget") {
	$dc = 'wget -O -';
} else {
	$dc = 'lynx -source';
}

setupzenddir();
my $zendtar = downloadzend();


open(ZTAR,">/home/cpzendinstall/zendopt.tar.gz");
print ZTAR $zendtar;
close(ZTAR);

my $file = `tar tfz /home/cpzendinstall/zendopt.tar.gz`;
my @FILES=split(/\n/, $file);
my $dir = $FILES[0];

system("tar","xfz","/home/cpzendinstall/zendopt.tar.gz");

if (-d "/home/cpzendinstall/$dir") {
	chdir("/home/cpzendinstall/$dir");
	system("./install");
} else {
	die "Unable to download zend optimizer.";
}

sub setupzenddir {
	system("rm","-rf","/home/cpzendinstall");
	system("mkdir","/home/cpzendinstall");
	chdir("/home/cpzendinstall");
}

sub downloadzend {
	my $zendtar;
	my $system;
	my $system64;
	print "Downloading Zend Optimizer.....";
	chomp($system = `uname -s`);
	if ($system =~ /freebsd/i) {
		my $fbsdurl = $urls{'FreeBSD 4.x'};
		if(`uname -r` =~ m/^5/) { $fbsdurl = $urls{'FreeBSD 5.x'}; }
		$zendtar = `${dc} "$fbsdurl"`;
	} else {
		chomp($system64 = `uname -p`);
		if ($system64  =~ /x86_64/i) {
		print "Downloading 64bit\n";
		$zendtar = `${dc} "$urls{Linux64}"`;
		} else {
			$zendtar = `${dc} "$urls{Linux}"`;
		}
	}
	print "Done\n";
	return($zendtar);
}


