#!/usr/bin/perl
#
# $Revision: 1.12 $
# Copyright 2011 Teleflora.
#
# Update BBj to Rev 10.04 - 11-05-2010_0940
#

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


my $HELP = 0;
my $VERSION = 0;
my $BBJ10 = "";
my $INSTALL_JAVA = "";

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 $bbjinstallsettings1004 = "";
my $config_ini = "";
my $returnval = 0;
my $BBJ = "";
my $JRE_X64 = "";
my $JRE_X86 = "";

#
# "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,
	"bbj10" => \$BBJ10,
        "java!" => \$installflags{'java'},
);



# --version
if($VERSION != 0) {
	print("$0 " . '$Revision: 1.12 $' . "\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);

# WHich OS are we using?
open(FILE, "< /etc/redhat-release");
while(<FILE>) {
	if(/release 4/) {
		$OS = "RHEL4";
	}
	if(/release 5/) {
		$OS = "RHWS5";
	}
}
close(FILE);


$POSDIR = "/usr2/bbx";


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

	loginfo("Starting update_bbj.pl " . '$Revision: 1.12 $' . "\n");
	# --bbj10
	if($BBJ10 != 0) {
		loginfo("Installing BBj Rev 10.04 Software Dependencies...");
		$BBJ = "BBj1004_update.tar";
		$JRE_X64 = "jre-6u24-linux-x64.bin";
		$JRE_X86 = "jre-6u24-linux-i586.bin";

        	# Install Java
        	if($installflags{'java'} != 0) {
			if(-d "/usr/java/jre1.6.0_24" || -d "/usr/java/jdk1.6.0_24") {
				loginfo("Java 1.6.0_24 is installed, skipping Java update");
			} else {
				loginfo("Java 1.6.0_24 is NOT installed, beginning Java update");
				install_java();
			}

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

		install_bbj10_packages();
	}

}



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


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

$0 --version
$0 --help
$0 --bbj10            Installs BBj 10.04
$0 --java / --nojava  Do / Do not install Java 1.6.0_24. Defaults to --java.

EOF

}


#
# Install BBj v10.04.
#
sub install_bbj10_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 v10.04...");
	if(! -f "/tmp/$BBJ.gz") {
		system("wget --proxy=off --cache=off -O /tmp/$BBJ.gz http://rtihardware.homelinux.com/ks/$BBJ.gz");
		if(! -f "/tmp/$BBJ.gz") {
			logerror("Could not download file http://rtihardware.homelinux.com/ks/$BBJ.gz");
			exit(1);
		}
	}
#####
#Basis license Info
####

	loginfo("Getting AuthNumber for Basis License......");
	my $authnumtest = `grep AuthNum= /usr2/basis/blm/Register.properties 2>/dev/null`;
	chomp $authnumtest;
	my @authnum=split(/\=/, $authnumtest);
	$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);
	$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);
	$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);
	$Host_ID=$hostid[$#hostid];
	loginfo("Host ID = $Host_ID");
 		

	#Create bbjinstallsettings1004.txt
#	open(BBJINST, "> /tmp/bbjinstallsettings1004.txt");
#        print(BBJINST << 'EOF');
$bbjinstallsettings1004 = "
################################################################################
# BASIS Installation and Configuration Wizard options for BBj 10.0 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
#
################################################################################
# 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=/usr2/basis/
# Specifies the java directory
INSTALL_JAVA_DIRECTORY=/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=
#
################################################################################
# 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]
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=10
LICENSE_REGISTER_DEMOSERIALNUM=BBX000001
LICENSE_REGISTER_DEMOAUTHNUM=9999999999
# 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_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
# 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/bbjinstallsettings1004.txt");
        print BBJINST $bbjinstallsettings1004;
	close(BBJINST);
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/bbjinstallsettings1004.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/bbjinstallsettings1004.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("Untaring $BBJ.......");
		loginfo("Installing $BBJ......");
		mysystem("java -jar /usr2/install_bbj/bin/BBj1004.jar -p /usr2/install_bbj/bbjinstallsettings1004.txt");
		if($returnval != 0) {
			logerror("Terminating update_bbj with return code $returnval.");
			exit($returnval);
		}
	loginfo("Completed $BBJ Installation......");
	loginfo("Removing /var/www/lib/ files.....");
		mysystem("rm -r /var/www/lib/*");
	loginfo("removing /var/www/jnlp/ files.....");
		mysystem("rm -r /var/www/jnlp/*");
	loginfo("Copy new unsigned jars to /usr2/basis/lib/ .....");
		mysystem("cp -r /usr2/install_bbj/jars/unsigned/* /usr2/basis/lib/");
	loginfo("Copy new signed jars to /var/www/lib/ .....");
		mysystem("cp -r /usr2/install_bbj/jars/signed/* /var/www/lib/");
	loginfo("Copy perl scripts to /var/www/cgi-bin/ ......");
		mysystem("cp -r /usr2/install_bbj/cgi-bin/* /var/www/cgi-bin/");
	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;
				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");
	loginfo("Removing Installation Files........");
		mysystem("rm -fr /usr2/install_bbj");
	loginfo("Done with update to BBj v10.04.....");
	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!");
	}
}

#
#
#### Install Java
#
#
sub install_java
{

	loginfo("Installing Java JRE...");
	if("$ARCH" eq "x86") {
		if(! -f "/tmp/$JRE_X86") {
			system("wget --proxy=off --cache=off -O /tmp/$JRE_X86 http://rtihardware.homelinux.com/ks/$JRE_X86");
		}
		if(! -f "/tmp/$JRE_X86") {
			logerror("Could not download file http://rtihardware.homelinux.com/ks/$JRE_X86");
			exit(1);
		} else {
			mysystem("mv /tmp/$JRE_X86 /usr/java/");
			mysystem("chmod a+rx /usr/java/$JRE_X86");
			loginfo("Installing Java...");
			mysystem("cd /usr/java/ && ./$JRE_X86");
			if($returnval != 0) {
				logerror("Terminating update_bbj with return code $returnval.");
				exit($returnval);
			}
		}

	} else {
		if(! -f "/tmp/$JRE_X64") {
			system("wget --proxy=off --cache=off -O /tmp/$JRE_X64 http://rtihardware.homelinux.com/ks/$JRE_X64");
		}
		if(! -f "/tmp/$JRE_X64") {
			logerror("Could not download file http://rtihardware.homelinux.com/ks/$JRE_X64");
			exit(1);
		} else {
			mysystem("mv /tmp/$JRE_X64 /usr/java/");
			mysystem("chmod a+rx /usr/java/$JRE_X64");
			loginfo("Installing Java...");
			mysystem("cd /usr/java && ./$JRE_X64");
			if($returnval != 0) {
				logerror("Terminating update_bbj with return code $returnval.");
				exit($returnval);
			}
		}
	}

	# Link correct java
	loginfo("Linking new Java..");
	mysystem("rm -f /usr/bin/java");
	mysystem("rm -f /usr/java/latest");
	mysystem("ln -s /usr/java/jre1.6.0_24 /usr/java/latest");
	mysystem("ln -s /usr/java/latest/bin/java /usr/bin/java");

	loginfo("Cleaning Up..");
	mysystem("rm -f /usr/java/$JRE_X64 /usr/java/$JRE_X86 2>/dev/null");
}


#
#
#### 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)
}

