#!/usr/bin/perl
#
# $Revision: 1.9 $
# Copyright 2015 Teleflora.
#
# Update BBj to Rev 15.00
#

use strict;
use warnings;
use English;
use Getopt::Long;
use POSIX;


my $HELP = 0;
my $VERSION = 0;
my $BBJ15 = 0;

my $OS = "";
my $ARCH = "";
my $POSDIR = "";
my $pid = 0;

my $authnumtest = "";
my $serialnumtest = "";
my $hostnametest = "";
my $hostidtest = "";
my $Auth_Number = "";
my $Serial_Number = "";
my $Host_Name = "";
my $Host_ID = "";
my $bbjinstallsettings15 = "";
my $config_ini = "";
my $returnval = 0;
my $BBJ = "";
my $JDK_X64 = "";
my $JDK_X86 = "";
my $java_ver = "";
my $java_rel = "";
my $BBJ_INSTALL_FILE = "";
#
# "0" means "do not install"
# "1" means "do install"
# "-1" means "default", which is dictated later on by other factors
# Barring any other factors, "-1" means "do".
#
my %installflags = (
        java => -1,
);

GetOptions(
	"help" => \$HELP,
	"version" => \$VERSION,
	"bbj15" => \$BBJ15,
        "java!" => \$installflags{'java'},
);



# --version
if($VERSION != 0) {
	print("$0 " . '$Revision: 1.9 $' . "\n");
	exit(0);
}

# --help
if($HELP != 0) {
	usage();
	exit(0);
}

# Which Processor are we using?
open(PIPE, "uname -i |");
while(<PIPE>) {
	if(/i.86/) {
		$ARCH = "x86";
	}
	if(/x86_64/) {
		$ARCH = "x64";
	}
}
close(PIPE);

$POSDIR = "/usr2/bbx";


# We must be root to do these things.
if($EUID == 0) {

	loginfo("Starting update_bbj.pl " . '$Revision: 1.9 $' . "\n");
	# --bbj15
	if($BBJ15 != 0) {
		loginfo("Installing BBj Rev 15.00 Software Dependencies...");
		$BBJ = "bbj15update.tar";
		$BBJ_INSTALL_FILE = "BBj1511_09-28-2015_1801.jar";

		my $java_rel = "8u45";
		my $java_ver = "1.8.0_45";

		$JDK_X64 = "jdk-" . $java_rel . "-linux-x64.tar.gz";
		$JDK_X86 = "jdk-" . $java_rel . "-linux-i586.tar.gz";

        	# Install Java
        	if ($installflags{'java'} != 0) {

			if (is_java_already_installed($java_ver)) {
				loginfo("Java $java_ver is installed, skipping Java update");
			}
			else {
				# After the Java distribution file is downloaded,
				# an rpm is extracted and any previous rpm files must
				# be removed before proceeding or "unzip" will want to
				# interact with the user hanging the process.
				loginfo("Removing old Java rpm packages...");
				mysystem("rm /tmp/jre-$java_rel-linux*.rpm");
				mysystem("rpm -e jre-$java_ver");
				mysystem("rpm -e jdk-$java_ver");

				loginfo("Java $java_ver is NOT installed, beginning Java update");
				install_java();
			}
        	}

		else {
                	loginfo("--nojava specified. Skipping Java Update.");
        	}

		install_bbj15_packages();
	}
}



exit(0);
###################################################
###################################################
###################################################


sub usage
{
	print(<< "EOF");
$0 Usage:

$0 --version
$0 --help
$0 --bbj15            Installs BBj 15
$0 --java / --nojava  Do / Do not install Java 1.8.0_45. Defaults to --java.

EOF

}


#
# Install BBj v15
#
sub install_bbj15_packages
{
	my $line = "";

	# Install BBj
	if(-d "/usr2/basis") {
		loginfo("Moving current /usr2/basis/ to /usr2/basis-old/...");
		mysystem("rm -rf /usr2/basis-old");
		mysystem("cp -r /usr2/basis /usr2/basis-old");
		if($returnval != 0) {
			logerror("Terminating update_bbj with return code $returnval.");
			exit($returnval);
		}
	} else {
		loginfo("/usr2/basis/ did not previously exist...");
	}


	
	loginfo("Installing BBj v15...");
	if(! -f "/tmp/$BBJ.gz") {
		system("wget --proxy=off --cache=off -O /tmp/$BBJ.gz http://tposlinux.blob.core.windows.net/rtibbjupdate11/$BBJ.gz");
		if(! -f "/tmp/$BBJ.gz") {
			logerror("Could not download file http://tposlinux.blob.core.windows.net/rtibbjupdate11/$BBJ.gz");
			exit(1);
		}
	}
#####
#Basis license Info
####

	loginfo("Getting AuthNumber for Basis License......");
 	if (-f "//usr2/basis/blm/Register.properties")
	{
	my $authnumtest = `grep AuthNum= /usr2/basis/blm/Register.properties 2>/dev/null`;
	chomp $authnumtest;
	my @authnum=split(/\=/, $authnumtest);
	my $Auth_Number=$authnum[$#authnum];
	loginfo("Auth_Number = $Auth_Number");

	loginfo("Getting Serial Number..... ");	
	my $serialnumtest = `grep SerialNum= /usr2/basis/blm/Register.properties 2>/dev/null`;
	chomp $serialnumtest;
	my @serialnum=split(/\=/, $serialnumtest);
	my $Serial_Number=$serialnum[$#serialnum];
	loginfo("Serial Number = $Serial_Number");
	
	loginfo("Getting HostName .....");
	my $hostnametest = `grep HostName /usr2/basis/blm/Register.properties 2>/dev/null`;
	chomp $hostnametest;
	my @hostname=split(/\=/, $hostnametest);
	my $Host_Name=$hostname[$#hostname];
	loginfo("Host Name = $Host_Name");
	
	loginfo("Getting Composite.....");
	my $hostidtest = `grep HostID /usr2/basis/blm/Register.properties 2>/dev/null`;
	chomp $hostidtest;
	my @hostid=split(/ID\=/, $hostidtest);
	my $Host_ID=$hostid[$#hostid];
	loginfo("Host ID = $Host_ID");

	my $bbjinstallsettings15 = "
################################################################################
# BASIS Installation and Configuration Wizard options for BBj 11.12 and higher
#
#
# A forward slash or two back slashes should be used when specifying directories or files
# Passwords will be encrypted when recorded.
#
#
################################################################################
# Wizard Settings
#
# The following variables set whether or not to run various BASIS
# installation and configuration wizards after the installation of the software.
# Setting a value to [interactive] will cause the specified wizard to be run
# interactively. Setting a value to [silent] will cause the specified wizard to
# be run silently. Setting a value to [off] will prevent that wizard from being run.
# The UAC wizard will only be run on Windows machines in which UAC is enabled. The
# license selection and finish wizards can not be run silently.
#
# The following value can be [interactive] [silent]. The default is [interactive].
INSTALL_WIZARD=silent
# The following values can be [off] [interactive] [silent]. The default is [off].
UAC_WIZARD=off
LICENSE_SELECTION_WIZARD=silent
LICENSE_REGISTER_WIZARD=silent
LICENSE_INSTALL_WIZARD=silent
BBJ_BRAND_WIZARD=off
BBJ_CFG_STARTUP_WIZARD=silent
BBJ_START_STOP_WIZARD=silent
BLM_CFG_STARTUP_WIZARD=silent
BLM_START_STOP_WIZARD=off
EM_WIZARD=off
FINISH_WIZARD=silent
#
################################################################################
# Global Wizard Detail Settings
#
# The following value can be [en] [nl] [fr] [de] [it] [es] [sv].
# The default is the current locale language.
LANGUAGE=en
#
# The splash image can be a png or jpg and can be found in the installable jar or on disk. By default the BASIS splash image will be used.
# The following value can be [none] which will skip the splash window. A GUI environment is needed to display the splash window.
SPLASH_IMAGE=
#
################################################################################
# Install Wizard Detail Settings
#
# The following value can be [true] [false]. Default is [false].
INSTALL_LICENSE_AGREE=true
# Specifies the installation target directory
INSTALL_TARGET_DIRECTORY_NON_WIN=/usr2/basis/
# Specifies the java directory
INSTALL_JAVA_DIRECTORY_NON_WIN=/usr/java/latest/
# The following value can be [true] [false]. Default is [false].
INSTALL_CUSTOM=false
# Specifies the comma separated custom features to install. The default is to install all available features
INSTALL_CUSTOM_FEATURES=
# The following value can be [true] [false]. Default is [false].
INSTALL_WEB_START_INSTALLATION=true
# The following properties are used to configure Web Start
# Specifies if a certificate should be generated in order to sign Web Start jars. This value can be [true] [false]. Default is [true].
INSTALL_GENERATE_CERTIFICATE=true
# Specifies the company name to use when generating a Web Start certificate
INSTALL_YOUR_COMPANY_NAME=Teleflora
# Specifies the Jetty host to use when generating a Web Start certificate. By default the web server host in BBj.properties will be used if it exists, otherwise the external IP address of the machine will be used.
INSTALL_JETTY_HOST=
# Specifies the Jetty port to use when generating a Web Start certificate. By default the web server port in BBj.properties will be used if it exists, otherwise 8888 will be used.
INSTALL_JETTY_PORT=
# Specifies if a CA certificate should be used to sign Web Start jars. This value can be [true] [false]. Default is [false].
INSTALL_USE_CA_CERTIFICATE=false
# Specifies the keystore to use when using a CA certificate to sign Web Start jars.
INSTALL_KEYSTORE=
# Specifies the keystore password to use when using a CA certificate to sign Web Start jars.
INSTALL_KEYSTORE_PASSWORD=
# Specifies the private key to use when using a CA certificate to sign Web Start jars.
INSTALL_PRIVATE_KEY=
# Specifies the private key password to use when using a CA certificate to sign Web Start jars.
INSTALL_PRIVATE_KEY_PASSWORD=
# The following properties can be specified to run a BBj program at the installation finish. The variable {dollarsign}InstallDir can be used in values that contain a path to be relative to the BBj installation directory.
INSTALL_BBEXEC_PROGRAM=
INSTALL_BBEXEC_CONFIG=
INSTALL_BBEXEC_WORKING_DIR=
INSTALL_BBEXEC_TERMINAL=
INSTALL_BBEXEC_USER=
# The following value can be [true] [false]. Default is [false].
INSTALL_BBEXEC_QUIET=
INSTALL_BBEXEC_APP_NAME=
INSTALL_BBEXEC_APP_USER_NAME=
INSTALL_BBEXEC_CLASSPATH_NAME=
# The following value can be [true] [false]. Default is [false].
INSTALL_BBEXEC_SECURE=
INSTALL_BBEXEC_LOCAL_PORT=
INSTALL_BBEXEC_REMOTE_PORT=
INSTALL_BBEXEC_ARGS=
# The following value can be [true] [false]. Default is [false].
INSTALL_BBEXEC_SYNC=
# The following value default is 6, a wait of 30 seconds will be performed between retries, for a total default retry time of 3 minutes.
INSTALL_BBEXEC_NUM_RETRIES=
# The following value can be [true] [false]. Default is [false].
INSTALL_BBEXEC_SHOW_PROGRESS=
# The following value can be [true] [false]. Default is [false].
INSTALL_BBEXEC_ALLOW_CANCEL=
INSTALL_BBEXEC_PROGRESS_TITLE=
INSTALL_BBEXEC_PROGRESS_TEXT=
INSTALL_BBEXEC_FAILURE_TITLE=
INSTALL_BBEXEC_FAILURE_TEXT=
#
################################################################################
# UAC Wizard Detail Settings
#
# The following value can be [true] [false]. Default is [false].
UAC_ELEVATE=
#
################################################################################
# License Selection Wizard Detail Settings
#
# The license regsistration, install, and brand wizards will
# be automatically added, depending on the user selection.
# The following value can be [register] [install] [blm]. Default is [register]
LICENSE_SELECTION_OPTION=register
#
################################################################################
# License Registration Wizard Detail Settings
#
# The following value can be [true] [false]
LICENSE_REGISTER_DEMOLIC=false
LICENSE_REGISTER_COMPANYNAME=Teleflora
LICENSE_REGISTER_FIRSTNAME=JJ
LICENSE_REGISTER_LASTNAME=Blankenship
LICENSE_REGISTER_EMAIL=jblankenship\@teleflora.com
LICENSE_REGISTER_FAX=
LICENSE_REGISTER_PHONE=800.621.8324
# The following are only used when LICENSE_REGISTER_DEMOLIC=[false]
# The following values can be left empty, so that they will be dynamically populated
LICENSE_REGISTER_SERIALNUM=$Serial_Number 
LICENSE_REGISTER_AUTHNUM=$Auth_Number
LICENSE_REGISTER_HOSTNAME=$Host_Name
LICENSE_REGISTER_HOSTID=$Host_ID
# The following are only used when LICENSE_REGISTER_DEMOLIC=[true]
LICENSE_REGISTER_DEMOUSERCOUNT=
LICENSE_REGISTER_DEMOSERIALNUM=
LICENSE_REGISTER_DEMOAUTHNUM=
# The following value can be [auto] [web] [email] [phone] [other]. Default is [auto]
LICENSE_REGISTER_REGMETHOD=auto
# The following value can be [web] [email]. Default is [web]. This setting is not
# used if LICENSE_REGISTER_REGMETHOD=[auto]
LICENSE_REGISTER_DELMETHOD=web
# The following value can be [true] [false]. Default is [true].
LICENSE_REGISTER_COUNTRYUSACANADA=true
# The following value can be [true] [false]. Default is [false].
LICENSE_REGISTER_WANTINFO=false
# The following value can be [true] [false]. Default is [false].
LICENSE_REGISTER_NOTEBOOK=false
# The following value is only used when LICENSE_REGMETHOD=[phone].
# Specify path and file name, a ASCII text file will be generated by the wizard.
LICENSE_REGISTER_PHONEFILE=
# The following value is only used when LICENSE_REGMETHOD=[other].
# Specify path and file name, a ASCII text file will be generated by the wizard.
LICENSE_REGISTER_OTHERFILE=
#
################################################################################
# License Install Wizard Detail Settings
#
# The following value can be [true] [false]. Default is [false].
LICENSE_INSTALL_ENTERLICINFO=false
# The following is only used when LICENSE_INSTALL_ENTERLICINFO=[false].
# Specify the location of an existing license file.
LICENSE_INSTALL_LICENSEFILE=/usr2/basis/blm/
# The following are only used when LICENSE_INSTALL_ENTERLICINFO=[true].
LICENSE_INSTALL_FEATURE=
LICENSE_INSTALL_ENCRYPTCODE=
LICENSE_INSTALL_LICREV=
LICENSE_INSTALL_HOSTID=
LICENSE_INSTALL_EXPDATE=
LICENSE_INSTALL_CHECKSUM=
LICENSE_INSTALL_NUMUSERS=
LICENSE_INSTALL_SERIALNUM=
#
################################################################################
# BBj Brand Wizard Detail Settings
#
# The following value can be [true] [false]. Default is [false].
BBJ_BRAND_REMOTE=false
BBJ_BRAND_SERVERNAME=
#
################################################################################
# BBj Configuration Startup Wizard Detail Settings
#
# On Windows the following value can be [service] [login] [manual]. Default is [service].
# On Non-Windows the following value can be [init] [manual]. Default is [init].
BBJ_CFG_STARTUP_TYPE=init
BBJ_CFG_STARTUP_TYPE_NON_WIN=init
BBJ_CFG_STARTUP_USERACCOUNT=root
BBJ_CFG_STARTUP_PASSWORD=
# The following value is only used when run as a service and can be [auto] [manual] [disabled]
BBJ_CFG_STARTUP_SERVICESTARTUPTYPE=auto
#
################################################################################
# BBj Services Wizard Detail Settings
#
# The following value can be [start] [stop] [restart]
BBJ_START_STOP_STARTUP=start
# The following values are only used if BBJ_START_STOP_STARTUP=[stop].
# The following default value is [localhost]
BBJ_START_STOP_SERVERNAME=localhost
# The following default value is [2002]
BBJ_START_STOP_ADMINPORT=2002
# The following default value is [admin]
BBJ_START_STOP_USERNAME=
# The following default value is [admin123] only in silent mode
BBJ_START_STOP_USERPASSWORD=
# The following default value is [false]
BBJ_START_STOP_WAITFORCLIENTS=false
#
################################################################################
# BLM Configuration Startup Wizard Detail Settings
#
# On Windows the following value can be [service] [login] [manual]. Default is [service].
# On Non-Windows the following value can be [init] [manual]. Default is [init].
BLM_CFG_STARTUP_TYPE=init
BLM_CFG_STARTUP_TYPE_NON_WIN=init
# The following value can be [auto] [manual] [disabled]
BLM_CFG_STARTUP_SERVICESTARTUPTYPE=auto
#
################################################################################
# BLM Services Wizard Detail Settings
#
# The following value can be [start] [stop] [restart]
BLM_START_STOP_STARTUP=start
#
################################################################################
# EM Wizard Detail Settings
#
EM_CURADMINPASSWORD=
EM_NEWADMINPASSWORD=
EM_SERVERNAME=
EM_ADMINPORT=
";
##EOF
		open(BBJINST, "> /tmp/bbjinstallsettings15.txt");
        	print BBJINST $bbjinstallsettings15;
		close(BBJINST);
	}
         else {
                loginfo("No Register.properties file exists...");
        }

loginfo("Removing existing /usr2/bbx/config/config.ini.....");
	mysystem("rm -r /usr2/bbx/config/config.ini");
loginfo("Creating new /usr2/bbx/config/config.ini.....");
$config_ini = "
[RTI14]
DATEFORMAT.1=
DATEFORMAT.2=
RWUSERS=
DATESUFFIX.2=
CREATETABLETYPE=6
DATESUFFIX.1=
DICTIONARY=/usr2/bbx/dict/
DATABASE=RTI14
ROUSERS=
TRUNCATEIFTOOLONG=Y
ADVISORYLOCKING=Y
ADMINUSERS=
DATECOLUMNSSORTED=false
ACCESSPOLICY=ALL
Y2KWINDOW.1=0
DATESUFFIX=
Y2KWINDOW.2=0
CHARSET=
READONLY=N
Y2KWINDOW=0
DATA=/usr2/bbx/bbxd/
DATEFORMAT=
AUTO_ANALYZE_TABLES=false

[RTI]
DATEFORMAT.1=
DATEFORMAT.2=
RWUSERS=
DATESUFFIX.2=
CREATETABLETYPE=6
DATESUFFIX.1=
DICTIONARY=/usr2/bbx/odbc_dict/
DATABASE=RTI
ROUSERS=
TRUNCATEIFTOOLONG=Y
ADVISORYLOCKING=Y
ADMINUSERS=
DATECOLUMNSSORTED=false
ACCESSPOLICY=ALL
Y2KWINDOW.1=0
DATESUFFIX=
Y2KWINDOW.2=0
CHARSET=
READONLY=N
Y2KWINDOW=0
DATA=/usr2/bbx/bbxd/
DATEFORMAT=
AUTO_ANALYZE_TABLES=false";
open(BBJCFG, "> /usr2/bbx/config/config.ini");
        print BBJCFG $config_ini;
        close(BBJCFG);
	mysystem("chmod 775 /usr2/bbx/config/config.ini"); 
	mysystem("chown tfsupport:rtiadmins /usr2/bbx/config/config.ini"); 

	if( (-f "/tmp/$BBJ.gz")
	&&  (-f "/tmp/bbjinstallsettings15.txt")
	) {
		loginfo("Stopping RTI Programs.....");
		mysystem("/sbin/service rti stop");
		loginfo("Stopping BBj Services.....");
		mysystem ("$POSDIR/bin/bbjservice.pl --stop");
		loginfo("Stopping Basis License Manager.....");
		mysystem ("/sbin/service blm stop");
		loginfo("Creating /usr2/install_bbj directory.....");
		mysystem ("mkdir /usr2/install_bbj");
		mysystem ("mv /tmp/$BBJ.gz /usr2/install_bbj/");
		mysystem ("mv /tmp/bbjinstallsettings15.txt /usr2/install_bbj/"); 
		loginfo("Gunziping and untar $BBJ......");
		mysystem("gunzip /usr2/install_bbj/$BBJ.gz");
		if($returnval != 0) {
			logerror("Terminating update_bbj with return code $returnval.");
			exit($returnval);
		}
		mysystem ("tar xvf /usr2/install_bbj/$BBJ -C /usr2/install_bbj/");
		if($returnval != 0) {
			logerror("Terminating update_bbj with return code $returnval.");
			exit($returnval);
		}
		loginfo("Removing existing jar files....");
			mysystem("rm -r /usr2/basis/lib/*");
		loginfo("Untaring $BBJ.......");
		loginfo("Installing $BBJ......");
		mysystem("java -jar /usr2/install_bbj/$BBJ_INSTALL_FILE -p /usr2/install_bbj/bbjinstallsettings15.txt");
		if($returnval != 0) {
			logerror("Terminating update_bbj with return code $returnval.");
			exit($returnval);
		}
	loginfo("Completed $BBJ Installation......");
	loginfo("Removing /var/www/lib/ files.....");
	loginfo("Webstart access is no longer accepted. Removing all files in /var/www/ relating to BBj.");
		mysystem("rm -r /var/www/lib/*");
	loginfo("removing /var/www/jnlp/ files.....");
		mysystem("rm -r /var/www/jnlp/*");
	loginfo("removing /var/www/cgi-bin/ files.....");
		mysystem("rm -r /var/www/cgi-bin/*");
	#loginfo("Copy new unsigned jars to /usr2/basis/lib/ .....");
	#	mysystem("cp -r /usr2/install_bbj/jars/unsigned/* /usr2/basis/lib/");
	# not putting new jars in place with v15 as we no longer allow webstart access
	# loginfo("Copy new signed jars to /var/www/lib/ .....");
	#	mysystem("cp -r /usr2/install_bbj/jars/signed/* /var/www/lib/");
	 loginfo("Copy new librxtxSerial.so to /usr2/basis/lib/ .....");
		mysystem("cp -r /usr2/install_bbj/librxtxSerial.so /usr2/basis/lib/");
	# loginfo("Copy new jnlp.pl to /var/www/cgi-bin/ .....");
#		mysystem("cp -r /usr2/install_bbj/bin/jnlp.pl /var/www/cgi-bin/");
#		mysystem("chmod 775 /var/www/cgi-bin/jnlp.pl");
	loginfo("Changing settings in BBj.properties.....");
		open BBJPROP, "</usr2/basis/cfg/BBj.properties";
		open BBJPROPOUT, ">/usr2/basis/cfg/BBj.properties.tmp"; 	
			while (<BBJPROP>) {
				$_ =~ s/com.basis.user.useFork=true/com.basis.user.useFork=false/g;
				$_ =~ s/basis.java.jvm.BBjServices=\/usr\/java\/usr\/java\/jre1.6.0_16\/bin\/java/basis.java.jvm.BBjServices=\/usr\/java\/latest\/bin\/java/g;
				$_ =~ s/basis.java.jvm.Default=\/usr\/java\/usr\/java\/jre1.6.0_16\/bin\/java/basis.java.jvm.Default=\/usr\/java\/latest\/bin\/java/g;
				$_ =~ s/com.basis.server.admin.1.useSSL=false/com.basis.server.admin.1.useSSL=true/g;
				$_ =~ s/com.basis.bbj.comm.ProxyManagerServer.start=false/com.basis.bbj.comm.ProxyManagerServer.start=true/g;
				$_ =~ s/com.basis.bbj.comm.ThinClientProxyServer.start=false/com.basis.bbj.comm.ThinClientProxyServer.start=true/g;
				$_ =~ s/com.basis.bbj.comm.ThinClientServer.start=false/com.basis.bbj.comm.ThinClientServer.start=true/g;
				$_ =~ s/\-verbose\\:gc/\-Dfile.encoding\\=ISO\-8859\-1 \-verbose\\:gc/g;
				print BBJPROPOUT $_;
			}
		close BBJPROP;
		close BBJPROPOUT;
		mysystem("mv /usr2/basis/cfg/BBj.properties /usr2/basis/cfg/BBj.properties.bak");
		mysystem("mv /usr2/basis/cfg/BBj.properties.tmp /usr2/basis/cfg/BBj.properties");
		mysystem("chmod 644 /usr2/basis/cfg/BBj.properties");
# Adding /usr2/bbx/bin to the /usr2/basis/cfg/.envsetup file 
		$returnval=mysystem ("grep \"/usr2/bbx/bin\"/ /usr2/basis/bin/.envsetup > /dev/null 2> /dev/null");
     if($returnval != 0) {
           loginfo("Add /usr2/bbx/bin to the Basis env setup PATH.");
           mysystem("cp /usr2/basis/bin/.envsetup /usr2/basis/bin/.envsetup.bak");
           open ENVOLD, "< /usr2/basis/bin/.envsetup.bak";
           open ENVNEW, "> /usr2/basis/bin/.envsetup";
           while(<ENVOLD>) {
                my $line = $_;
                if ($line =~ m/PATH=/) {
                     print ENVNEW $line;
                     $line = "PATH=\"\$PATH:\${bbjHome}/bin:\${bbjHome}/lib:/usr2/bbx/bin/\"\n";
                }
                print ENVNEW $line;
           }
           close ENVNEW;
           close ENVOLD;
           mysystem("chmod 775 /usr2/basis/bin/.envsetup");
           mysystem("rm -f /usr2/basis/bin/.envsetup.bak");
     	}
	loginfo("Removing Installation Files........");
		mysystem("rm -fr /usr2/install_bbj");
	loginfo("Done with update to BBj v15.....");
	loginfo("Restarting Basis License Manager.....");
		mysystem("/sbin/service blm stop");
		sleep (2);
		mysystem("/sbin/service blm start");
	loginfo("Restarting BBj Services.....");
		mysystem("$POSDIR/bin/bbjservice.pl --stop");
		sleep (2);
		mysystem("$POSDIR/bin/bbjservice.pl --start");
		sleep (2);
	loginfo("Starting RTI Programs.....");
		mysystem("/sbin/service rti start");
	loginfo("Restart Complete......Finished!");
	}
}

#
# Verify that Java is already (correctly) installed.
#
# Returns
#   1 if installed
#   0 if not
#

sub is_java_already_installed
{
    my ($java_ver) = @_;

    my $java_root = '/usr/java';
    my $java_jre_dir = "$java_root/jre" . $java_ver;
    my $java_jdk_dir = "$java_root/jdk" . $java_ver;

    if (-d $java_root) {
	if (-d $java_jre_dir || -d $java_jdk_dir) {
	    my $link = readlink "$java_root/latest";
	    if ($link eq $java_jre_dir || $link eq $java_jdk_dir) {
		return(1);
	    }
	}
    }

    return(0);
}


#
#
#### Install Java
#
#

sub get_and_load_java
{
	my ($java_file) = @_;

	my $url = "http://tposlinux.blob.core.windows.net/rtibbjupdate11";
	my $java_no_gz_test = $java_file ;
       	 	chomp $java_no_gz_test;
        	my @java_no_gz=split('.gz', $java_no_gz_test);
        	my $java_no_gz=$java_no_gz[$#java_no_gz];

	unless (-f "/tmp/$java_file") {
		system("wget --proxy=off --cache=off -O /tmp/$java_file $url/$java_file");
	}
	unless (-f "/tmp/$java_file") {
		logerror("Could not download file $url/$java_file");
		exit(1);
	}

	loginfo("Installing Java...");
	mysystem("chmod a+rx /tmp/$java_file");
	mysystem("mv /tmp/$java_file /usr/java/");
	mysystem("cd /usr/java/ && gunzip $java_file");
	mysystem("cd /usr/java/ && tar xvf $java_no_gz");
	mysystem("cd /usr/java/ && rm -r latest");
	mysystem("cd /usr/java/ && ln -s jdk1.8.0_45 latest");
	if ($returnval != 0) {
		logerror("Java install returned non-zero exitstatus: $returnval.");
		exit($returnval);
	}

	# Normally, clean up is a "good thing", but looks like the convention
	# for this script is to leave the Java download file.
	#loginfo("Cleaning Up...");
	#mysystem("rm -f /tmp/$java_file 2>/dev/null");
}

sub install_java
{
	loginfo("Installing Java JDK...");

	if("$ARCH" eq "x86") {
	    get_and_load_java($JDK_X86);
	}

	else {
	    get_and_load_java($JDK_X64);
	}
}


#
#
#### Loginfo  & logerror routines
#
#
sub loginfo
{
	my $message = $_[0];
	my $logtime = strftime("%Y-%m-%d %H:%M:%S", localtime());

	chomp($message);
	open LOGFILE, ">> $POSDIR/log/RTI-Patches.log";
		print LOGFILE "$logtime ($0-$$) <I> $message\r\n";
	close LOGFILE;

	return "";
}


sub logerror
{
	my $message = $_[0];
	my $logtime = strftime("%Y-%m-%d %H:%M:%S", localtime());

	chomp($message);
	open LOGFILE, ">> $POSDIR/log/RTI-Patches.log";
		print LOGFILE "$logtime ($0-$$) <E> $message\r\n";
	close LOGFILE;

	return "";
}

#
# Subroutine to run system commands.  This logs an entry.
#
sub mysystem
{
        my $command = $_[0];
	my $LOG_FILE = "$POSDIR/log/RTI-Patches.log";

        system($command . ">> $LOG_FILE 2>> $LOG_FILE");
        $returnval = WEXITSTATUS($?);
        loginfo($command . " Returned $returnval");

        return ($returnval)
}

