#!/usr/bin/perl
use strict;
use POSIX;

my($sysname, $nodename, $release, $version, $machine) = POSIX::uname();

if ($sysname =~ /freebsd/i) { 
	print "<b>FreeBSD cannot be supported due to lack of java support from Sun Microsystems.</b>\n";
	exit();
}

my $systemtype = "i586";
if ( $machine eq "x86_64" ) {
	$systemtype = "amd64";
}

my $javaversion = "1_5_0_05";
my $javafile = "jdk-${javaversion}-linux-${systemtype}.bin";
my $mirror = "http://layer1.cpanel.net/buildapache/1";
my $install = 0;

my $linkedname = $javaversion;
$linkedname =~ s/\-//g;
$linkedname =~ s/\_{1}/\./;
$linkedname =~ s/\_{1}/\./;

if ( ! -e "/usr/local/jdk/bin/java" ) {
  $install = 1;
} else {
	my $version = `/usr/local/jdk/bin/java -version 2>&1`;
	if ( $version =~ /"([^"]+)/) {
		if ( $1 ne $linkedname ) {
			$install = 1;
		}
	}
}


if ( $install == 1 ) {
	print "Java is not currently installed or is the wrong version, now (re)installing java on this system\n";
	chdir("/usr/local");
	$ENV{PATH}="/usr/local:$ENV{PATH}";
	if (! -e $javafile) {
		system("wget","-O","$javafile","http://layer1.cpanel.net/buildapache/1/$javafile");
	}
	chmod(0700,$javafile);
	if (my $pid = fork()) {
	      waitpid($pid,0);
	} else {
	      open3(\*JF,\*RDR,\*RDR,"./$javafile"); # Dan's Fix!
	      while(<RDR>) {
		      print;
		      if (/replace\s+/) { 
			      print JF "A\n";
		      } elsif (/above license terms/) {
			      print JF "yes\n";
		      }
	      }
	      close(RDR);
	      close(JF);
	      exit();
	}
	unlink("jdk");
	symlink("jdk${linkedname}","jdk");
	unlink("/usr/local/${javafile}");
} else {
	print "Java is currently up to date\n";
}
return 1;