#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

#

#++
# "This software program is available to you under a choice of one of two 
# licenses.  You may choose to be licensed under either the GNU General Public 
# License (GPL) Version 2, June 1991, available at 
# http://www.fsf.org/copyleft/gpl.html, or the Intel BSD + Patent License, 
# the text of which follows:
# 
# "Recipient" has requested a license and Intel Corporation ("Intel") is willing
# to grant a license for the software entitled InfiniBand(tm) System Software 
# (the "Software") being provided by Intel Corporation.

# The following definitions apply to this License: 

# "Licensed Patents" means patent claims licensable by Intel Corporation which 
# are necessarily infringed by the use or sale of the Software alone or when 
# combined with the operating system referred to below.

# "Recipient" means the party to whom Intel delivers this Software.
# "Licensee" means Recipient and those third parties that receive a license to 
# any operating system available under the GNU Public License version 2.0 or 
# later.

# Copyright (c) 1996-2002 Intel Corporation. All rights reserved. 

# The license is provided to Recipient and Recipient's Licensees under the 
# following terms.  

# Redistribution and use in source and binary forms of the Software, with or 
# without modification, are permitted provided that the following conditions are 
# met: 
# Redistributions of source code of the Software may retain the above copyright 
# notice, this list of conditions and the following disclaimer. 

# Redistributions in binary form of the Software may reproduce the above 
# copyright notice, this list of conditions and the following disclaimer in the 
# documentation and/or other materials provided with the distribution. 

# Neither the name of Intel Corporation nor the names of its contributors shall 
# be used to endorse or promote products derived from this Software without 
# specific prior written permission.

# Intel hereby grants Recipient and Licensees a non-exclusive, worldwide, 
# royalty-free patent license under Licensed Patents to make, use, sell, offer 
# to sell, import and otherwise transfer the Software, if any, in source code 
# and object code form. This license shall include changes to the Software that 
# are error corrections or other minor changes to the Software that do not add 
# functionality or features when the Software is incorporated in any version of 
# a operating system that has been distributed under the GNU General Public 
# License 2.0 or later.  This patent license shall apply to the combination of 
# the Software and any operating system licensed under the GNU Public License 
# version 2.0 or later if, at the time Intel provides the Software to Recipient, 
# such addition of the Software to the then publicly available versions of such 
# operating system available under the GNU Public License version 2.0 or later 
# (whether in gold, beta or alpha form) causes such combination to be covered by 
# the Licensed Patents. The patent license shall not apply to any other 
# combinations which include the Software. No hardware per se is licensed 
# hereunder. 

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY 
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
#--
#
#
#============================================================================
# initialization
use strict;
use Term::ANSIColor;
use Term::ANSIColor qw(:constants);
use File::Basename;
use Math::BigInt;
use Cwd;

#Setup some defaults
my $exit_code=0;

# IB_STACK affects assorted processing in various common comp_* files
# such as comp_fastfabric.pl
# The correct value should be set in main script for the given installer
my $IB_STACK="IBACCESS";	# stack which is being installed
my $Force_Install = 0;# force option used to force install on unsupported distro

# some options specific to OFED builds
my $OFED_force_rebuild=0;
my $OFED_user_configure_options="";
my $OFED_kernel_configure_options="";
my $OFED_prefix="/usr";
my $OFED_no32bit = 1;	# if 1 disable building 32 bit libraries on 64bit OS
my $OFED_debug = 0;	# if 1 build a debug version of modules
my $OFED_xeonphi = 0;	# if 1 install xeon phi packages
my $OFED_xeonphi_path = ""; # path to mpss-psm* packages

my $CUR_OS_VER=0;
if ( -s "/etc/SuSE-release" )
{
	my $patch_level_version = 1;
	my $sles_version = 0;
	system("cat /etc/SuSE-release | grep PATCHLEVEL > patchlevel");
	system("cat /etc/SuSE-release | grep VERSION > sles_version");
	open (PATCHLEVELFILE, 'patchlevel');
	while (<PATCHLEVELFILE>) {
		chomp;
		$patch_level_version = "$_\n";
	}
	close (PATCHLEVELFILE);
	system("rm -f patchlevel");
	$patch_level_version =~ /(.*)= (\d)/;
	$patch_level_version = $2;
	open (SLESVERSIONFILE, 'sles_version');
	while (<SLESVERSIONFILE>) {
		chomp;
		$sles_version = "$_\n";
	}
	close (SLESVERSIONFILE);
	system("rm -f sles_version");
	$sles_version =~ /(.*) = ([0-9]*)/;
	$sles_version = $2;

	if ( $patch_level_version < 2 &&  $sles_version == 11) {
		LogPrint("SLES11 SP1/SP0 not supported");
		$CUR_OS_VER="3.0.76-0.11-default";
	} else {
		$CUR_OS_VER=`uname -r`;
	}
} elsif ( -s "/etc/redhat-release" ) {
		my $rhel_rel_ver = "";
		my $rhel_rel_maj_ver = 0;
		my $rhel_rel_min_ver = 0;

		open (RHELRELFILE, '/etc/redhat-release');
		while (<RHELRELFILE>) {
				chomp;
				$rhel_rel_ver = "$_\n";
		}
		close (RHELRELFILE);
		$rhel_rel_ver =~ /(Red Hat Enterprise Linux Server release) (\d+).(\d+) .*/;
		$rhel_rel_maj_ver = $2;
		$rhel_rel_min_ver = $3;
		if ( $rhel_rel_maj_ver == 6 && $rhel_rel_min_ver < 4) {
					LogPrint("RHEL$rhel_rel_maj_ver.$rhel_rel_min_ver not supported\n");
					$CUR_OS_VER = "2.6.32-504.el6.x86_64";
		} else {
				$CUR_OS_VER=`uname -r`;
		}
} else {
		$CUR_OS_VER=`uname -r`;
}

chomp $CUR_OS_VER;
# firmware and data files
my $OLD_BASE_DIR = "/etc/sysconfig/iba";
my $BASE_DIR = "/etc/sysconfig/iba";
# iba editable config scripts
my $IBA_CONFIG_DIR = "/etc/sysconfig/iba";

my $UVP_CONF_FILE = "$BASE_DIR/uvp.conf";
my $UVP_CONF_FILE_SOURCE = "uvp.conf";
my $DAT_CONF_FILE_SOURCE = "dat.conf";
my $NETWORK_CONF_DIR = "/etc/sysconfig/network-scripts";
my $ROOT = "/";	# TBD prepared to make this "" removes some // prompts and logs

#This string is compared in verify_os_rev for correct revision of
#kernel release.
my $CUR_DISTRO_VENDOR = "";
my $CUR_VENDOR_VER = "";	# full version (such as ES5.1)
my $CUR_VENDOR_MAJOR_VER = "";    # just major number part (such as ES5)
my $ARCH = `uname -m | sed -e s/ppc/PPC/ -e s/powerpc/PPC/ -e s/i.86/IA32/ -e s/ia64/IA64/ -e s/x86_64/X86_64/`;
chomp $ARCH;
my $ARCH_VENDOR=`grep vendor_id /proc/cpuinfo | tail -1`;
chomp $ARCH_VENDOR;
if ($ARCH eq "X86_64")
{
	if ((-f "$ROOT/etc/redhat-release" || -f "$ROOT/etc/rocks-release") && $ARCH_VENDOR =~ /.*GenuineIntel.*/ && substr($CUR_OS_VER,0,3) eq "2.4")
	{
		$ARCH = "EM64T";
	}
}
my $DRIVER_SUFFIX=".o";
if (substr($CUR_OS_VER,0,3) eq "2.6" || substr($CUR_OS_VER,0,2) eq "3.")
{
	$DRIVER_SUFFIX=".ko";
}
my $DBG_FREE="release";


# Command paths
my $LSPCI = "/sbin/lspci";
my $RPM="/bin/rpm";

# a few key commands to verify exist
my @verify_cmds = ( "uname", "mv", "cp", "rm", "ln", "cmp", "yes", "echo", "sed", "chmod", "chown", "chgrp", "mkdir", "rmdir", "grep", "diff", "awk", "find", "xargs", "sort", $RPM, "chroot", $LSPCI );

sub Abort(@);
sub NormalPrint(@);
sub LogPrint(@);
sub HitKeyCont();
# ============================================================================
# General utility functions

# verify the given command can be found in the PATH
sub check_cmd_exists($)
{
	my $cmd=shift();
	return (0 == system("which $cmd >/dev/null 2>/dev/null"));
}

sub check_root_user()
{
	my $user;
	$user=`/usr/bin/id -u`;
	if ($user != 0)
	{
		die "\n\nYou must be \"root\" to run this install program\n\n";
	}

	# verify basic commands are in path
	foreach my $cmd ( @verify_cmds ) {
		if (! check_cmd_exists($cmd)) {
			die "\n\n$cmd not found in PATH.\nIt is required to login as root or su - root.\nMake sure the path includes /sbin and /usr/sbin\n\n";
		}
	}
}

sub my_tolower($)
{
	my($str) = shift();

	$str =~ tr/[A-Z]/[a-z]/;
	return "$str";
}

sub ROOT_is_set()
{
	return ("$ROOT" ne "/" && "$ROOT" ne "");
}

# ============================================================================
# Version and branding

# version string is filled in by prep, special marker format for it to use
my $VERSION = "THIS_IS_THE_ICS_VERSION_NUMBER:@(#)3.18.3.4% 0.000B000";
$VERSION =~ s/THIS_IS_THE_ICS_VERSION_NUMBER:@\(#\)//;
$VERSION =~ s/%.*//;
my $INT_VERSION = "THIS_IS_THE_ICS_INTERNAL_VERSION_NUMBER:@(#)3_18_3_4% 0.000B000";
$INT_VERSION =~ s/THIS_IS_THE_ICS_INTERNAL_VERSION_NUMBER:@\(#\)//;
$INT_VERSION =~ s/%.*//;
my $BRAND = "THIS_IS_THE_ICS_BRAND:Intel%                    ";
# backslash before : is so patch_brand doesn't replace string
$BRAND =~ s/THIS_IS_THE_ICS_BRAND\://;
$BRAND =~ s/%.*//;

# convert _ and - in version to dots
sub dot_version($)
{
	my $version = shift();

	$version =~ tr/_-/./;
	return $version;
}

# ============================================================================
# installation paths

# where to install libraries
my $LIB_DIR = "/lib";
my $UVP_LIB_DIR = "/lib";
my $USRLOCALLIB_DIR = "/usr/local/lib";
my $OPTIBALIB_DIR = "/opt/iba/lib";
# if different from $LIB_DIR, where to remove libraries from past release
my $OLD_LIB_DIR = "/lib";
my $OLD_USRLOCALLIB_DIR = "/usr/local/lib";
my $OLD_UVP_LIB_DIR = "/lib";

sub set_libdir()
{
	if ( -d "$ROOT/lib64" )
	{
		$LIB_DIR = "/lib64";
		$UVP_LIB_DIR = "/lib64";
		$UVP_CONF_FILE_SOURCE = "uvp.conf.64";
		$DAT_CONF_FILE_SOURCE = "dat.conf.64";
		$USRLOCALLIB_DIR = "/usr/local/lib64";
		$OPTIBALIB_DIR = "/opt/iba/lib64";
	}
}

# determine the os vendor release level based on build system
# this script is stolen from funcs-ext.sh and should
# be maintained in parallel
sub os_vendor_version($)
{
	my $vendor = shift();

	my $rval = "";
	if ($vendor eq "apple") {
		$rval=`sw_vers -productVersion|cut -f1-2 -d.`;
		chop($rval);
	} elsif ($vendor eq "rocks") {
		$rval=`cat /etc/rocks-release | cut -d' ' -f3`;
		chop($rval);
	} elsif ($vendor eq "scyld") {
		$rval=`cat /etc/scyld-release | cut -d' ' -f4`;
		chop($rval);
	} elsif ($vendor eq "mandrake") {
		$rval=`cat /etc/mandrake-release | cut -d' ' -f4`;
		chop($rval);
	} elsif ($vendor eq "fedora") {
		$rval=`cat /etc/fedora-release | cut -d' ' -f4`;
		chop($rval);
	} elsif ($vendor eq "redhat") {
		if (!system("grep -qi advanced /etc/redhat-release")) {
			$rval=`cat /etc/redhat-release | cut -d' ' -f7`;
			chop($rval);
		} elsif (!system("grep -qi centos /etc/redhat-release")) {
			# Find a number of the form "#.#" and output the portion
			# to the left of the decimal point.
			$rval = `cat /etc/redhat-release`;
			$rval =~ m/(\d+).(\d+)/;
			$rval="ES".$1;
		} elsif (!system("grep -qi Scientific /etc/redhat-release")) {
			# Find a number of the form "#.#" and output the portion
			# to the left of the decimal point.
			$rval = `cat /etc/redhat-release`;
			$rval =~ m/(\d+).(\d+)/;
			$rval="ES".$1;
		} elsif (!system("grep -qi enterprise /etc/redhat-release")) {
			# Red Hat Enterprise Linux Server release $a.$b (name)
			#PR 110926
			$rval=`cat /etc/redhat-release | cut -d' ' -f7 | cut -d'.' -f1`;
			chop($rval);
			$rval="ES".$rval;
		} else {
			$rval=`cat /etc/redhat-release | cut -d' ' -f5`;
			chop($rval);
		}
	} elsif ($vendor eq "UnitedLinux") {
		$rval=`grep United /etc/UnitedLinux-release | cut -d' ' -f2`;
		chop($rval);
	} elsif ($vendor eq "SuSE") {
		if (!system("grep -qi enterprise /etc/SuSE-release")) {
			$rval=`grep -i enterprise /etc/SuSE-release | cut -d' ' -f5`;
			chop($rval);
			$rval="ES".$rval;
		} else {
			$rval=`grep SuSE /etc/SuSE-release | cut -d' ' -f3`;
			chop($rval);
		}
	} elsif ($vendor eq "turbolinux") {
		$rval=`cat /etc/turbolinux-release | cut -d' ' -f3`;
		chop($rval);
	}
	return $rval;
}

# Get OS distribution, vendor and vendor version
# set CUR_DISTRO_VENDOR, CUR_VENDOR_VER, CUR_VENDOR_MAJOR_VER
sub determine_os_version()
{
	# we use the current system to select the distribution
	# TBD we expect client image for diskless client install to have these files
	if ( -e "/etc/redhat-release" && !(-l "/etc/redhat-release") ) 
	{
		$CUR_DISTRO_VENDOR = "redhat";
	} elsif ( -s "/etc/UnitedLinux-release" ) {          
		$CUR_DISTRO_VENDOR = "UnitedLinux";
		$NETWORK_CONF_DIR = "/etc/sysconfig/network";
	} elsif ( -s "/etc/SuSE-release" ) {          
		$CUR_DISTRO_VENDOR = "SuSE";
		$NETWORK_CONF_DIR = "/etc/sysconfig/network";
	} elsif ( -s "/etc/centos-release" ) {
		$CUR_DISTRO_VENDOR = "redhat";
	} else {
		# autodetermine the distribution
		open DISTRO_VENDOR, "ls /etc/*-release|grep -v lsb 2>/dev/null |"
			|| die "Unable to open pipe\n";
		$CUR_DISTRO_VENDOR="";
		while (<DISTRO_VENDOR>) {
			chop;
			if (!(-l $_)) {
				my $CDV  = fileparse($_, '-release');
				if ( "$CDV" ne "rocks" ) {
					$CUR_DISTRO_VENDOR = $CDV;
				}
			}
		}
		close DISTRO_VENDOR;
		if ( $CUR_DISTRO_VENDOR eq "" )
		{            
			NormalPrint "Unable to determine current Linux distribution.\n";
			Abort "Please contact your support representative...\n";
		} elsif ($CUR_DISTRO_VENDOR eq "SuSE") {
			$NETWORK_CONF_DIR = "/etc/sysconfig/network";
		} elsif ($CUR_DISTRO_VENDOR eq "centos") {
			$CUR_DISTRO_VENDOR = "redhat";
		}
	}

	$CUR_VENDOR_VER = os_vendor_version($CUR_DISTRO_VENDOR);
	$CUR_VENDOR_MAJOR_VER = $CUR_VENDOR_VER;
	$CUR_VENDOR_MAJOR_VER =~ s/\..*//;	# remove any . version suffix
}

# verify distrib of this system matches files indicating supported
#  arch, distro, distro_version
sub verify_distrib_files
{
	my $supported_arch=`cat ./arch 2>/dev/null`;
	chomp($supported_arch);
	my $supported_distro_vendor=`cat ./distro 2>/dev/null`;
	chomp($supported_distro_vendor);
	my $supported_distro_vendor_ver=`cat ./distro_version 2>/dev/null`;
	chomp($supported_distro_vendor_ver);

	if ( "$supported_arch" eq "" || $supported_distro_vendor eq ""
		|| $supported_distro_vendor_ver eq "") {
		NormalPrint "Unable to proceed: installation image corrupted or install not run as ./INSTALL\n";
		NormalPrint "INSTALL must be run from within untar'ed install image directory\n";
		Abort "Please contact your support representative...\n";
	}

	my $archname;
	my $supported_archname;
	if ( "$supported_arch" ne "$ARCH"
		|| "$supported_distro_vendor" ne "$CUR_DISTRO_VENDOR"
		|| ("$supported_distro_vendor_ver" ne "$CUR_VENDOR_VER"
			&& "$supported_distro_vendor_ver" ne "$CUR_VENDOR_MAJOR_VER"))
	{
		#LogPrint "Unable to proceed, $CUR_DISTRO_VENDOR $CUR_VENDOR_VER not supported by $INT_VERSION media\n";

		$archname=$ARCH;
		if ( $ARCH eq "IA32") {
			$archname="the Pentium Family";
		} 
		if ( $ARCH eq "IA64" ) {
			$archname="the Itanium family";
		} 
		if ( $ARCH eq "X86_64" ) {
			$archname="the EM64T or Opteron";
		} 
		if ( $ARCH eq "PPC64" ) {
			$archname="the PowerPC 64 bit";
		} 
		if ( $ARCH eq "PPC" ) {
			$archname="the PowerPC";
		} 
		
		NormalPrint "$CUR_DISTRO_VENDOR $CUR_VENDOR_VER for $archname is not supported by this installation\n";
		NormalPrint "This installation supports the following Linux Distributions:\n";
		$supported_archname=$ARCH;
		if ( $supported_arch eq "IA32") {
			$supported_archname="the Pentium Family";
		} 
		if ( $supported_arch eq "IA64" ) {
			$supported_archname="the Itanium family";
		} 
		if ( $supported_arch eq "X86_64" ) {
			$supported_archname="the EM64T or Opteron";
		} 
		if ( $supported_arch eq "PPC64" ) {
			$supported_archname="the PowerPC 64 bit";
		} 
		if ( $supported_arch eq "PPC" ) {
			$supported_archname="the PowerPC";
		} 
		NormalPrint "For $supported_archname: $supported_distro_vendor.$supported_distro_vendor_ver\n";
		if ( $Force_Install ) {
			NormalPrint "Installation Forced, will proceed with risk of undefined results\n";
			HitKeyCont;
		} else {
			Abort "Please contact your support representative...\n";
		}
	}
}
#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

#

#++
# "This software program is available to you under a choice of one of two 
# licenses.  You may choose to be licensed under either the GNU General Public 
# License (GPL) Version 2, June 1991, available at 
# http://www.fsf.org/copyleft/gpl.html, or the Intel BSD + Patent License, 
# the text of which follows:
# 
# "Recipient" has requested a license and Intel Corporation ("Intel") is willing
# to grant a license for the software entitled InfiniBand(tm) System Software 
# (the "Software") being provided by Intel Corporation.

# The following definitions apply to this License: 

# "Licensed Patents" means patent claims licensable by Intel Corporation which 
# are necessarily infringed by the use or sale of the Software alone or when 
# combined with the operating system referred to below.

# "Recipient" means the party to whom Intel delivers this Software.
# "Licensee" means Recipient and those third parties that receive a license to 
# any operating system available under the GNU Public License version 2.0 or 
# later.

# Copyright (c) 1996-2002 Intel Corporation. All rights reserved. 

# The license is provided to Recipient and Recipient's Licensees under the 
# following terms.  

# Redistribution and use in source and binary forms of the Software, with or 
# without modification, are permitted provided that the following conditions are 
# met: 
# Redistributions of source code of the Software may retain the above copyright 
# notice, this list of conditions and the following disclaimer. 

# Redistributions in binary form of the Software may reproduce the above 
# copyright notice, this list of conditions and the following disclaimer in the 
# documentation and/or other materials provided with the distribution. 

# Neither the name of Intel Corporation nor the names of its contributors shall 
# be used to endorse or promote products derived from this Software without 
# specific prior written permission.

# Intel hereby grants Recipient and Licensees a non-exclusive, worldwide, 
# royalty-free patent license under Licensed Patents to make, use, sell, offer 
# to sell, import and otherwise transfer the Software, if any, in source code 
# and object code form. This license shall include changes to the Software that 
# are error corrections or other minor changes to the Software that do not add 
# functionality or features when the Software is incorporated in any version of 
# a operating system that has been distributed under the GNU General Public 
# License 2.0 or later.  This patent license shall apply to the combination of 
# the Software and any operating system licensed under the GNU Public License 
# version 2.0 or later if, at the time Intel provides the Software to Recipient, 
# such addition of the Software to the then publicly available versions of such 
# operating system available under the GNU Public License version 2.0 or later 
# (whether in gold, beta or alpha form) causes such combination to be covered by 
# the Licensed Patents. The patent license shall not apply to any other 
# combinations which include the Software. No hardware per se is licensed 
# hereunder. 

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY 
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
#--
#
#
#============================================================================
# initialization
use strict;
use Term::ANSIColor;
use Term::ANSIColor qw(:constants);
use File::Basename;
use Math::BigInt;
use Cwd;

#Setup some defaults
my $exit_code=0;

# IB_STACK affects assorted processing in various common comp_* files
# such as comp_fastfabric.pl
# The correct value should be set in main script for the given installer
my $IB_STACK="IBACCESS";	# stack which is being installed
my $Force_Install = 0;# force option used to force install on unsupported distro

# some options specific to OFED builds
my $OFED_force_rebuild=0;
my $OFED_user_configure_options="";
my $OFED_kernel_configure_options="";
my $OFED_prefix="/usr";
my $OFED_no32bit = 1;	# if 1 disable building 32 bit libraries on 64bit OS
my $OFED_debug = 0;	# if 1 build a debug version of modules
my $OFED_xeonphi = 0;	# if 1 install xeon phi packages
my $OFED_xeonphi_path = ""; # path to mpss-psm* packages

my $CUR_OS_VER=0;
if ( -s "/etc/SuSE-release" )
{
	my $patch_level_version = 1;
	my $sles_version = 0;
	system("cat /etc/SuSE-release | grep PATCHLEVEL > patchlevel");
	system("cat /etc/SuSE-release | grep VERSION > sles_version");
	open (PATCHLEVELFILE, 'patchlevel');
	while (<PATCHLEVELFILE>) {
		chomp;
		$patch_level_version = "$_\n";
	}
	close (PATCHLEVELFILE);
	system("rm -f patchlevel");
	$patch_level_version =~ /(.*)= (\d)/;
	$patch_level_version = $2;
	open (SLESVERSIONFILE, 'sles_version');
	while (<SLESVERSIONFILE>) {
		chomp;
		$sles_version = "$_\n";
	}
	close (SLESVERSIONFILE);
	system("rm -f sles_version");
	$sles_version =~ /(.*) = ([0-9]*)/;
	$sles_version = $2;

	if ( $patch_level_version < 2 &&  $sles_version == 11) {
		LogPrint("SLES11 SP1/SP0 not supported");
		$CUR_OS_VER="3.0.76-0.11-default";
	} else {
		$CUR_OS_VER=`uname -r`;
	}
} elsif ( -s "/etc/redhat-release" ) {
		my $rhel_rel_ver = "";
		my $rhel_rel_maj_ver = 0;
		my $rhel_rel_min_ver = 0;

		open (RHELRELFILE, '/etc/redhat-release');
		while (<RHELRELFILE>) {
				chomp;
				$rhel_rel_ver = "$_\n";
		}
		close (RHELRELFILE);
		$rhel_rel_ver =~ /(Red Hat Enterprise Linux Server release) (\d+).(\d+) .*/;
		$rhel_rel_maj_ver = $2;
		$rhel_rel_min_ver = $3;
		if ( $rhel_rel_maj_ver == 6 && $rhel_rel_min_ver < 4) {
					LogPrint("RHEL$rhel_rel_maj_ver.$rhel_rel_min_ver not supported\n");
					$CUR_OS_VER = "2.6.32-504.el6.x86_64";
		} else {
				$CUR_OS_VER=`uname -r`;
		}
} else {
		$CUR_OS_VER=`uname -r`;
}

chomp $CUR_OS_VER;
# firmware and data files
my $OLD_BASE_DIR = "/etc/sysconfig/iba";
my $BASE_DIR = "/etc/sysconfig/iba";
# iba editable config scripts
my $IBA_CONFIG_DIR = "/etc/sysconfig/iba";

my $UVP_CONF_FILE = "$BASE_DIR/uvp.conf";
my $UVP_CONF_FILE_SOURCE = "uvp.conf";
my $DAT_CONF_FILE_SOURCE = "dat.conf";
my $NETWORK_CONF_DIR = "/etc/sysconfig/network-scripts";
my $ROOT = "/";	# TBD prepared to make this "" removes some // prompts and logs

#This string is compared in verify_os_rev for correct revision of
#kernel release.
my $CUR_DISTRO_VENDOR = "";
my $CUR_VENDOR_VER = "";	# full version (such as ES5.1)
my $CUR_VENDOR_MAJOR_VER = "";    # just major number part (such as ES5)
my $ARCH = `uname -m | sed -e s/ppc/PPC/ -e s/powerpc/PPC/ -e s/i.86/IA32/ -e s/ia64/IA64/ -e s/x86_64/X86_64/`;
chomp $ARCH;
my $ARCH_VENDOR=`grep vendor_id /proc/cpuinfo | tail -1`;
chomp $ARCH_VENDOR;
if ($ARCH eq "X86_64")
{
	if ((-f "$ROOT/etc/redhat-release" || -f "$ROOT/etc/rocks-release") && $ARCH_VENDOR =~ /.*GenuineIntel.*/ && substr($CUR_OS_VER,0,3) eq "2.4")
	{
		$ARCH = "EM64T";
	}
}
my $DRIVER_SUFFIX=".o";
if (substr($CUR_OS_VER,0,3) eq "2.6" || substr($CUR_OS_VER,0,2) eq "3.")
{
	$DRIVER_SUFFIX=".ko";
}
my $DBG_FREE="release";


# Command paths
my $LSPCI = "/sbin/lspci";
my $RPM="/bin/rpm";

# a few key commands to verify exist
my @verify_cmds = ( "uname", "mv", "cp", "rm", "ln", "cmp", "yes", "echo", "sed", "chmod", "chown", "chgrp", "mkdir", "rmdir", "grep", "diff", "awk", "find", "xargs", "sort", $RPM, "chroot", $LSPCI );

sub Abort(@);
sub NormalPrint(@);
sub LogPrint(@);
sub HitKeyCont();
# ============================================================================
# General utility functions

# verify the given command can be found in the PATH
sub check_cmd_exists($)
{
	my $cmd=shift();
	return (0 == system("which $cmd >/dev/null 2>/dev/null"));
}

sub check_root_user()
{
	my $user;
	$user=`/usr/bin/id -u`;
	if ($user != 0)
	{
		die "\n\nYou must be \"root\" to run this install program\n\n";
	}

	# verify basic commands are in path
	foreach my $cmd ( @verify_cmds ) {
		if (! check_cmd_exists($cmd)) {
			die "\n\n$cmd not found in PATH.\nIt is required to login as root or su - root.\nMake sure the path includes /sbin and /usr/sbin\n\n";
		}
	}
}

sub my_tolower($)
{
	my($str) = shift();

	$str =~ tr/[A-Z]/[a-z]/;
	return "$str";
}

sub ROOT_is_set()
{
	return ("$ROOT" ne "/" && "$ROOT" ne "");
}

# ============================================================================
# Version and branding

# version string is filled in by prep, special marker format for it to use
my $VERSION = "THIS_IS_THE_ICS_VERSION_NUMBER:@(#)3.18.3.4% 0.000B000";
$VERSION =~ s/THIS_IS_THE_ICS_VERSION_NUMBER:@\(#\)//;
$VERSION =~ s/%.*//;
my $INT_VERSION = "THIS_IS_THE_ICS_INTERNAL_VERSION_NUMBER:@(#)3_18_3_4% 0.000B000";
$INT_VERSION =~ s/THIS_IS_THE_ICS_INTERNAL_VERSION_NUMBER:@\(#\)//;
$INT_VERSION =~ s/%.*//;
my $BRAND = "THIS_IS_THE_ICS_BRAND:Intel%                    ";
# backslash before : is so patch_brand doesn't replace string
$BRAND =~ s/THIS_IS_THE_ICS_BRAND\://;
$BRAND =~ s/%.*//;

# convert _ and - in version to dots
sub dot_version($)
{
	my $version = shift();

	$version =~ tr/_-/./;
	return $version;
}

# ============================================================================
# installation paths

# where to install libraries
my $LIB_DIR = "/lib";
my $UVP_LIB_DIR = "/lib";
my $USRLOCALLIB_DIR = "/usr/local/lib";
my $OPTIBALIB_DIR = "/opt/iba/lib";
# if different from $LIB_DIR, where to remove libraries from past release
my $OLD_LIB_DIR = "/lib";
my $OLD_USRLOCALLIB_DIR = "/usr/local/lib";
my $OLD_UVP_LIB_DIR = "/lib";

sub set_libdir()
{
	if ( -d "$ROOT/lib64" )
	{
		$LIB_DIR = "/lib64";
		$UVP_LIB_DIR = "/lib64";
		$UVP_CONF_FILE_SOURCE = "uvp.conf.64";
		$DAT_CONF_FILE_SOURCE = "dat.conf.64";
		$USRLOCALLIB_DIR = "/usr/local/lib64";
		$OPTIBALIB_DIR = "/opt/iba/lib64";
	}
}

# determine the os vendor release level based on build system
# this script is stolen from funcs-ext.sh and should
# be maintained in parallel
sub os_vendor_version($)
{
	my $vendor = shift();

	my $rval = "";
	if ($vendor eq "apple") {
		$rval=`sw_vers -productVersion|cut -f1-2 -d.`;
		chop($rval);
	} elsif ($vendor eq "rocks") {
		$rval=`cat /etc/rocks-release | cut -d' ' -f3`;
		chop($rval);
	} elsif ($vendor eq "scyld") {
		$rval=`cat /etc/scyld-release | cut -d' ' -f4`;
		chop($rval);
	} elsif ($vendor eq "mandrake") {
		$rval=`cat /etc/mandrake-release | cut -d' ' -f4`;
		chop($rval);
	} elsif ($vendor eq "fedora") {
		$rval=`cat /etc/fedora-release | cut -d' ' -f4`;
		chop($rval);
	} elsif ($vendor eq "redhat") {
		if (!system("grep -qi advanced /etc/redhat-release")) {
			$rval=`cat /etc/redhat-release | cut -d' ' -f7`;
			chop($rval);
		} elsif (!system("grep -qi centos /etc/redhat-release")) {
			# Find a number of the form "#.#" and output the portion
			# to the left of the decimal point.
			$rval = `cat /etc/redhat-release`;
			$rval =~ m/(\d+).(\d+)/;
			$rval="ES".$1;
		} elsif (!system("grep -qi Scientific /etc/redhat-release")) {
			# Find a number of the form "#.#" and output the portion
			# to the left of the decimal point.
			$rval = `cat /etc/redhat-release`;
			$rval =~ m/(\d+).(\d+)/;
			$rval="ES".$1;
		} elsif (!system("grep -qi enterprise /etc/redhat-release")) {
			# Red Hat Enterprise Linux Server release $a.$b (name)
			#PR 110926
			$rval=`cat /etc/redhat-release | cut -d' ' -f7 | cut -d'.' -f1`;
			chop($rval);
			$rval="ES".$rval;
		} else {
			$rval=`cat /etc/redhat-release | cut -d' ' -f5`;
			chop($rval);
		}
	} elsif ($vendor eq "UnitedLinux") {
		$rval=`grep United /etc/UnitedLinux-release | cut -d' ' -f2`;
		chop($rval);
	} elsif ($vendor eq "SuSE") {
		if (!system("grep -qi enterprise /etc/SuSE-release")) {
			$rval=`grep -i enterprise /etc/SuSE-release | cut -d' ' -f5`;
			chop($rval);
			$rval="ES".$rval;
		} else {
			$rval=`grep SuSE /etc/SuSE-release | cut -d' ' -f3`;
			chop($rval);
		}
	} elsif ($vendor eq "turbolinux") {
		$rval=`cat /etc/turbolinux-release | cut -d' ' -f3`;
		chop($rval);
	}
	return $rval;
}

# Get OS distribution, vendor and vendor version
# set CUR_DISTRO_VENDOR, CUR_VENDOR_VER, CUR_VENDOR_MAJOR_VER
sub determine_os_version()
{
	# we use the current system to select the distribution
	# TBD we expect client image for diskless client install to have these files
	if ( -e "/etc/redhat-release" && !(-l "/etc/redhat-release") ) 
	{
		$CUR_DISTRO_VENDOR = "redhat";
	} elsif ( -s "/etc/UnitedLinux-release" ) {          
		$CUR_DISTRO_VENDOR = "UnitedLinux";
		$NETWORK_CONF_DIR = "/etc/sysconfig/network";
	} elsif ( -s "/etc/SuSE-release" ) {          
		$CUR_DISTRO_VENDOR = "SuSE";
		$NETWORK_CONF_DIR = "/etc/sysconfig/network";
	} elsif ( -s "/etc/centos-release" ) {
		$CUR_DISTRO_VENDOR = "redhat";
	} else {
		# autodetermine the distribution
		open DISTRO_VENDOR, "ls /etc/*-release|grep -v lsb 2>/dev/null |"
			|| die "Unable to open pipe\n";
		$CUR_DISTRO_VENDOR="";
		while (<DISTRO_VENDOR>) {
			chop;
			if (!(-l $_)) {
				my $CDV  = fileparse($_, '-release');
				if ( "$CDV" ne "rocks" ) {
					$CUR_DISTRO_VENDOR = $CDV;
				}
			}
		}
		close DISTRO_VENDOR;
		if ( $CUR_DISTRO_VENDOR eq "" )
		{            
			NormalPrint "Unable to determine current Linux distribution.\n";
			Abort "Please contact your support representative...\n";
		} elsif ($CUR_DISTRO_VENDOR eq "SuSE") {
			$NETWORK_CONF_DIR = "/etc/sysconfig/network";
		} elsif ($CUR_DISTRO_VENDOR eq "centos") {
			$CUR_DISTRO_VENDOR = "redhat";
		}
	}

	$CUR_VENDOR_VER = os_vendor_version($CUR_DISTRO_VENDOR);
	$CUR_VENDOR_MAJOR_VER = $CUR_VENDOR_VER;
	$CUR_VENDOR_MAJOR_VER =~ s/\..*//;	# remove any . version suffix
}

# verify distrib of this system matches files indicating supported
#  arch, distro, distro_version
sub verify_distrib_files
{
	my $supported_arch=`cat ./arch 2>/dev/null`;
	chomp($supported_arch);
	my $supported_distro_vendor=`cat ./distro 2>/dev/null`;
	chomp($supported_distro_vendor);
	my $supported_distro_vendor_ver=`cat ./distro_version 2>/dev/null`;
	chomp($supported_distro_vendor_ver);

	if ( "$supported_arch" eq "" || $supported_distro_vendor eq ""
		|| $supported_distro_vendor_ver eq "") {
		NormalPrint "Unable to proceed: installation image corrupted or install not run as ./INSTALL\n";
		NormalPrint "INSTALL must be run from within untar'ed install image directory\n";
		Abort "Please contact your support representative...\n";
	}

	my $archname;
	my $supported_archname;
	if ( "$supported_arch" ne "$ARCH"
		|| "$supported_distro_vendor" ne "$CUR_DISTRO_VENDOR"
		|| ("$supported_distro_vendor_ver" ne "$CUR_VENDOR_VER"
			&& "$supported_distro_vendor_ver" ne "$CUR_VENDOR_MAJOR_VER"))
	{
		#LogPrint "Unable to proceed, $CUR_DISTRO_VENDOR $CUR_VENDOR_VER not supported by $INT_VERSION media\n";

		$archname=$ARCH;
		if ( $ARCH eq "IA32") {
			$archname="the Pentium Family";
		} 
		if ( $ARCH eq "IA64" ) {
			$archname="the Itanium family";
		} 
		if ( $ARCH eq "X86_64" ) {
			$archname="the EM64T or Opteron";
		} 
		if ( $ARCH eq "PPC64" ) {
			$archname="the PowerPC 64 bit";
		} 
		if ( $ARCH eq "PPC" ) {
			$archname="the PowerPC";
		} 
		
		NormalPrint "$CUR_DISTRO_VENDOR $CUR_VENDOR_VER for $archname is not supported by this installation\n";
		NormalPrint "This installation supports the following Linux Distributions:\n";
		$supported_archname=$ARCH;
		if ( $supported_arch eq "IA32") {
			$supported_archname="the Pentium Family";
		} 
		if ( $supported_arch eq "IA64" ) {
			$supported_archname="the Itanium family";
		} 
		if ( $supported_arch eq "X86_64" ) {
			$supported_archname="the EM64T or Opteron";
		} 
		if ( $supported_arch eq "PPC64" ) {
			$supported_archname="the PowerPC 64 bit";
		} 
		if ( $supported_arch eq "PPC" ) {
			$supported_archname="the PowerPC";
		} 
		NormalPrint "For $supported_archname: $supported_distro_vendor.$supported_distro_vendor_ver\n";
		if ( $Force_Install ) {
			NormalPrint "Installation Forced, will proceed with risk of undefined results\n";
			HitKeyCont;
		} else {
			Abort "Please contact your support representative...\n";
		}
	}
}
#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# Installation logging

my $LogLevel = 0;	# 0 = normal/quiet, 1=verbose, 2=very verbose
my $LogFile = "/dev/null";	# set when open_log

sub open_log(;$)
{
	my($logfile) = shift();
	if ( "$logfile" eq "" ) {
		$logfile="$ROOT/var/log/iba.log";
	}
	$LogFile = $logfile;
	open(LOG_FD, ">>$logfile");
	print LOG_FD "-------------------------------------------------------------------------------\n";
	print LOG_FD my_basename($0) . " $INT_VERSION Run " . `/bin/date`;
	print LOG_FD "$0 @ARGV\n";
	print LOG_FD "Current Dir: " .  getcwd() . "\n";
}

sub close_log()
{
	close LOG_FD;
}

# output to log and screen and die
sub Abort(@)
{
	print(LOG_FD @_);
	die(@_);
}

# output to log and screen
sub NormalPrint(@)
{
	print(@_);
	print(LOG_FD @_);
}

# output to log only
sub LogPrint(@)
{
	print(LOG_FD @_);
}

sub VerbosePrintEnabled()
{
	return ($LogLevel >= 1);
}

sub VerbosePrint(@)
{
	if (VerbosePrintEnabled() ) {
		print(LOG_FD @_);
	}
}
sub DebugPrintEnabled()
{
	return ($LogLevel >= 2);
}

sub DebugPrint(@)
{
	if (DebugPrintEnabled() ) {
		print(LOG_FD @_);
	}
}

# ============================================================================
# Basic input and prompting routines
my $KEY_ESC=27;
my $KEY_CNTL_C=3;
my $KEY_ENTER=13;

my $Default_Prompt=0;	 # use default values at prompts, non-interactive

sub getch()
{
	my $c;
	system("stty -echo raw");
	$c=getc(STDIN);
	system("stty echo -raw");
	print "\n";
	return $c;
}

sub HitKeyCont()
{
	if ( $Default_Prompt )
	{
		return;
	}

	print "Hit any key to continue...";
	getch();
	return;
}

sub remove_whitespace($)
{
	my $string=shift();
	chomp($string);
	$string =~ s/^[[:space:]]*//;	# remove leading
	$string =~ s/[[:space:]]*$//;	# remove trailing
	return $string;
}

# return numeric value: minimum <= value <= maximum
sub GetNumericValue($$$$)
{
	my($retval) = 0;

	my($Question) = $_[0];
	my($default) = $_[1];
	my($minvalue) = $_[2];
	my($maxvalue) = $_[3];

        if ( $Default_Prompt ) {
		NormalPrint "$Question -> $default\n";
		if (($default ge $minvalue) && ($default le $maxvalue)) {
			return $default;
		}
		# for invalid default, fall through and prompt
	}

	while (1)
	{
		NormalPrint "$Question [$default]: ";
		chomp($retval = <STDIN>);
		$retval=remove_whitespace($retval);

		if (length($retval) == 0) {
			$retval=$default;
		}
		if (($retval >= $minvalue) && ($retval <= $maxvalue)) {
			LogPrint "$Question -> $retval\n";
			return $retval;
		}
		else {
			NormalPrint "Value Out-of-Range\n";
                }
	}        
}

#return 0 for no, 1 for yes
sub GetYesNo($$)
{
	my($Question) = shift();
	my($default) = shift();

	my($retval) = 1;
	my($answer) = 0;

	if ( $Default_Prompt ) {
		NormalPrint "$Question -> $default\n";
		if ( "$default" eq "y") {
			return 1;
		} elsif ("$default" eq "n") {
			return 0;
		}
		# for invalid default, fall through and prompt
	}

	while ($answer == 0)
	{
		print "$Question [$default]: ";
		chomp($_ = <STDIN>);
		$_=remove_whitespace($_);
		if ("$_" eq "") {
			$_=$default;
		}
		if (/^[Nn]/) 
		{
			LogPrint "$Question -> n\n";
			$retval = 0;
			$answer = 1;
		} elsif (/^[Yy]/ ) {
			LogPrint "$Question -> y\n";
			$retval = 1;
			$answer = 1;
		}
	}        
	return $retval;
}

# we keep answers in text format.  This way we can later enhance the command
# line argument list to allow answers to more complex questions
my %AnswerMemory = ();	# keep track of past answers to yes/no questions

my @AnswerHelp = ();	# help test for each keyword

# process_args and Usage call occurs before source_comp.  So when we put
# this call in comp.pl, INSTALL has the "built version" of the usage
# which may be out of sync with the "installed version".  Only impacts questions
# asked during uninstall, especially for downgrade case, so that is
# acceptable
sub AddAnswerHelp($$)
{
	my($Keyword) = shift();
	my($help) = shift();

	# check for duplicates, skip if already in list
	foreach my $ans (@AnswerHelp)
	{
		if ($ans =~ m/^$Keyword -/)
		{
			return;
		}
	}
	@AnswerHelp = (@AnswerHelp, "$Keyword - $help");
}

sub showAnswerHelp()
{
	if (scalar(@AnswerHelp) != 0) {
	 	printf STDERR "       --answer keyword=value - provide an answer to a question which might\n";
	 	printf STDERR "            occur during the operation.  answers to questions which are not\n";
	 	printf STDERR "            asked are ignored.  Invalid answers will result in prompting\n";
	 	printf STDERR "            for interactive installs or use of the default for non-interactive.\n";
		printf STDERR "       Possible Questions:\n";
		foreach my $help (@AnswerHelp) {
			printf STDERR "         $help\n";
		}
	} else {
	 	printf STDERR "       --answer keyword=value - presently ignored\n";
	}
}

# similar to GetYesNo, except if the question has already been answered
# (or defaulted on the command line), the question is not asked, instead the
# previous answer is provided
sub GetYesNoWithMemory($$$$)
{
	my($Keyword) = shift();	# unique keyword to identify question
	my($remember) = shift(); # remember answer for use next time
	my($Question) = shift(); # the question shown to user
	my($default) = shift();	# the default to use if not already remembered
	my($retval);

	if ( exists $AnswerMemory{"$Keyword"})
	{
		$_ = $AnswerMemory{"$Keyword"};
		if (/^[Nn]/) 
		{
			NormalPrint "$Keyword: $Question -> n\n";
			$retval = 0;
		} elsif (/^[Yy]/ ) {
			NormalPrint "$Keyword: $Question -> y\n";
			$retval = 1;
		} else {
			# invalid answer, now what?  prompt?
			NormalPrint "$Keyword: $Question -> Invalid answer: $_\n";
			delete $AnswerMemory{"$Keyword"};
		}
	}
	if ( ! exists $AnswerMemory{"$Keyword"})
	{
		$retval = GetYesNo($Question, $default);
		if ($remember) {
			my($ans);
			if ( $retval ) {
				$ans = "y";
			} else {
				$ans = "n";
			}
			$AnswerMemory{"$Keyword"} = $ans;
		}
	}
	return $retval;
}

sub set_answer($$)
{
	my($Keyword) = shift();	# unique keyword to identify question
	my($answer) = shift(); # answer to question

	$AnswerMemory{"$Keyword"} = $answer;
}

sub clear_answer($)
{
	my($Keyword) = shift();

	delete $AnswerMemory{"$Keyword"};
}

sub clear_all_answers($)
{
	my $Keyword;

	foreach $Keyword (keys(%AnswerMemory))
	{
		delete $AnswerMemory{"$Keyword"};
	}
}


#return choice
sub GetChoice($$@)
{
	my($Question) = shift();
	my($default) = shift();
	my(@choices) = @_;	# single character choices

	my $c;

	if ( $Default_Prompt ) {
		NormalPrint "$Question -> $default\n";
		foreach $c ( @choices )
		{
			if ("$default" eq "$c" ) {
				return $c;
			}
		}
		# for invalid default, fall through and prompt
	}

	while (1)
	{
		print "$Question [$default]: ";
		chomp($_ = <STDIN>);
		$_=remove_whitespace($_);
		if ("$_" eq "") {
			$_=$default;
		}
		$_ = my_tolower($_);
		foreach $c ( @choices )
		{
			if ("$_" eq "$c" ) {
				LogPrint "$Question -> $c\n";
				return $c;
			}
		}
	}        
	# NOTREACHED
}

sub print_separator()
{
	print "-------------------------------------------------------------------------------\n";
}

# based on files on install media update DBG_FREE
# if both release and debug are available on media, prompt user
# This routine checks both the location for IbAccess and Open IB FF installs
sub select_debug_release($)
{
	my($srcdir) = shift();
	my $inp;

	# check current directory to determine if Debug available
	if ( (! -d "$srcdir/bin/$ARCH/$CUR_OS_VER/debug") 
	    and (! -d "$srcdir/bin/$ARCH/$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER/lib/debug")
	    and (! -d "$srcdir/bin/$ARCH/$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER/lib/debug") )
	{
		# no choice, only release available
		$DBG_FREE="release";
	}
	elsif ( (! -d "$srcdir/bin/$ARCH/$CUR_OS_VER/release")
			and (! -d "$srcdir/bin/$ARCH/$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER/lib/release")
			and (! -d "$srcdir/bin/$ARCH/$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER/lib/release") )
	{
		# no choice, only debug available
		$DBG_FREE="debug";
	} elsif ( $Default_Prompt ) {
		$DBG_FREE="release";
		printf ("Installing $DBG_FREE Software\n");
	} else {
		printf ("Both Release and Debug versions are available\n\n");
		printf ("Please select which version should be used for install or upgrade operations:\n\n");
		printf ("1) Release Software\n");
		printf ("2) Debug Software\n");

		$inp = getch();

		if ($inp == 1)
		{
			$DBG_FREE="release";
		}
		elsif ($inp == 2)
		{
			$DBG_FREE="debug";
		}
		else 
		{
			printf ("Invalid Choice...\n");
			HitKeyCont;
			return;
		}
	}
}

#!/usr/bin/perl
# # INTEL CONFIDENTIAL
# # Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
# # The source code contained or described herein and all documents related
# # to the source code ("Material") are owned by Intel Corporation or its
# # suppliers or licensors. Title to the Material remains with Intel Corporation
# # or its suppliers and licensors. The Material contains trade secrets and
# # proprietary and confidential information of Intel or its suppliers and
# # licensors. The Material is protected by worldwide copyright and trade
# # secret laws and treaty provisions. No part of the Material may be used,
# # copied, reproduced, modified, published, uploaded, posted, transmitted,
# # distributed, or disclosed in any way without Intel's prior express
# # written permission.
# #
# # No license under any patent, copyright, trade secret or other intellectual
# # property right is granted to or conferred upon you by disclosure or delivery
# # of the Materials, either expressly, by implication, inducement, estoppel or
# # otherwise. Any license under such intellectual property rights must be
# # express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ===========================================================================
# Basic file/directory install/remove

my $Skip_UsrLocalSymLinks=0;	# -l option used to select skipping symlinks from /opt/iba to /usr/local
my $OWNER = "root";
my $GROUP = "root";

# remove any directory prefixes from path
sub my_basename($)
{
	my($path) = shift();

	$path =~ s/.*\/(.*)$/$1/;
	return $path;
}

# check for a file using a glob pattern
# return 1st filename to match pattern
# return "" if no match
sub file_glob($)
{
	my $globpat = shift();	# glob pattern to expand

	my $file;
	# there is a little perl trick here, glob returns a list of matching
	# files.  If we simply assigned glob to a scalar it would retain
	# the rest of the list and return subsequent entries on future glob calls
	# then it would return "" after the last matched name.
	# Hence even if glob matched only 1 name, it would return a 2nd ""
	# value to a future caller.  real subtle problem to figure out.
	
	# the list assignment below allows glob to return a list
	# and all extra list entries are discarded.  Hence this returns the
	# first filename which matches or "" if none are matched
	( $file) = glob("$globpat");

	return "$file";
}

sub make_dir($$$$)
{
	my($dir) = shift();
	my($owner) = shift();
	my($group) = shift();
	my($mode) = shift();

	system "mkdir -p -m $mode $ROOT$dir";
	system "chown $owner $ROOT$dir";
	system "chgrp $group $ROOT$dir";
}

sub check_dir($)
{
	my($dir) = shift();
	if (! -d "$ROOT$dir" ) 
	{
		#Creating directory 

		make_dir("$dir", "$OWNER", "$GROUP", "ugo=rx,u=rwx");
	}
}

sub isDirectoryEmpty($)
{
	my($dir) = shift();
	my $filecount=0;
	if ( -e $dir and -d $dir )
	{
		$filecount=`ls -la $dir| wc -l`;
		if ( $filecount < 4 )
		{
	    	return 1;
		}       
	}
	return 0;
}

sub copy_file($$$$$)
{
	my($src) = shift();
	my($dest) = shift();
	my($owner) = shift();
	my($group) = shift();
	my($mode) = shift();
	# only copy file if source exists, this keep all those cp errors for litering
	# install for development.

	if ( -e $src)
	{               
		system "cp -rf $src $ROOT$dest";
		system "chown $owner $ROOT$dest";
		system "chgrp $group $ROOT$dest";
		system "chmod $mode $ROOT$dest";
	}
}

sub symlink_usrlocal($$)
{
	my($src) = shift();
	my($dest) = shift();

	if ( ! $Skip_UsrLocalSymLinks ) {
		system "rm -f $ROOT$dest";
		if ( -e "$ROOT/$src" ) {
			system "ln -s $src $ROOT$dest";
		}
	}
}

sub copy_all_files($$$$$;$)
{
	my($src_dir)=shift();
	my($dest_dir)=shift();
	my($owner) = shift();
	my($group) = shift();
	my($mode) = shift();
	my($symlink_dir) = shift();	# optional argument
	my(@files);
	my $f;
	my $d;

	if (!-d "$src_dir" )
	{
	 	return;	
	}
	if (!-d "$ROOT$dest_dir")
	{
		return;
	}
	if ( ! $Skip_UsrLocalSymLinks && "$symlink_dir" ne "" &&
		!-d "$ROOT$symlink_dir")
	{
		return;
	}
	@files = glob("$src_dir/*");
	foreach $f (@files)
	{
		$d= my_basename($f);
		if (!-d $f)
		{
			copy_file($f, "$dest_dir/$d", $owner, $group, $mode);
			if ( "$symlink_dir" ne "") {
				symlink_usrlocal("$dest_dir/$d", "$symlink_dir/$d");
			}
		} else {
			check_dir("$dest_dir/$d");
			if ( ! $Skip_UsrLocalSymLinks && "$symlink_dir" ne "") {
				check_dir("$symlink_dir/$d");
				copy_all_files($f, "$dest_dir/$d", $owner, $group, $mode, "$symlink_dir/$d");
			} else {
				copy_all_files($f, "$dest_dir/$d", $owner, $group, $mode,"");
			}
		}
	}
}

sub remove_file($)
{
	my($file) = shift();
	system "rm -f $ROOT$file";
}

sub copy_driver_file($$)
{
	copy_file("$_[0]", "$_[1]", "$OWNER", "$GROUP", "ugo=r,u=rw");
}

sub copy_data_file($$)
{
	copy_file("$_[0]", "$_[1]", "$OWNER", "$GROUP", "ugo=r,u=rw");
}

sub copy_all_data_files($$;$)
{
	copy_all_files("$_[0]", "$_[1]", "$OWNER", "$GROUP", "ugo=r,u=rw","$_[2]");
}

sub copy_arlib_file($$)
{
	copy_file("$_[0]", "$_[1]", "$OWNER", "$GROUP", "ugo=r,u=rw");
}

sub copy_systool_file($$)
{
	# Administrator execution only
	copy_file("$_[0]", "$_[1]", "$OWNER", "$GROUP", "ugo=r,ug=rx,u=rwx");
}

sub copy_all_systool_files($$;$)
{
	copy_all_files("$_[0]", "$_[1]", "$OWNER", "$GROUP", "ugo=r,ug=rx,u=rwx", "$_[2]");
}

sub copy_bin_file($$)
{
	# general user execution
	copy_file("$_[0]", "$_[1]", "$OWNER", "$GROUP", "ugo=rx,u=rwx");
}

sub remove_oldarlib($)
{
	my($libbase) = shift();
	if ( "$LIB_DIR" ne "$OLD_LIB_DIR" )
	{
		system "rm -f $ROOT$libbase";
	}
}

#
# Removes a list of files from a directory
# arg0 : target directory
# arg1 : space delimited list of file names.
#
sub remove_file_list($@)
{
	my($dir)=shift();
	my $f;

	foreach $f (@_)
	{
		remove_file("$dir/$f");
	}
}

# remove the files built from source or installed
# (as listed in .files and .dirs)
# $0 = dirname relative to $ROOT
sub remove_installed_files($)
{
	my $dirname = shift();

	# remove files we installed or user compiled, however do not remove
	# any logs or other files the user may have created
	if ( -d "$ROOT/$dirname" ) {
		system "cd $ROOT/$dirname; for dir in `cat .dirs 2>/dev/null`; do ( cd \$dir; make clobber ) >/dev/null 2>&1; done";
		system "cd $ROOT/$dirname; cat .files 2>/dev/null|xargs rm -f 2>/dev/null";
		system "cd $ROOT/$dirname; cat .files 2>/dev/null|sort -r|xargs rmdir 2>/dev/null";
		system "rm -f $ROOT/$dirname/.files 2>/dev/null";
		system "rm -f $ROOT/$dirname/.dirs 2>/dev/null";
		system "rmdir $ROOT/$dirname/ 2>/dev/null";
	}
}

# ===========================================================================
# Shared Libaries
my $RunLdconfig=0;

sub copy_shlib_file($$)
{
	$RunLdconfig=1;
	copy_file("$_[0]", "$_[1]", "$OWNER", "$GROUP", "ugo=rx,u=rw");
}

sub copy_shlib($$$)
{
	my($src) = shift();
	my($libbase) = shift();
	my($version) = shift();

	system "rm -f $ROOT${libbase}.so";
	if ( ! -e $src )
	{
		if ( -e "$src.so.${version}" )
		{
			$src="$src.so.${version}";
		}
		elsif ( -e "$src.so" )
		{
			$src="$src.so";
		}
	}
	if ( -e $src)
	{
		copy_shlib_file("$src", "${libbase}.so.${version}");
		# source dir is not $ROOT so that when boot root, it will work properly
		system "rm -f " . " $ROOT${libbase}.so";
		system "ln -s " . my_basename("${libbase}.so.${version}") . " $ROOT${libbase}.so";
	}
}

sub symlink_usrlocal_shlib($$$)
{
	# a /opt/iba path w/o suffix (eg. a previous dest for copy_shlib)
	my($src) = shift();
	my($libbase) = shift();
	my($version) = shift();

	symlink_usrlocal("${src}.so.${version}", "${libbase}.so.${version}");
	symlink_usrlocal("${src}.so.${version}", "${libbase}.so");
}

sub remove_shlib($)
{
	my($libbase) = shift();
	$RunLdconfig=1;
	system "rm -f $ROOT${libbase}.so $ROOT${libbase}.so.*";
}

sub remove_oldshlib($)
{
	if ( "$LIB_DIR" ne "$OLD_LIB_DIR" )
	{
		remove_shlib("$_[0]");
	}
}

sub check_ldconfig()
{
	if ($RunLdconfig == 1 )
	{
		print_separator;
		print "Updating dynamic linker cache...\n";
		# this is how /etc/rc.sysinit runs ldconfig
		#LogPrint "Updating dynamic linker cache: /sbin/ldconfig -n /lib\n";
		#system "chroot /$ROOT /sbin/ldconfig -n /lib > /dev/null 2>&1";
		LogPrint "Updating dynamic linker cache: /sbin/ldconfig\n";
		system "chroot /$ROOT /sbin/ldconfig > /dev/null 2>&1";
		$RunLdconfig=0;
		return 1;
	}
	return 0;
}

# ===========================================================================
# Will Reboot be required
my $NeedReboot=0;
sub need_reboot()
{
	$NeedReboot=1;
}

sub check_need_reboot()
{
	if ($NeedReboot == 1 )
	{
		print_separator;
		print BOLD, RED, "A System Reboot is recommended to activate the software changes\n", RESET;
		LogPrint "A System Reboot is recommended to activate the software changes\n";
		return 1;
	}
	return 0;
}
#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

#

#++
# "This software program is available to you under a choice of one of two 
# licenses.  You may choose to be licensed under either the GNU General Public 
# License (GPL) Version 2, June 1991, available at 
# http://www.fsf.org/copyleft/gpl.html, or the Intel BSD + Patent License, 
# the text of which follows:
# 
# "Recipient" has requested a license and Intel Corporation ("Intel") is willing
# to grant a license for the software entitled InfiniBand(tm) System Software 
# (the "Software") being provided by Intel Corporation.

# The following definitions apply to this License: 

# "Licensed Patents" means patent claims licensable by Intel Corporation which 
# are necessarily infringed by the use or sale of the Software alone or when 
# combined with the operating system referred to below.

# "Recipient" means the party to whom Intel delivers this Software.
# "Licensee" means Recipient and those third parties that receive a license to 
# any operating system available under the GNU Public License version 2.0 or 
# later.

# Copyright (c) 1996-2002 Intel Corporation. All rights reserved. 

# The license is provided to Recipient and Recipient's Licensees under the 
# following terms.  

# Redistribution and use in source and binary forms of the Software, with or 
# without modification, are permitted provided that the following conditions are 
# met: 
# Redistributions of source code of the Software may retain the above copyright 
# notice, this list of conditions and the following disclaimer. 

# Redistributions in binary form of the Software may reproduce the above 
# copyright notice, this list of conditions and the following disclaimer in the 
# documentation and/or other materials provided with the distribution. 

# Neither the name of Intel Corporation nor the names of its contributors shall 
# be used to endorse or promote products derived from this Software without 
# specific prior written permission.

# Intel hereby grants Recipient and Licensees a non-exclusive, worldwide, 
# royalty-free patent license under Licensed Patents to make, use, sell, offer 
# to sell, import and otherwise transfer the Software, if any, in source code 
# and object code form. This license shall include changes to the Software that 
# are error corrections or other minor changes to the Software that do not add 
# functionality or features when the Software is incorporated in any version of 
# a operating system that has been distributed under the GNU General Public 
# License 2.0 or later.  This patent license shall apply to the combination of 
# the Software and any operating system licensed under the GNU Public License 
# version 2.0 or later if, at the time Intel provides the Software to Recipient, 
# such addition of the Software to the then publicly available versions of such 
# operating system available under the GNU Public License version 2.0 or later 
# (whether in gold, beta or alpha form) causes such combination to be covered by 
# the Licensed Patents. The patent license shall not apply to any other 
# combinations which include the Software. No hardware per se is licensed 
# hereunder. 

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY 
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
#--
#
#
use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ========================================================================
# Basic configuration files

my $CONFIG_DIR = "/etc/sysconfig"; # general driver config
my $OFED_CONFIG_DIR = "/etc/infiniband"; # general driver config
my $OFED_CONFIG = "$OFED_CONFIG_DIR/openib.conf";
my %KeepConfig = (); # keep track of past questions to config questions

my $TMP_CONF="/tmp/conf.$$";	# scratch file

sub check_config_dirs()
{
	check_dir("$BASE_DIR");
	check_dir("$IBA_CONFIG_DIR");
}

sub check_keep_config($$$)
{
	my($configFile) = shift();
	my($configDesc) = shift();
	my($default) = shift();

	my($prompt) = "";
	my $keep;

	if ("$configDesc" eq "")
	{
		$prompt="$ROOT$configFile";
	} else {
		$prompt="$configDesc ($ROOT$configFile)";
	}

	if (! exists $KeepConfig{"$ROOT$configFile"})
	{
		$keep=system "diff $ROOT$configFile $ROOT$configFile-sample > /dev/null 2>&1";
		if ($keep != 0)
		{
			NormalPrint "You have a modified $ROOT$configFile configuration file\n";
			$KeepConfig{"$ROOT$configFile"} = GetYesNo("Do you want to keep $prompt?", "$default");
		} else {
			$KeepConfig{"$ROOT$configFile"} = $keep;
		}
	}
	return $KeepConfig{"$ROOT$configFile"};
}

sub clear_keep_config($)
{
	my($configFile) = shift();

	delete $KeepConfig{"$ROOT$configFile"};
}

sub remove_conf_file($$)
{
	my($WhichDriver) = shift();
	my($ConfFile) = shift();

	if (-e "$ROOT$ConfFile") 
	{
		if (check_keep_config("$ConfFile", "$WhichDriver configuration file", "y"))
		{
			NormalPrint "Keeping $WhichDriver configuration file ($ROOT$ConfFile) ...\n";
		} else {
			system "rm -rf $ROOT$ConfFile";
		}
	}
	system "rm -rf $ROOT${ConfFile}-sample";
}

# remove a config file where a previous release used a different name for
# the file
sub remove_renamed_conf_file($$;@)
{
	my($WhichDriver) = shift();
	my($ConfFile) = shift();
	my(@OldConfFile_list) = @_;	# old config file names

	foreach my $OldConfFile ( @OldConfFile_list) {
		remove_conf_file("$WhichDriver", "$OldConfFile");
	}
	remove_conf_file("$WhichDriver", "$ConfFile");
}

sub install_conf_file($$$;@)
{
	my($WhichDriver) = shift();
	my($ConfFileDest) = shift();
	my($ConfFileSrc) = shift();
	my(@OldConfFileDest_list) = @_;	# optional
	my $diff_src_dest;
	my $diff_src_sample;
	my $diff_dest_sample;
	my $keep;
	my $need_copy = 1;

	# install an appropriate file into $ConfFileDest
	foreach my $OldConfFileDest ( @OldConfFileDest_list, $ConfFileDest ) {
		DebugPrint("Checking $ROOT$OldConfFileDest\n");
		next if ( ! -e "$ROOT$OldConfFileDest" );

		$diff_src_dest = system "diff $ConfFileSrc $ROOT$OldConfFileDest > /dev/null 2>&1";

		if ( ! -e "${OldConfFileDest}-sample" )
		{
			DebugPrint("No $ROOT${OldConfFileDest}-sample\n");
			$diff_src_sample=1;
			$diff_dest_sample=1;
		} else {
			$diff_src_sample = system "diff $ConfFileSrc $ROOT${OldConfFileDest}-sample > /dev/null 2>&1";
			$diff_dest_sample = system "diff $OldConfFileDest $ROOT${OldConfFileDest}-sample > /dev/null 2>&1";
		}
		DebugPrint("Comparisons: src vs old=$diff_src_dest, src vs oldsample=$diff_src_sample, old vs oldsample=$diff_dest_sample\n");

		if ($diff_src_dest != 0)
		{
			if ($diff_dest_sample == 0)
			{
				NormalPrint "You have an unmodified $WhichDriver configuration file from an earlier install\n";
				$keep =check_keep_config("$OldConfFileDest", "", "n");
			} elsif ($diff_src_sample != 0)
			{
				NormalPrint "You have a $WhichDriver configuration file from an earlier install\n";
				$keep=check_keep_config("$OldConfFileDest", "", "y");
			} else {
				NormalPrint "You have a modified $WhichDriver configuration file\n";
				$keep=check_keep_config("$OldConfFileDest", "", "y");
			}
			if ( $keep ) {
				if ("$OldConfFileDest" ne "$ConfFileDest") {
					# we are working on an old config file
					copy_data_file("$ROOT$OldConfFileDest", "$ConfFileDest");
					NormalPrint "Using $ROOT$OldConfFileDest as $ROOT$ConfFileDest...\n";
				} else {
					# we are working against the new supplied config file
					NormalPrint "Leaving $ROOT$OldConfFileDest unchanged...\n";
				}
				$need_copy=0;
				last;
			} # otherwise onto next file, if needed will copy new file below
		}
	}
	if ( $need_copy) {
		# no old files kept (or not found), use new release version
		NormalPrint "Updating $ROOT$ConfFileDest ...\n";
		copy_data_file("$ConfFileSrc", "$ConfFileDest");
	}
	foreach my $OldConfFileDest ( @OldConfFileDest_list ) {
		system "rm -rf $ROOT${OldConfFileDest}-sample";
	}
	copy_file("$ConfFileSrc", "${ConfFileDest}-sample", "$OWNER", "$GROUP", "ugo=r,u=r");
}

# after doing an rpm install, config files will be either installed (if new)
# or retained with the new version in .rpmnew
# this allows user to select which to keep as their present config file
sub copy_rpm_conf_file($$;@)
{
	my($WhichDriver) = shift();
	my($ConfFileDest) = shift();
	my(@OldConfFileDest_list) = @_;	# optional
	my($ConfFileSrc) = "$ROOT$ConfFileDest.rpmnew";

	if ( ! -e "$ROOT$ConfFileDest.rpmnew" )
	{
		# must be first install, Dest is the newest file
		# save a copy in case we overwrite it with an OldConfFileDest below
		system("cp $ROOT$ConfFileDest $TMP_CONF");
		$ConfFileSrc="$TMP_CONF"
	}
	install_conf_file($WhichDriver, $ConfFileDest, $ConfFileSrc, @OldConfFileDest_list);
	system("rm -f $ConfFileSrc");
}

# install a config file where a previous release used a different name for
# the file
sub install_renamed_conf_file($$$;@)
{
	my($WhichDriver) = shift();
	my($ConfFileDest) = shift();
	my($ConfFileSrc) = shift();
	my(@OldConfFileDest_list) = @_;	# in order that we consider them

	my $diff_src_dest;
	my $diff_src_sample;
	my $diff_dest_sample;

	if (! -e "$ROOT$ConfFileDest") {
		# first upgrade install, we consider old files as relevant
		# we want to do the install_conf_file algorithm
		# but use OldConfFileDest for all but file destination of copy
		install_conf_file("$WhichDriver","$ConfFileDest","$ConfFileSrc",@OldConfFileDest_list);
	} else {
		# don't touch old (if any), just perform normal upgrade/install
		foreach my $OldConfFileDest ( @OldConfFileDest_list ) {
			system "rm -rf $ROOT${OldConfFileDest}-sample";
		}
		install_conf_file("$WhichDriver","$ConfFileDest","$ConfFileSrc");
	}
}

# ===========================================================================
# functions to insert/remove config file additions bounded by markers

# 
# Deletes contents from start marker to end marker
# arg0 : Start marker
# arg1 : End Marker
# arg2 : Leave Marks in file after removing contents
# arg3 : Filename to operate on
#

sub del_marks($$$$)
{
	my($StartMark) = shift();
	my($EndMark) = shift();
	my($LeaveMarks) = shift();
	my($FileName) = shift();

	my($found_mark)=0;

	open (INPUT, "$FileName");
	open (OUTPUT, ">>$TMP_CONF");

	select (OUTPUT);
	while (($found_mark == 0) && ($_=<INPUT>)) {
		if (/$StartMark/) {
			$found_mark=1;
			if ($LeaveMarks) {
				print $_;
			}
		} else {
			print $_;
		}
	}

	while (($found_mark == 1) && ($_=<INPUT>)) {
		if (/$EndMark/) {
			$found_mark = 0;
			if ($LeaveMarks) {
				print $_;
			}
		} 
	}

	while ($_=<INPUT>) {
		print $_;
	}

	select(STDOUT);

	close (INPUT);
	close (OUTPUT);

	system "mv $TMP_CONF $FileName";
}

sub ins_marks($$$$)
{
	my($StartMark) = shift();
	my($EndMark) = shift();
	my($Contents) = shift();
	my($FileName) = shift();

	my($found_mark)=0;
	my($ReadEnd) = "";

	open (INPUT, "$FileName");
	open (OUTPUT, ">>$TMP_CONF");

	select (OUTPUT);
	while (($found_mark == 0) && ($_=<INPUT>)) {
		if (/$StartMark/) {
			$found_mark=1;
			print $_;
		} else {
			print $_;
		}
	}

	while (($found_mark == 1) && ($_=<INPUT>)) {
		if (/$EndMark/) {
			$found_mark = 0;
			$ReadEnd = $_;
		} 
	}

	print $Contents;
	print $ReadEnd;

	while ($_=<INPUT>) {
		print $_;
	}

	select(STDOUT);

	close (INPUT);
	close (OUTPUT);

	system "mv $TMP_CONF $FileName";
}

# gets contents including marks and compares to specified file
# returns 0 on match, 1 if different
sub compare_marks($$$$)
{
	my($StartMark) = shift();
	my($EndMark) = shift();
	my($FileName) = shift();
	my($CompareTo) = shift();

	my $is_different;
	my $found_inf;

	system "awk '/$StartMark/, /$EndMark/ {print}' $FileName > /tmp/tmp.conf";
	$found_inf = `diff /tmp/tmp.conf $CompareTo`;
	system "rm -f /tmp/tmp.conf";

	if ($found_inf eq "") 
	{
		$is_different = 0;
	} else 
	{
		$is_different = 1;
	}
	return $is_different
}

sub	edit_conf_file($$$$$)
{
	my($SourceFile) = shift();
	my($DestFile) = shift();
	my($FileDesc) = shift();
	my($StartMarker) = shift();
	my($EndMarker) = shift();

	my $is_different;
	my $found_inf;

	if (! -e "$ROOT$DestFile")
	{
		Abort "$FileDesc file $ROOT$DestFile is missing";
	}

	NormalPrint "Updating $FileDesc...\n";
	$found_inf = `grep "$StartMarker" $ROOT$DestFile`;

	# if the iba section does not exist then just add and then return
	if ($found_inf eq "") 
	{
		system "cat $SourceFile >> $ROOT$DestFile";
		return;
	}

	# found an iba section so lets extract the iba section and compare it to the new section
	$is_different = compare_marks ("$StartMarker", "$EndMarker", "$ROOT$DestFile", "$SourceFile");

	if ($is_different) 
	{
		NormalPrint "You have $FileDesc entries for IB drivers from an earlier install\n";
		if (check_keep_config($DestFile, "", "y"))
		{
			NormalPrint "Leaving $ROOT$DestFile unchanged...\n";
		} 
		else
		{
			# delete old section and markers
			del_marks ("$StartMarker", "$EndMarker", 0, "$ROOT$DestFile");
			# add in the new
			system "cat $SourceFile >> $ROOT$DestFile";
		}
	}
}

# ===========================================================================
# functions to edit simple config files

# This function supports reading parameters from config file which are
# actually shell scripts.  openib.conf, fastfabric.conf and the Linux network
# config files are examples of such.
# If the file or parameter does not exist, returns ""
sub read_simple_config_param($$)
{
	my $config_file=shift();
	my $parameter=shift();

	if ( ! -e "$config_file" ) {
		return "";
	}
	my $value=`. $config_file >/dev/null 2>/dev/null; echo \$$parameter`;
	chomp($value);
	return "$value";
}

sub edit_simple_config_file($$)
{
	my($FileName) = shift();
	my($changes) = shift();	# set of sed commands

	my $rc;

	$rc = system("sed $changes < $FileName > $TMP_CONF");
	if ($rc != 0) {
		system ("rm -rf $TMP_CONF >/dev/null 2>&1");
		return $rc;
	}

	$rc = system "mv $TMP_CONF $FileName";
	return $rc;
}

# ==========================================================================
# OFED configuration file

# OFED has a single start script but controls which ULPs are loaded via
# entries in $OFED_CONFIG (openib.conf)
# This file also controls options for OFED operation
# OFED configuration files are structured as a list of lines of the form:
# 	parameter=value
# There may be additional comment and whitespace lines
sub change_openib_conf_param($$)
{
	my $parameter=shift();
	my $newvalue=shift();

	VerbosePrint("edit $ROOT/$OFED_CONFIG: '$parameter=$newvalue'\n");
	if (0 != system("grep '^$parameter=' $ROOT/$OFED_CONFIG >/dev/null 2>/dev/null")) {
		# add parameter to file
		system ("echo '$parameter=$newvalue' >> $ROOT/$OFED_CONFIG 2>/dev/null");;
	} else {
		return edit_simple_config_file("$ROOT/$OFED_CONFIG",
			"-e 's/^$parameter=.*/$parameter=$newvalue/g'");
	}
}

sub read_openib_conf_param($$)
{
	my $parameter=shift();
	my $config_file=shift();	# if "", defaults to standard file

	if ( "$config_file" eq "" ) {
		$config_file="$ROOT/$OFED_CONFIG";
	}
	return read_simple_config_param($config_file, $parameter);
}

sub prompt_openib_conf_param($$$)
{
	my $parameter=shift();
	my $parameterDesc=shift();
	my $default=shift();

	my $prompt;
	my $value;
	if ("$parameterDesc" eq "") {
		$prompt="$parameter";
	} else {
		$prompt="$parameterDesc ($parameter)";
	}
	if (GetYesNo("Enable $prompt?", $default) == 1) {
		$value="yes"
	} else {
		$value="no"
	}
	change_openib_conf_param($parameter, $value);
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ===========================================================================
# startup scripts

# on Some Os's this configures startup file dependencies, especially for
# parallel startup optimizations
my $INSSERV_CONF="/etc/insserv.conf";
# where master copy of init scripts are installed
my $INIT_DIR = "/etc/init.d";
# Components and Sub-Components which user has asked to stop
# these could be utilities or drivers
my %StopFacility = ();

sub disable_autostart($)
{
	my($WhichStartup) = shift();

	# disable autostart but leave any kill scripts so stopped on shutdown
	# Note on SLES off removes kill scripts too, on redhat they remain
	system "chroot /$ROOT /sbin/chkconfig $WhichStartup off > /dev/null 2>&1";
	if ("$CUR_DISTRO_VENDOR" eq "SuSE" && "$CUR_VENDOR_VER" eq "ES12" && "$WhichStartup" eq "openibd")
	{
		system "chroot /$ROOT /usr/bin/systemctl disable $WhichStartup";
		system "chroot /$ROOT /usr/bin/systemctl mask $WhichStartup";
	}

}

sub enable_autostart($)
{
	my($WhichStartup) = shift();

	if ("$CUR_DISTRO_VENDOR" eq "SuSE" && "$CUR_VENDOR_VER" eq "ES12" && "$WhichStartup" eq "openibd")
	{
		system "chroot /$ROOT /usr/bin/systemctl unmask $WhichStartup";
		system "chroot /$ROOT /usr/bin/systemctl enable $WhichStartup";
	}

	# cleanup to be safe
	system "chroot /$ROOT /sbin/chkconfig --del $WhichStartup > /dev/null 2>&1";
	system "chroot /$ROOT /sbin/chkconfig --add $WhichStartup > /dev/null 2>&1";
	# make sure its enabled now
	system "chroot /$ROOT /sbin/chkconfig $WhichStartup on > /dev/null 2>&1";
}

# Is given startup script currently configured to autostart
sub IsAutostart($)
{
	my($WhichStartup) = shift();

	my $logoutput;               
	open(CHKCONFIG,"chroot /$ROOT /sbin/chkconfig --list $WhichStartup 2> /dev/null |") || Abort "Couldn't open a pipe for chkconfig\n";
	$logoutput = <CHKCONFIG>;
	close(CHKCONFIG);               
	# remove startup name from output, this way iba_mon is not mistaken for "on"
	$logoutput=~s/^$WhichStartup//;
	if (grep /:on/, $logoutput)
	{
		return 1;
	} elsif ( `ls $ROOT/etc/rc.d/rc3.d/S*$WhichStartup 2>/dev/null` ne "" ) {
		# this case is an old install being updated
		return 1;
	} else {
		return 0;
	}
}

# remove startup dependency
sub del_insserv_conf($$)
{
	my($WhichStartup) = shift();	# our startup script
	my($dependent) = shift();		# start up which must preceed it

	if ( -e "$ROOT/$INSSERV_CONF" )
	{
		system "sed -e '/^\$$dependent\[ \\t\]/s/\[ \\t\]+\\+$WhichStartup//' > $TMP_CONF < $ROOT/$INSSERV_CONF";
		system "mv $TMP_CONF $ROOT/$INSSERV_CONF";
		system "chmod 444 $ROOT/$INSSERV_CONF";
	}
}

# add startup dependency
sub add_insserv_conf($$)
{
	my($WhichStartup) = shift();	# our startup script
	my($dependent) = shift();		# startup which must preceed it

	if ( -e "$ROOT/$INSSERV_CONF" )
	{
		del_insserv_conf("$WhichStartup", "$dependent");
		system "sed -e '/^\$$dependent\[ \\t\]/s/\$/ +$WhichStartup/' > $TMP_CONF < $ROOT/$INSSERV_CONF";
		system "mv $TMP_CONF $ROOT/$INSSERV_CONF";
		system "chmod 444 $ROOT/$INSSERV_CONF";
	}
}

# Determine if the specified utility is running.
# Use 'pgrep' to check for a matching utility name.
#
# input:
#	[0] = name of utility as output by 'ps'.
# output:
#	0 == named utility not running (reported by pgrep).
#	1 == named utility is running.

sub IsUtilityRunning($)
{
	my($WhichUtility) = shift();

	my $result;

	if ( ROOT_is_set() )
	{
		return 0;
	}

	$result = system("/usr/bin/pgrep $WhichUtility >/dev/null 2>/dev/null");
	if ($result != 0 )
	{
		return 0
	} else {
		return 1
	}
}

# prompts and stops a driver or autostart utility
sub check_stop_facility($$)
{
	my($WhichFacility) = shift();
	my($prompt) = shift();

	if ( ROOT_is_set() )
	{
		return 0;
	}
	if (! exists $StopFacility{$WhichFacility})
	{
		$StopFacility{$WhichFacility} = GetYesNo("Stop $prompt now?", "n");
	}
	return $StopFacility{$WhichFacility};
}

sub stop_utility($$$)
{
	my($UtilityDesc) = shift();
	my($WhichUtility) = shift();	# utility executable in ps
	my($InitScript) = shift();

	my($retval)=0;
	my $prompt;

	if ( ROOT_is_set() )
	{
		return;
	}
	if ( "$UtilityDesc" eq "" )
	{
		$prompt="$WhichUtility";
	} else {
		$prompt="$UtilityDesc ($WhichUtility)";
	}
	if (IsUtilityRunning("$WhichUtility") == 1) 
	{
		if (check_stop_facility("$WhichUtility", "$prompt") == 1)
		{
			if (-e "$INIT_DIR/$InitScript" )
			{
				system "$INIT_DIR/$InitScript stop";
				$retval=1;
			} else {
				system "/usr/bin/pkill $WhichUtility";
				$retval=1;
			}
			$StopFacility{$WhichUtility} = 0;	# ask again if find still running
		}
	}
	return $retval;
}

sub start_utility($$$$)
{
	my($UtilityDesc) = shift();
	my($UtilityDir) = shift();
	my($WhichUtility) = shift();	# executable in $UtilityDir and found in ps
	my($InitScript) = shift();

	my $prompt;

	if ( ROOT_is_set() )
	{
		return;
	}
	if ( "$UtilityDesc" eq "" )
	{
		$prompt="$WhichUtility";
	} else {
		$prompt="$UtilityDesc ($WhichUtility)";
	}
	if (-e "/$UtilityDir/$WhichUtility" )
	{
		if (IsUtilityRunning("$WhichUtility") == 1) 
		{
			print "$prompt already started...\n";
			if (GetYesNo("Restart $prompt now?", "n") == 1)
			{
				if (-e "$INIT_DIR/$InitScript" )
				{
					system "$INIT_DIR/$InitScript restart";
				} else {
					system "/usr/bin/pkill $WhichUtility";
				}
			}
		} else {
			if (GetYesNo("Start $prompt now?", "n") == 1)
			{
				if (-e "$INIT_DIR/$InitScript" )
				{
					system "$INIT_DIR/$InitScript start";
				} else {
					system "/usr/bin/pkill $WhichUtility";
				}
			}
		}
	}
}

sub remove_startup($)
{
	my($WhichStartup) = shift();

	# test added to avoid duplicate message
	if ( -e "$ROOT$INIT_DIR/$WhichStartup" )
	{
		print "Removing $WhichStartup init scripts...\n";
	}
	# to be safe, remove and disable it even if missing
	disable_autostart($WhichStartup);
	system "chroot /$ROOT /sbin/chkconfig --del $WhichStartup > /dev/null 2>&1";
	system "rm -f $ROOT$INIT_DIR/$WhichStartup";
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ============================================================================
# Driver file management

# path to source directories for each set of kernel drivers,
# such as <./bin/$ARCH/*>;
my @supported_kernels;
my @module_dirs = ();

my $RunDepmod=0;	# do we need to run depmod
sub	verify_modtools()
{
	my $look_str;
	my $look_len;
	my $ver;
	my $mod_ver;

	$look_str = "insmod version ";
	$look_len = length ($look_str);
	$ver = `$ROOT/sbin/insmod -V 2>&1 | grep \"$look_str\"`;
	chomp $ver;
	$mod_ver = substr ($ver, $look_len - 1, length($ver)-$look_len+1);
	$_ = $mod_ver;
	/2\.[34]\.[0-9]+/;
	#$MOD_UTILS_REV;
	if ($& eq "")
	{
		NormalPrint "Unable to proceed, modutils tool old: $mod_ver\n";
		Abort "Install newer version of modutils 2.3.15 or greater" ;
	}
}

sub check_depmod()
{
	if ($RunDepmod == 1 )
	{
		print_separator;
		print "Generating module dependencies...\n";
		LogPrint "Generating module dependencies: /sbin/depmod -aev\n";
		system "chroot /$ROOT /sbin/depmod -aev > /dev/null 2>&1";
		$RunDepmod=0;
		return 1;
	}
	return 0;
}

# is the given driver available on the install media
sub available_driver($$)
{
	my($srcdir) = shift();
	my($WhichDriver) = shift();

	$WhichDriver .= $DRIVER_SUFFIX;
	return ( -e "$srcdir/$CUR_OS_VER/$DBG_FREE/$WhichDriver" );
}

# is the given driver installed on this system
sub installed_driver($$)
{
	my($WhichDriver) = shift();
	my($subdir) = shift();
	$WhichDriver .= $DRIVER_SUFFIX;
	return (-e "$ROOT/lib/modules/$CUR_OS_VER/$subdir/$WhichDriver" );
}

# create iba kernel module directory
sub create_driver_dirs($)
{
	my($subdir) = shift();

	my $supported_kernel;
	foreach my $supported_kernel_path ( @supported_kernels ) 
	{    
		$supported_kernel = my_basename($supported_kernel_path);
		if ( -d "$ROOT/lib/modules/$supported_kernel" )
		{
			make_dir("/lib/modules/$supported_kernel/$subdir", "$OWNER", "$GROUP", "ugo=rx,u=rwx");
		}
	}
}

# remove iba kernel module directories
sub remove_driver_dirs($)
{
	my($subdir) = shift();

	my $supported_kernel;
	if ( "$subdir" ne "" ) {
		foreach my $supported_kernel_path ( @supported_kernels ) 
		{    
			$supported_kernel = my_basename($supported_kernel_path);
			if ( -d "$ROOT/lib/modules/$supported_kernel/$subdir" )
			{
				system "rm -rf $ROOT/lib/modules/$supported_kernel/$subdir";
			}
		}
	}

	# remove SDK stuff
	system "rm -rf $ROOT/etc/iba";
}

sub copy_driver($$$)
{
	# TBD put drivers in /lib/modules instead of /lib/modules/iba
	my($WhichDriver) = shift();
	my($subdir) = shift();
	my($verbosity) = shift(); # verbose or silent

	$WhichDriver .= $DRIVER_SUFFIX;

	if ( "$verbosity" ne "silent" ) {
		print ("Copying ${WhichDriver}...\n");
	}
	$RunDepmod=1;
	need_reboot();
	my $supported_kernel;

	foreach my $supported_kernel_path ( @supported_kernels ) 
	{    
		$supported_kernel = my_basename($supported_kernel_path);

		if ( -d "$ROOT/lib/modules/$supported_kernel" )
		{             
			copy_driver_file( "$supported_kernel_path/$DBG_FREE/$WhichDriver",
								"/lib/modules/$supported_kernel/$subdir" );
		}
	}
}

# copy a single driver from srcdir for current OS only
sub copy_driver2($$$$)
{
	my($WhichDriver) = shift();
	my($srcdir) = shift();
	my($subdir) = shift();
	my($verbosity) = shift();	# verbose or silent

	$WhichDriver .= $DRIVER_SUFFIX;

	if ( "$verbosity" ne "silent" ) {
		printf ("Copying ${WhichDriver}...\n");
	}
	$RunDepmod=1;
	need_reboot();
	copy_driver_file( "$srcdir/$WhichDriver", "/lib/modules/$CUR_OS_VER/$subdir" );
}

sub remove_driver($$$)
{
	my($WhichDriver) = shift();
	my($subdir) = shift();
	my($verbosity) = shift();	# verbose or silent

	my $dd;

	$WhichDriver .= $DRIVER_SUFFIX;
	if ( "$verbosity" ne "silent" ) {
		print ("Removing ${WhichDriver}...\n");
	}
	LogPrint ("Removing $subdir/${WhichDriver}...\n");
	$RunDepmod=1;
	need_reboot();
	foreach $dd (@module_dirs)
	{
		if ( -e "$ROOT$dd/$subdir/$WhichDriver" )
		{
			system "rm -rf $ROOT$dd/$subdir/$WhichDriver";  
		}
		if ( "$subdir" ne "" && isDirectoryEmpty("$ROOT$dd/$subdir") )
		{
	    	system "rm -rf $ROOT$dd/$subdir"
		}
	}
}

# Determine if the specified kernel module is loaded.
# Scan output of 'lsmod' for a matching module name.
#
# input:
#	[0] = name of module as output by 'lsmod'.
# output:
#	0 == named module not loaded (reported by lsmod).
#	1 == named module is loaded.

sub IsModuleLoaded($)
{
	my($WhichModule) = shift();

	my($found) = 0;
	my($TmpFile) = "/usr/tmp/lsmod.out";

	if ( ROOT_is_set() ) {
		return 0;
	}

	system("/sbin/lsmod > ".$TmpFile);

	open (INPUT, $TmpFile) || return 0;
	while ( ($_=<INPUT>) ) {
		if (/^$WhichModule\s/) {
			$found=1;
			last;
		}
	}
	close(INPUT);

	system("rm -f ".$TmpFile);

	return $found;
}

sub stop_driver($$$)
{
	my($DriverName) = shift();	# descriptive name of driver
	my($WhichDriver) = shift();	# actual linux module name
	my($InitScript) = shift();	# if "" use rmmod on WhichDriver

	my($retval)=0;
	my $prompt;

	if ( ROOT_is_set() ) {
		return;
	}
	if ( "$DriverName" eq "" ) {
		$prompt="$WhichDriver";
	} else {
		$prompt="$DriverName ($WhichDriver)";
	}
	if (IsModuleLoaded("$WhichDriver") == 1) 
	{
		if (check_stop_facility("$WhichDriver", "$prompt driver") == 1)
		{
			if (-e "$INIT_DIR/$InitScript" )
			{
				system "$INIT_DIR/$InitScript stop";
				$retval=1;
			} else {
				system "/sbin/rmmod $WhichDriver";
				$retval=1;
			}
			$StopFacility{$WhichDriver} = 0;	# ask again if find still running
		}
	}
	return $retval;
}

sub start_driver($$$$)
{
	my($DriverName) = shift();
	my($WhichDriver) = shift();
	my($subdir) = shift();
	my($InitScript) = shift();

	my $prompt;

	$WhichDriver .= $DRIVER_SUFFIX;
	if ( ROOT_is_set() )
	{
		return;
	}
	if ( "$DriverName" eq "" )
	{
		$prompt="$WhichDriver";
	} else {
		$prompt="$DriverName ($WhichDriver)";
	}
	if (-e "/lib/modules/$CUR_OS_VER/$subdir/$WhichDriver" )
	{
		if (IsModuleLoaded("$WhichDriver") == 1) 
		{
			print "$prompt driver already started...\n";
			if (GetYesNo("Restart $prompt driver now?", "n") == 1)
			{
				if (-e "$INIT_DIR/$InitScript" )
				{
					system "$INIT_DIR/$InitScript restart";
				} else {
					system "/sbin/rmmod $WhichDriver";
				}
			}
		} else {
			if (GetYesNo("Start $prompt driver now?", "n") == 1)
			{
				if (-e "$INIT_DIR/$InitScript" )
				{
					system "$INIT_DIR/$InitScript start";
				} else {
					system "/sbin/rmmod $WhichDriver";
				}
			}
		}
	}
}

# ============================================================================
# Device identification

# Identify speed of PCIe link for a Mellanox HCA
# This routine is from OFED, but is not yet used.  OFED only used it to
# provide a verbose message during install
sub check_pcie_link
{
	my $setpci = '/sbin/setpci';
	my $lspci = '/sbin/lspci';
    if (open (PCI, "$lspci -d 15b3: -n|")) {
        while(<PCI>) {
            my $devinfo = $_;
            $devinfo =~ /(15b3:[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F])/;
            my $devid = $&;
            my $link_width = `$setpci -d $devid 72 | cut -b1`;
            chomp $link_width;

            print BLUE "Device ($devid):\n";
            print "\t" . `$lspci -d $devid`;

            if ( $link_width eq "8" ) {
                print "\tLink Width: 8x\n";
            }
            else {
                print "\tLink Width is not 8x\n";
            }
            my $link_speed = `$setpci -d $devid 72 | cut -b2`;
            chomp $link_speed;
            if ( $link_speed eq "1" ) {
                print "\tLink Speed: 2.5Gb/s\n";
            }
            elsif ( $link_speed eq "2" ) {
                print "\tLink Speed: 5Gb/s\n";
            }
            else {
                print "\tLink Speed: Unknown\n";
            }
            print "", RESET "\n";
        }
        close (PCI);
    }
}
#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# =========================================================================
# Component installation state

# constants for component state/action tracking during menus
my $State_Uninstall = 0;
my $State_Install = 1;
my $State_UpToDate = 2;
my $State_DoNotInstall = 3;
my $State_DoNotAutoInstall = 4;	# valid only in DefaultInstall, must explicitly select

sub component_start_prompts();
sub disable_components(@);

# indicate if given state reflects a component which will be on the system
# after processing the present menu selections
# states:
# $State_Uninstall - make sure not on system (Uninstall)
# $State_Install - install on system (Install/Upgrade/Re-Install)
# $State_UpToDate - leave as is on system (Installed/Up To Date)
# $State_DoNotInstall - leave as is not on system (Do Not Install)
sub will_be_on_system($)
{
	my $state = shift();

	return ($state == $State_Install || $state == $State_UpToDate);
}

# state returned:
# $State_Uninstall - make sure not on system (Uninstall)
# $State_Install - install on system (Install/Upgrade/Re-Install)
# $State_UpToDate - leave as is on system (Installed/Up To Date)
# $State_DoNotInstall - leave as is not on system (Do Not Install)
sub setstate($$$$)
{
	my $isinstalled = shift();   
	my $available   = shift();
	my $isupgrade   = shift();
	my $defaultstate= shift();	# default if available and ! installed

	if (! $available && $isinstalled && !$isupgrade){ return $State_UpToDate; }
	if (! $available && ! $isinstalled )			{ return $State_DoNotInstall; }
	if (! $available )				                { return $State_Uninstall; }
	if ($isinstalled && !$isupgrade)				{ return $State_UpToDate; }
	if ($isinstalled)								{ return $State_Install; }
	# available and not installed
	if ($defaultstate == $State_DoNotAutoInstall)	{ return $State_DoNotInstall; }
	return $defaultstate;	# typcally State_Install
}

# state returned:
# $State_Uninstall - make sure not on system (Uninstall)
# $State_Install - install on system (Install/Upgrade/Re-Install)
# $State_UpToDate - leave as is on system (Installed/Up To Date)
# $State_DoNotInstall - leave as is not on system (Do Not Install)
sub shiftstate($$$$)
{
	my $state       = shift();
	my $isinstalled = shift();   
	my $available   = shift();
	my $isupgrade   = shift();

	if (! $available && $isinstalled && ! $isupgrade) {
		return ($state==$State_UpToDate)?$State_Uninstall:$State_UpToDate;
	}
	if (! $available && ! $isinstalled ) {
		return ($state==$State_DoNotInstall)?$State_Uninstall:$State_DoNotInstall;
	}
	if (! $available ) {
		return $State_Uninstall;
	}
	if ($isinstalled && !$isupgrade) {
		return ($state==$State_UpToDate)?$State_Install
				:($state==$State_Install)?$State_Uninstall
				:$State_UpToDate;
	}
	if ($isinstalled ) {
		return ($state==$State_Install)?$State_Uninstall:$State_Install;
	}
	# available and not installed
	return ($state==$State_Uninstall)?$State_Install
			:($state==$State_Install)?$State_DoNotInstall:$State_Uninstall;
}

sub InstallStateToStr($)
{
	my $state = shift();

	if ($state == $State_Uninstall) {
		return "Uninstall";
	} elsif ($state == $State_Install) {
		return "Install";
	} elsif ($state == $State_UpToDate) {
		return "UpToDate";
	} elsif ($state == $State_DoNotInstall) {
		return "DoNotInstall";
	} elsif ($state == $State_DoNotAutoInstall) {
		return "DoNotAutoInstall";
	} else {
		return "INVALID";
	}
}

# caller has output 24 characters, we have 55 left to play with
# (avoid using last column so don't autowrap terminal)
sub printInstallState($$$$)
{
	my $installed = shift();
	my $uninstall = shift();
	my $boldmessage = shift();
	my $message   = shift();

	if ($uninstall )
	{
		print   RED, "[  Uninstall  ] ", RESET;
	} elsif ($installed ) {
		print GREEN, "[  Installed  ] ", RESET;
	} else {
		print        "[Not Installed] ";
	}
	if ("$message" ne "" && $boldmessage) {
		print BOLD, RED "$message", RESET, "\n";
	} else {
		print "$message\n";
	}
	return;
}

# states:
# $State_Uninstall - make sure not on system (Uninstall)
# $State_Install - install on system (Install/Upgrade/Re-Install)
# $State_UpToDate - leave as is on system (Installed/Up To Date)
# $State_DoNotInstall - leave as is not on system (Do Not Install)
sub printInstallAvailableState($$$$$$)
{
	my $installed = shift();
	my $available = shift();
	my $isupgrade = shift();
	my $state     = shift();
	my $boldmessage = shift();
	my $message   = shift();

	if ( $state == $State_Uninstall )
	{
		print RED, "[  Uninstall  ]", RESET;
	} elsif ( $state == $State_Install) {
		if ($installed)
		{           
			if ( $isupgrade ) 
			{       
				print GREEN, "[   Upgrade   ]", RESET;
			} else {
				print "[ Re-Install  ]";
			}
		} else {
			print           "[   Install   ]";
		}
	} elsif ($state == $State_UpToDate) {
		print "[ Up To Date  ]";
	} elsif ($state == $State_DoNotInstall) {
		print "[Don't Install]";
	}

	if ( $available )
	{
		print "[Available] ";
	} else {
		print BOLD, RED "[Not Avail] ", RESET;
	}
	if ("$message" ne "" && $boldmessage) {
		print BOLD, RED "$message", RESET, "\n";
	} else {
		print "$message\n";
	}

	return;
}

# =======================================================================
# Component processing

# indicate which main INSTALL is being used.  This can influence error checks
# and assumptions made by individual components
my $MainInstall = "";

# function must be supplied if any components set ComponentInfo{}{HasFirmware}
sub update_hca_firmware();

# these variables must be initialized by main program to control the
# data driven component menus and functions in this section
my $Default_Install=0;	# -a option used to select default install of All
my $Default_Upgrade=0;	# -U option used to select default upgrade of installed
my $Default_Uninstall=0;	# -u option used to select default uninstall of All
my $Default_SameAutostart=0; # -n option used to default install, preserving autostart values
my $Default_CompInstall=0;	# -i option used to select default install of Default_Components
my $Default_CompUninstall=0;	# -e option used to select default uninstall of Default_Components
my %Default_Components = ();		# components selected by -i or -e
my $Skip_FirmwareUpgrade=0;	# -f option used to select skipping firmware upgrade
my $Default_Autostart=0;	# -s option used to select default autostart of All
my $Default_DisableAutostart=0; # -D option used to select default disabling of autostart for Default_DisabledComponents
my %Default_DisabledComponents = ();		# components selected by -D
my $Default_EnableAutostart=0; # -E option used to select default enabling of autostart for Default_EnabledComponents
my %Default_EnabledComponents = ();		# components selected by -E

	# Names of supported install components
	# must be listed in depdency order such that prereqs appear 1st
my @Components = ();

# Sub components for autostart processing
my @SubComponents = ();

# components/subcomponents for autostart processing
my @AutostartComponents = ();

	# an additional "special" component which is always installed when
	# we install/upgrade anything and which is only uninstalled when everything
	# else has been uninstalled.  Typically this will be the iba_config
	# file and related files absolutely required by it (such as wrapper_version)
my $WrapperComponent = "";

# This provides more detailed information about each Component in @Components
# since hashes are not retained in the order specified, we still need
# @Components and @SubComponents to control install and menu order
# Fields are as follows:
#	Name => full name of component/subcomponent for prompts
# 	DefaultInstall => default installation (State_DoNotInstall,
# 					  State_DoNotAutoInstall or State_Install)
#					  used only when available and ! installed
#	SrcDir => directory name within install media for component
#	DriverSubdir => directory within /lib/modules/$CUR_OS_VERSION/ to
#					install driver to.  Set to "" if no drivers in component
#					set to "." if no subdir
# 	PreReq => other components which are prereqs of a given
#				component/subcomponent
#				Need space before and after each component name to
#				facilitate compares so that compares do not mistake names
#				such as mpidev for mpi
#	CoReq =>  other components which are coreqs of a given component
#				Note that CoReqs can also be listed as prereqs to provide
#				install verification as each component is installed,
#				however prereqs should only refer to items earlier in the list
#				Need space before and after each component name to
#				facilitate compares so that compares do not mistake names
#				such as mpidev for mpi
#	Hidden => component should not be shown in menus/prompts
#			  used for hidden PreReq.  Hidden components can't HasStart
#			  nor HasFirmware
#	Disabled =>  components/subcomponents which are disabled from installation
#	HasStart =>  components/subcomponents which have autostart capability
#	DefaultStart =>  should autostart default to Enable (1) or Disable (0)
#				Not needed/ignored unless HasStart=1
# 	StartPreReq => other components/subcomponents which must be autostarted
#				before autostarting this component/subcomponent
#				Not needed/ignored unless HasStart=1
#				Need space before and after each component name to
#				facilitate compares so that compares do not mistake names
#				such as mpidev for mpi
#	StartComponents => components/subcomponents with start for this component
#				if a component has a start script 
#				list the component as a subcomponent of itself
#	HasFirmware =>  components which need HCA firmware update after installed
#
# Note both Components and SubComponents are included in the list below.
# Components require all fields be supplied
# SubComponents only require the following fields:
#	Name, PreReq (should reference only components), HasStart, StartPreReq,
#	DefaultStart
my %ComponentInfo = ();
	# translate from startup script name to component/subcomponent name
my %StartupComponent = ();
	# has component been installed since last configured autostart
my %ComponentWasInstalled = ();

# constants for autostart functions $configure argument
my $Start_Unspecified=0;
my $Start_NoStart=1;
my $Start_Start=2;

sub ShowComponents()
{
	foreach my $comp ( @Components )
	{
		if (! $ComponentInfo{$comp}{'Hidden'}) {
			print " $comp";
		}
	}
	print "\n";
}

# return 1 if $comp has a prereq of $prereq, 0 otherwise
sub comp_has_prereq_of($$)
{
	my($comp) = shift();
	my($prereq) = shift();

	if ($ComponentInfo{$comp}{'PreReq'} =~ / $prereq /) {
		return 1;
	} else {
		return 0;
	}
}

# return 1 if $comp has a coreq of $coreq, 0 otherwise
sub comp_has_coreq_of($$)
{
	my($comp) = shift();
	my($coreq) = shift();

	if ($ComponentInfo{$comp}{'CoReq'} =~ / $coreq /) {
		return 1;
	} else {
		return 0;
	}
}

# return 1 if $comp has a prereq or coreq of $req, 0 otherwise
sub comp_has_req_of($$)
{
	my($comp) = shift();
	my($req) = shift();

	return (comp_has_prereq_of($comp, $req) || comp_has_coreq_of($comp, $req));
}
# return 1 if $comp has a prereq of $prereq, 0 otherwise
sub comp_has_startprereq_of($$)
{
	my($comp) = shift();
	my($prereq) = shift();

	if ($ComponentInfo{$comp}{'StartPreReq'} =~ / $prereq /) {
		return 1;
	} else {
		return 0;
	}
}

# for comp_is_available we specially handle the case of function not found
# in which case eval returns ""
# all other component functions against install media will have called
# comp_is_available first, so they need not be protected by this test
sub comp_is_available($)
{
	my $comp = shift();
	my $rc;

	if ($ComponentInfo{$comp}{'Disabled'}) {
		return 0;
	}
	$rc = eval "available_$comp()";
	if ( "$rc" eq "" ) {
		return 0;	# $comp not loaded
	} else {
		return $rc;
	}
}

# return version string for component on install media
# only valid if comp_is_available is TRUE
sub comp_media_version($)
{
	my $comp = shift();

	my $result = eval "media_version_$comp()";
	chomp $result;
	return $result;
}

# for comp_is_installed we specially handle the case of function not found
# in which case eval returns ""
# all other component functions against system itself will have called
# comp_is_installed first, so they need not be protected by this test
sub comp_is_installed($)
{
	my $comp = shift();
	my $rc;

	$rc = eval "installed_$comp()";
	if ( "$rc" eq "" ) {
		return 0;	# $comp not loaded
	} else {
		return $rc;
	}
}

# return version string for component on system
# only valid if comp_is_installed is TRUE
sub comp_installed_version($)
{
	my $comp = shift();

	my $result = eval "installed_version_$comp()";
	chomp $result;
	return $result;
}

# return TRUE if component is installed and up to date
# return FALSE if not installed, or not same version as media
# typically only called when component is available, returns
# FALSE if component not available
sub comp_is_uptodate($)
{
	my $comp = shift();

	# safety check
	if (! comp_is_available("$comp") ) {
		return 0;
	}
	if (! comp_is_installed("$comp")) {
		return 0;
	}
	# available and installed, compare versions
	return (comp_installed_version($comp) eq comp_media_version($comp));
}

# check if all prereqs of $comp have been installed
# returns: 1 - all ok, 0 - some prereqs missing
sub check_prereqs($)
{
	my($comp) = shift();

	foreach my $c ( @Components )
	{
		if (comp_has_prereq_of($comp, $c) && ! comp_is_installed("$c") )
		{
			NormalPrint "Unable to Install $ComponentInfo{$comp}{'Name'}, prereq $ComponentInfo{$c}{'Name'} not installed\n";
			return 0;
		}
	}
	return 1;
}

# build processing for the given component
# returns 0 on success, 1 on failure
# only valid if comp_is_available is TRUE
sub comp_build($$$$$)
{
	my $comp = shift();
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild

	LogPrint "Building $ComponentInfo{$comp}{'Name'} for $osver using '$build_temp'\n";
	return eval "build_$comp('$osver',$debug,'$build_temp',$force)";
}

# special hook for build processing for the given component within OFED build
# returns 1 if build should be done, 0 if not
# only valid for subset of components and if comp_is_available is TRUE
sub comp_ofed_need_build($$$$)
{
	my $comp = shift();
	my $osver = shift();
	my $force = shift();	# should we force build
	my $prompt = shift();	# should we prompt user about build

	return eval "ofed_need_build_$comp('$osver',$force,$prompt)";
}

# special hook for build processing for the given component within OFED build
# returns 0 on success, >0 on failure
# only valid for subset of components and if comp_is_available is TRUE
sub comp_ofed_check_build_dependencies($$)
{
	my $comp = shift();
	my $osver = shift();

	return eval "ofed_check_build_dependencies_$comp('$osver')";
}

# special hook for build processing for the given component within OFED build
# returns 0 on success, 1 on failure
# only valid for subset of components and if comp_is_available is TRUE
sub comp_ofed_build($$$$)
{
	my $comp = shift();
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build

	LogPrint "Building $ComponentInfo{$comp}{'Name'} for $osver using '$build_temp'\n";
	return eval "ofed_build_$comp('$osver',$debug,'$build_temp')";
}

# before preinstall determine if present settings will require all
# installed components to be reinstalled
# returns "all" if need to reinstall all UpToDate components
# returns "this" if need to reinstall this component even if up to date
# returns "no" if no need to reinstall this component even if up to date
# only valid if comp_is_available is TRUE
sub comp_need_reinstall($$$)
{
	my $comp = shift();
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return eval "need_reinstall_$comp('$install_list', '$installing_list')";
}

# check presence of OS prereqs for the given component
# returns 0 on success, 1 on failure
# only valid if comp_is_available is TRUE
# for backward compatibility with old comp.pl files
# we specially handle the case of function not found
# in which case eval returns ""
sub comp_check_os_prereqs($)
{
	my $comp = shift();
	my $rc;

	DebugPrint "Checking OS Prereqs for $ComponentInfo{$comp}{'Name'}\n";
	$rc = eval "check_os_prereqs_$comp()";
	DebugPrint "Done: rc='$rc'\n";
	if ( "$rc" eq "" ) {
		return 0;	# $comp not loaded
	} else {
		return $rc;
	}
}

# preinstall processing for the given component
# returns 0 on success, 1 on failure
# only valid if comp_is_available is TRUE
sub comp_preinstall($$$)
{
	my $comp = shift();
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return eval "preinstall_$comp('$install_list', '$installing_list')";
}

# install the given component
# only valid if comp_is_available is TRUE
sub comp_install($$$)
{
	my $comp = shift();
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	# sanity check, should not get here if false
	if (! comp_is_available($comp) ) {
		return;
	}
	print_separator;
	# this will catch failures in install of prereqs
	if (! check_prereqs($comp)) {
		return;
	}

	eval "install_$comp('$install_list', '$installing_list')";
}

# postinstall processing for the given component
# only valid if comp_is_available is TRUE
sub comp_postinstall($$$)
{
	my $comp = shift();
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	eval "postinstall_$comp('$install_list', '$installing_list')";
}

# uninstall the given component
# typically only called if comp_is_available is TRUE
# or comp_is_installed is TRUE
# however could be called when not available and not installed in which
# case could be an empty function, in which case we can simply ignore
# eval's "" return
sub comp_uninstall($$$)
{
	my $comp = shift();
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_separator;
	if ($ComponentInfo{$comp}{'HasStart'}) {
		disable_components(@{ $ComponentInfo{$comp}{'StartComponents'} });
	}
	eval "uninstall_$comp('$install_list', '$uninstalling_list')";
}

# start the given component now
# only valid if comp_is_installed is TRUE
sub comp_start($)
{
	my $comp = shift();

	eval "start_$comp()";
}

# stop the given component now
# can be called even if comp_is_installed is FALSE, in which case can be a noop
sub comp_stop($)
{
	my $comp = shift();

	eval "stop_$comp()";
}

# determine if the given component is configured for Autostart at boot
sub comp_IsAutostart2($)
{
	my $comp = shift();

	return eval "IsAutostart2_$comp()";
}
# get autostart desc for the given component
sub comp_autostart_desc($)
{
	my $comp = shift();

	my $desc = eval "autostart_desc_$comp()";
	if ( "$desc" eq "" ) {
		$desc = $ComponentInfo{$comp}{'Name'};
	}
	return $desc;
}
# enable autostart for the given component
sub comp_enable_autostart2($$)
{
	my $comp = shift();
	my $quiet = shift();

	if ( ! comp_IsAutostart2($comp) == 1 )
	{
		if (! $quiet) {
			my $desc = comp_autostart_desc($comp);
			NormalPrint "Enabling autostart for $desc\n";
		}
	}
	eval "enable_autostart2_$comp()";
}
# disable autostart for the given component
sub comp_disable_autostart2($$)
{
	my $comp = shift();
	my $quiet = shift();

	if ( comp_IsAutostart2($comp) == 1 )
	{
		if (! $quiet) {
			my $desc = comp_autostart_desc($comp);
			NormalPrint "Disabling autostart for $desc\n";
		}
	}

	eval "disable_autostart2_$comp()";
}

sub DumpComponents($)
{
	my $allow_install = shift();

	if (! DebugPrintEnabled() ) {
		return;
	}
	DebugPrint("\nComponents:\n");
	foreach my $comp ( @Components ) {
		DebugPrint("   $comp: '$ComponentInfo{$comp}{'Name'}' SrcDir: $ComponentInfo{$comp}{'SrcDir'}\n");
		DebugPrint("           DefaultInstall: ".InstallStateToStr($ComponentInfo{$comp}{'DefaultInstall'})." DriverSubdir: $ComponentInfo{$comp}{'DriverSubdir'}\n");
		DebugPrint("           PreReq: $ComponentInfo{$comp}{'PreReq'} CoReq: $ComponentInfo{$comp}{'CoReq'}\n");
		DebugPrint("           Hidden: $ComponentInfo{$comp}{'Hidden'} HasStart: $ComponentInfo{$comp}{'HasStart'} HasFirmware: $ComponentInfo{$comp}{'HasFirmware'}\n");
		DebugPrint("           StartPreReq: $ComponentInfo{$comp}{'StartPreReq'} StartComponents: $ComponentInfo{$comp}{'StartComponents'}\n");
		if ($allow_install) {
			my $avail = comp_is_available($comp);
			DebugPrint("           IsAvailable: $avail");
			if ($avail) {
				DebugPrint("           MediaVersion: ".comp_media_version($comp));
			}
			DebugPrint("\n");
		}
		my $installed = comp_is_installed($comp);
		DebugPrint("           IsInstalled: $installed");
		if ($installed) {
			DebugPrint("           InstalledVersion: ".comp_installed_version($comp));
		}
		DebugPrint("\n");
	}

	DebugPrint("\nSubComponents:\n");
	foreach my $comp ( @SubComponents ) {
		DebugPrint("   $comp: '$ComponentInfo{$comp}{'Name'}'\n");
		DebugPrint("           PreReq: $ComponentInfo{$comp}{'PreReq'} CoReq: $ComponentInfo{$comp}{'CoReq'}\n");
		DebugPrint("           HasStart: $ComponentInfo{$comp}{'HasStart'}\n");
		DebugPrint("           StartPreReq: $ComponentInfo{$comp}{'StartPreReq'}\n");
	}
}

# make sure every component is stopped
sub stop_all_components()
{
	my $comp;
	my $i;

	if ( ROOT_is_set() )
	{
		return;
	}
	print_separator;
	print "Stopping loaded drivers...\n";
	# perform the stop, work backwards through list
	for ($i=scalar(@Components)-1; $i >= 0; $i--)
	{
		$comp = $Components[$i];
		if ( $ComponentInfo{$comp}{'HasStart'} )
		{
			comp_stop($comp);
		}
	}
}


# build @AutostartComponents listing all components and subcomponents which
# have autostart capability.  They are listed in prefered startup order
sub build_autostart_components_list()
{
	my $comp;
	# only need to do once
	if (scalar(@AutostartComponents) != 0 ) {
		return;
	}
	foreach $comp ( @Components )
	{
		if ( $ComponentInfo{$comp}{'HasStart'} )
		{
			# StartComponents will list Components and SubComponents which
			# have start capability
			@AutostartComponents = ( @AutostartComponents, @{ $ComponentInfo{$comp}{'StartComponents'} })
		}
	}
}

# disable autostart for a list of components and
# all components dependent on given component
sub disable_components(@)
{
	my @disabled = ( @_ );
	my %need_disable = ();
	my %dont_need_disable = ();
	my $comp;

	build_autostart_components_list;
	foreach $comp ( @disabled ) {
		$need_disable{$comp} = 1;
		DebugPrint("disable $comp explicitly\n");
	}
	my $done = 0;
	while ( ! $done) {
		$done=1;
		foreach $comp ( @disabled ) {
			# comp will be disabled, any which depend on it as a
			# startprereqs will also be disabled
			foreach my $c ( @AutostartComponents ) {
				if (comp_has_startprereq_of($c, $comp)
					&& ! $need_disable{$c} && ! $dont_need_disable{$c} ) {
					if (comp_is_installed("$c") ) {
						@disabled = ( @disabled, $c );
						$need_disable{$c}=1;
						DebugPrint("also disable $c\n");
						$done=0;
					} else {
						$dont_need_disable{$c}=1;
						DebugPrint("no need to disable $c\n");
					}
				}
			}
		}
	}
	foreach $comp ( reverse(@AutostartComponents) ) {
		foreach my $c ( @disabled ) {
			if ( "$comp" eq "$c" ) {
				DebugPrint("invoke disable $c\n");
				comp_disable_autostart2($c,0);
			}
		}
	}
}

# enable autostart for a list of components and
# all components they depend on
sub enable_components(@)
{
	my @enabled = ( @_ );
	my %need_enable = ();
	my $comp;

	build_autostart_components_list;
	foreach $comp ( @enabled ) {
		$need_enable{$comp} = 1;
		DebugPrint("enable $comp explicitly\n");
	}
	my $done = 0;
	while ( ! $done) {
		$done=1;
		foreach $comp ( @enabled ) {
			# comp will be enabled, make sure all its
			# startprereqs will also be enabled
			foreach my $c ( @AutostartComponents ) {
				if (comp_has_startprereq_of($comp, $c) && ! $need_enable{$c} ) {
					DebugPrint("also enable $c\n");
					@enabled = ( $c, @enabled );
					$need_enable{$c}=1;
					$done=0;
				}
			}
		}
	}
	foreach $comp ( @AutostartComponents ) {
		foreach my $c ( @enabled ) {
			if ( "$comp" eq "$c" ) {
				DebugPrint("invoke enable $c\n");
				comp_enable_autostart2($c,0);
			}
		}
	}
}

sub install_startup($$$)
{
	my($srcdir) = shift();
	my($WhichStartup) = shift();
	my($StartupDesc) = shift();
	my $prompt;
	my $res;

	if ( "$StartupDesc" eq "" )
	{
		$prompt="$WhichStartup";
	} else {
		$prompt="$StartupDesc ($WhichStartup)";
	}
	print "Creating $prompt system startup files...\n";
	check_dir("$INIT_DIR");
	if ( -e "$srcdir/$WhichStartup.$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER" ) {
		copy_file("$srcdir/$WhichStartup.$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER", "$INIT_DIR/$WhichStartup",
					"$OWNER", "$GROUP", "ugo=rx,u=rwx");
	} elsif ( -e "$srcdir/$WhichStartup.$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER" ) {
		copy_file("$srcdir/$WhichStartup.$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER", "$INIT_DIR/$WhichStartup",
					"$OWNER", "$GROUP", "ugo=rx,u=rwx");
	} elsif ( -e "$srcdir/$WhichStartup.$CUR_DISTRO_VENDOR" )
	{
		copy_file("$srcdir/$WhichStartup.$CUR_DISTRO_VENDOR", "$INIT_DIR/$WhichStartup",
					"$OWNER", "$GROUP", "ugo=rx,u=rwx");
	} elsif ( -e "$srcdir/init_$WhichStartup.$CUR_DISTRO_VENDOR" ) {
		copy_file("$srcdir/init_$WhichStartup.$CUR_DISTRO_VENDOR", "$INIT_DIR/$WhichStartup",
					"$OWNER", "$GROUP", "ugo=rx,u=rwx");
	} elsif ( -e "$srcdir/$WhichStartup" )
	{
		copy_file("$srcdir/$WhichStartup", "$INIT_DIR/$WhichStartup",
					"$OWNER", "$GROUP", "ugo=rx,u=rwx");
	} elsif ( -e "$srcdir/init_$WhichStartup" ) {
		copy_file("$srcdir/init_$WhichStartup", "$INIT_DIR/$WhichStartup",
					"$OWNER", "$GROUP", "ugo=rx,u=rwx");
	} else {
		NormalPrint "$prompt system startup file not found\n";
	}
	
	if ( ! $Default_SameAutostart )
	{
		disable_autostart($WhichStartup);
	} else {
		if ( IsAutostart($WhichStartup) == 1 )
		{
			enable_autostart($WhichStartup);
		} else {
			disable_autostart($WhichStartup);
		}
	}     
}

# run build for all components
sub build_all_components($$$$)
{
	my $osver = shift();	# Kernel OS Version to build for
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a full rebuild

	my $comp;
	my $ret = 0;

	foreach $comp ( @Components )
	{
		my $rc = comp_build($comp,$osver,$debug,$build_temp,$force);
		if (0 != $rc) {
			NormalPrint "Unable to Build $ComponentInfo{$comp}{'Name'}\n";
		}
		$ret |= $rc;
	}
	return $ret;
}

sub count_hidden_comps()
{
	my $i;
	my $ret=0;

	for($i=0; $i < scalar(@Components); $i++)
	{
		my $comp = $Components[$i];
		if ($ComponentInfo{$comp}{'Hidden'}) {
			$ret++;
		}
	}
	return $ret;
}

# convert a screen selection into a Components subscript, accounting for Hidden
sub get_comp_subscript($$$)
{
	my $firstline=shift();
	my $maxlines=shift();
	my $selection=shift();
	my $index=0;
	my $i;

	for ($i=0; $i < scalar(@Components); $i++)
	{
		my $comp = $Components[$i];
		if ($index >= $firstline && $index < $firstline+$maxlines) {
			if (! $ComponentInfo{$comp}{'Hidden'}) {
				if ($index - $firstline == $selection) {
					return $i;
				}
				$index++;
			}
		} else {
			if (! $ComponentInfo{$comp}{'Hidden'}) {
				$index++;
			}
		}
	}
	return $i	# invalid entry return 1 past number of Components
}

sub show_install_menu($)
{
	my $showversion = shift();	# should per comp versions be shown

	my $inp;
	my %available = ();
	my %installed = ();
	my %installed_version = ();
	my %media_version = ();
	my %isupgrade = ();
	my %installState = ();
	my %statusMessage = ();
	my %boldMessage = ();
	my $comp;
	my $i;
	my $newstate = $State_Uninstall;	# most recent state change for a comp
	my $firstline = 0;
	my $maxlines=14;
	my $num_hidden_comps = count_hidden_comps();

	print "Determining what is installed on system...\n";
	DumpComponents(1);
	foreach $comp ( @Components )
	{
		$available{$comp} = comp_is_available("$comp");
		$installed{$comp} = comp_is_installed("$comp");
		if ( $available{$comp} ) {
			$media_version{$comp} = comp_media_version($comp);
		} else {
			$media_version{$comp} = "";
		}
		if ( $installed{$comp} ) {
			$installed_version{$comp} = comp_installed_version($comp);
			$isupgrade{$comp}= ($installed_version{$comp} ne $media_version{$comp});
		} else {
			$installed_version{$comp} = "";
			$isupgrade{$comp}=1;
		}
		$installState{$comp}= setstate($installed{$comp}, $available{$comp},
							$isupgrade{$comp}, $ComponentInfo{$comp}{'DefaultInstall'});
	}
	# to avoid a subtle effect, mark as not available any items whose
	# coreqs are not available.  Such packagings should not
	# occur, but better to be safe
	foreach $comp ( @Components )
	{
		if (! $available{$comp}) {
			foreach my $c ( @Components )
			{
				if (comp_has_coreq_of($c, $comp) && $available{$c}) {
					$available{$c}=0;
				}
			}
		}
	}

DO_INS:
	if ( $Default_Install) {	
		# setstate set UnInstall or DoNotInstall for those not available
		# force install for all available even if UpToDate
		# or ComponentInfo{comp}{'DefaultInstall'} is DoNotInstall
		foreach $comp ( @Components )
		{
			if ($available{$comp}
				&& ($installState{$comp} != $State_DoNotInstall
					|| $ComponentInfo{$comp}{'DefaultInstall'} != $State_DoNotAutoInstall)) {
				$installState{$comp} = $State_Install;
			}
		}
		$newstate = $State_Install;
		$inp='P';
	} elsif ( $Default_Upgrade) {	
		foreach $comp ( @Components )
		{
			if ( $installed{$comp} )
			{
				if ( $available{$comp} )
				{
					$installState{$comp} = $State_Install;
				} elsif ( ! $isupgrade{$comp} ) {
					$installState{$comp} = $State_UpToDate;
				} else {
					$installState{$comp} = $State_Uninstall; # we must uninstall
				}
			} else {
				if ( $available{$comp} )
				{
					$installState{$comp} = $State_DoNotInstall;
				} else {
					$installState{$comp} = $State_DoNotInstall;
				}
			}
		}
		$newstate = $State_Install;
		$inp='P';
	} elsif ( $Default_CompInstall) {
		foreach $comp ( @Components )
		{
			if ( $Default_Components{$comp} )
			{
				if ( $available{$comp} )
				{
					$installState{$comp} = $State_Install;
				} else {
					NormalPrint "Skipped $ComponentInfo{$comp}{'Name'}, Not Available\n";
					# setstate provided a reasonable default action
				}
			} else {
				# setstate defaulted to install all available and not installed
				# for version updates re-install to be safe
				if ( $installState{$comp} == $State_Install 
					&& ( ! $installed{$comp} || ! $isupgrade{$comp} ) )
				{
					# Do Not Install
					$installState{$comp} = $State_DoNotInstall;
				}
			}
		}
		$newstate = $State_Install;
		$inp='P';
	} else {
		system "clear";        
		printf ("$BRAND IB Install ($VERSION $DBG_FREE) Menu\n\n");
		my $screens = int((scalar(@Components) - $num_hidden_comps + $maxlines-1)/$maxlines);
		if ($screens > 1 ) {
			printf ("Please Select Install Action (screen %d of $screens):\n",
						$firstline/$maxlines+1);
		} else {
			printf ("Please Select Install Action:\n");
		}
		my $index=0;
		for ($i=0; $i < scalar(@Components); $i++)
		{
			$comp = $Components[$i];
			if ($index >= $firstline && $index < $firstline+$maxlines) {
				if ($showversion && "$statusMessage{$comp}" eq "") {
					if ($available{$comp}) {
						$statusMessage{$comp} = $media_version{$comp};
						$boldMessage{$comp} = 0;
					} elsif($installed{$comp}) {
						$statusMessage{$comp} = $installed_version{$comp};
						$boldMessage{$comp} = 0;
					}
				}
				if (! $ComponentInfo{$comp}{'Hidden'}) {
					printf ("%x) %-20s", $index-$firstline, $ComponentInfo{$comp}{'Name'});
					printInstallAvailableState($installed{$comp},
									$available{$comp},
									$isupgrade{$comp},
 									$installState{$comp},
									$boldMessage{$comp}, $statusMessage{$comp});
					$index++;
				}
			} elsif (! $ComponentInfo{$comp}{'Hidden'}) {
				$index++;
			}
		}
		
		printf ("\n");
		if ($screens > 1 ) {
			printf ("N) Next Screen\n");
		}
		printf (  "P) Perform the selected actions       I) Install All\n");
		printf (  "R) Re-Install All                     U) Uninstall All\n");
		printf (  "X) Return to Previous Menu (or ESC)\n");	

		$inp = getch();                
	        
		if ($inp =~ /[qQ]/ || $inp =~ /[xX]/ || ord($inp) == $KEY_ESC ) 
		{
			return;
		}

		# do not clear status messages when jump between screens
		if ($inp !~ /[nN]/ ) {
			%statusMessage = ();
			%boldMessage = ();
		}

	}

	if ($inp =~ /[nN]/ )
	{
		if (scalar(@Components) > $maxlines) {
			$firstline += $maxlines;
			if ($firstline >= scalar(@Components)) {
				$firstline=0;
			}
		}
	} elsif ($inp =~ /[rR]/ )
	{
		$installState{'qlgc_srp'} = $State_Uninstall;
		$installState{'qlgc_vnic'} = $State_Uninstall;
		foreach $comp ( @Components )
		{
			if ( $installed{$comp} && $available{$comp}) {
				$installState{$comp} = $State_Install;
			}
		}
	} elsif ($inp =~ /[iI]/ )
	{
		foreach $comp ( @Components )
		{
			if ( $available{$comp} ) {
				$installState{$comp} = $State_Install;
			}
		}
		$newstate = $State_Install;
	} elsif ($inp =~ /[uU]/ )
	{
		foreach $comp ( @Components )
		{
			$installState{$comp} = $State_Uninstall;
		}
		$newstate = $State_Uninstall;
	} elsif ($inp =~ /[0123456789abcdef]/) {
		my $value = hex($inp);
		my $index = get_comp_subscript($firstline, $maxlines, $value);
		if ( $value < $maxlines && $index < scalar(@Components)) {
			my $selected = $Components[$index];
			$installState{$selected} = shiftstate($installState{$selected},$installed{$selected},$available{$selected},$isupgrade{$selected});
            if ($selected eq "ib_stack" && $installState{$selected} == $State_Install) {
                    $installState{'qlgc_srp'} = $State_Uninstall;
                    $installState{'qlgc_vnic'} = $State_Uninstall;
            }
			$newstate = $installState{$selected};
		}
	}

	if (! will_be_on_system($newstate)) {
		# something is being uninstalled or not installed
		# loop through a few times to catch all coreqs, prereqs
		# and coreqs of prereqs
		my $done = 0;	# we are done if we loop through with no changes
		while (! $done) {
			$done=1;
			foreach $comp ( @Components )
			{
				if (! will_be_on_system($installState{$comp})) {
					# comp will not be on system, make sure all its
					# pre/coreqs will also not be on system
					foreach my $c ( @Components )
					{
						if (comp_has_req_of($c, $comp)
							&& will_be_on_system($installState{$c})) {
							$statusMessage{$c}="requires $ComponentInfo{$comp}{'Name'}";
							$boldMessage{$c}=1;
							$installState{$c}=$installed{$c}?$State_Uninstall:$State_DoNotInstall;
							$done=0;
						}
					}
				}
				if ($ComponentInfo{$comp}{'Hidden'}) {
					# if no longer needed, also remove it
					my $needed = 0;	# is $comp needed
					foreach my $c ( @Components )
					{
						if (comp_has_req_of($c, $comp)
							&& will_be_on_system($installState{$c})) {
							$needed=1;
						}
					}
					if (! $needed && will_be_on_system($installState{$comp})) {
						$installState{$comp}=$installed{$comp}?$State_Uninstall:$State_DoNotInstall;
						$done=0;
					}
				}
			}
		}
	} elsif (will_be_on_system($newstate)) {
		# something is being installed or left on system
		# loop through a few times to catch all coreqs, prereqs
		# and coreqs of prereqs
		my $done = 0;	# we are done if we loop through with no changes
		my $forcedone = 0;	# used to break infinite loop in subtle issue below
		while (! $forcedone && ! $done) {
			$done=1;
			foreach $comp ( @Components )
			{
				if (will_be_on_system($installState{$comp})) {
					# comp will be on system, make sure all its
					# pre/coreqs will also be on system
					foreach my $c ( @Components )
					{
						if (comp_has_req_of($comp, $c)
							&& ! will_be_on_system($installState{$c})) {
							if (! $available{$c} ) {
								# pre/coreq $c not available, can't install comp
								$statusMessage{$comp}="requires $ComponentInfo{$c}{'Name'}";
								$boldMessage{$comp}=1;
								$installState{$comp}=$installed{$comp}?$State_Uninstall:$State_DoNotInstall;
								# this should not occur for coreqs
								# however there are subtle effects here.
								# If we install an item which has a prereq
								# whose prereq is not available we could get
								# stuck with an invalid combination since we
								# will have marked the 1st prereq installed,
								# found the 2nd prereq problem
								# unmarked the 1st prereq but still have
								# left the original item to be installed
								# bail to avoid infinite loop
								$forcedone=1;
								last;
							} else {
								# also install $c
								$statusMessage{$c}="needed by $ComponentInfo{$comp}{'Name'}";
								$boldMessage{$c}=1;
								$installState{$c}=$State_Install;
							}
							$done=0;
						}
					}
				}
				if ($ComponentInfo{$comp}{'Hidden'} && $available{$comp}
					&& will_be_on_system($installState{$comp})) {
					# if all prereqs being reinstalled also reinstall it
					my $reinstall = 1;	# no already installed dependents
					foreach my $c ( @Components )
					{
						if (comp_has_req_of($c, $comp)
							&& will_be_on_system($installState{$c})
							&& $installState{$c} != $State_Install) {
							$reinstall=0;
						}
					}
					if ($reinstall) {
						$installState{$comp}=$State_Install;
						# no need to force another loop, didn't change
						# will_be_on_system($comp)
					}
				}
			}
		}
	}

	if ($inp =~ /[pP]/) {
		# perform the install
		my $updateFirmware=0;

		# build a list of what will be installed after installation completes
		# use a space separate string so easier to pass and can be "grep'ed"
		my $install_list = "";
		my $installing_list = "";
		my $uninstalling_list = "";
		my $have_some_uptodate = 0;
		foreach $comp ( @Components )
		{
			if ($installState{$comp} == $State_UpToDate) {
				$have_some_uptodate = 1;
			}
			if ($installState{$comp} == $State_Install
				|| $installState{$comp} == $State_UpToDate) {
				$install_list .= " $comp ";
			}
			if ($installState{$comp} == $State_Install) {
				$installing_list .= " $comp ";
			}
			if ($installState{$comp} == $State_Uninstall) {
				$uninstalling_list .= " $comp ";
			}
		}

		# first uninstall what will be removed, do this in reverse order
		# so dependency issues are avoided
		foreach $comp ( reverse(@Components) ) {
			if ($installState{$comp} == $State_Uninstall) {
				comp_uninstall($comp, $install_list, $uninstalling_list);
				$installed{$comp} = 0;
			}
		}
		if ( "$WrapperComponent" ne "" && "$installing_list" eq "" && "$install_list" eq "" ) {
			comp_uninstall($WrapperComponent, $install_list, $uninstalling_list);
		}

		if ($have_some_uptodate ) {
			# determine if some up to date components need to be reinstalled
			# for example due to a change in install prefix, install options ...
			# to determine this run need_reinstall for all components which
			# will be installed or are up to date.  Net result is we may change
			# some or all components in State_UpToDate to State_Install

			my $need_reinstall_all = 0;
			my $need_reinstall_some = 0;
			foreach $comp ( @Components )
			{
				if (($installState{$comp} == $State_Install
						|| $installState{$comp} == $State_UpToDate)
					&& $available{$comp} ) {
					my $reins = comp_need_reinstall($comp,$install_list,$installing_list);
					if ("$reins" eq "all") {
						VerbosePrint("$comp needs reinstall all\n");
						$need_reinstall_all = 1;
						last;
					} elsif ("$reins" eq "this") {
						if ($installState{$comp} == $State_UpToDate
							&& $available{$comp} ) {
							VerbosePrint("$comp needs reinstall\n");
							$installState{$comp} = $State_Install;
							$need_reinstall_some = 1;
						}
					}
				}
			}
			if ($need_reinstall_all || $need_reinstall_some) {
				if ($need_reinstall_all) {
					NormalPrint "INSTALL options require Reinstall of all UpToDate Components\n";
				} else {
					NormalPrint "Reinstall of some UpToDate Components is Required\n";
				}
				$installing_list  = "";	# recompute
				foreach $comp ( @Components )
				{
					if ($need_reinstall_all
						&& $installState{$comp} == $State_UpToDate
						&& $available{$comp} ) {
						$installState{$comp} = $State_Install;
					}
					if ($installState{$comp} == $State_Install) {
						$installing_list .= " $comp ";
					}
				}
			}
		}
		# check OS pre-reqs for all components which will be installed
		my $have_all_os_prereqs=1;
		foreach $comp ( @Components )
		{
			if ($installState{$comp} == $State_Install) {
				if (0 != comp_check_os_prereqs($comp)) {
					$have_all_os_prereqs=0;
					NormalPrint "Lacking OS Prereqs for $ComponentInfo{$comp}{'Name'}\n";
				}
			}
		}
		if (! $have_all_os_prereqs) {
			HitKeyCont;
			goto DONE;
		}

		# run pre-install for all components which will be installed
		foreach $comp ( @Components )
		{
			if ($installState{$comp} == $State_Install) {
				if (0 != comp_preinstall($comp,$install_list,$installing_list)) {
					NormalPrint "Unable to Prepare $ComponentInfo{$comp}{'Name'} for Install\n";
					HitKeyCont;
					goto DONE;
				}
			}
		}

		# Now install components
		if ( "$WrapperComponent" ne "" && "$installing_list" ne "" ) {
			comp_install($WrapperComponent, $install_list, $installing_list);
		}
		foreach $comp ( @Components )
		{
			if ($installState{$comp} == $State_Install) {
				comp_install($comp, $install_list, $installing_list);
				if ( $ComponentInfo{$comp}{'HasFirmware'} ) {
					$updateFirmware=1;
				}
			}
		}

		# run post-install for all components which were installed
		foreach $comp ( @Components )
		{
			if ($installState{$comp} == $State_Install) {
				comp_postinstall($comp, $install_list, $installing_list);
			}
		}

		%installed = ();
		if ( $Default_Prompt ) {
			foreach $comp ( @Components )
			{
				$installed{$comp} = 0;
			}
			# limit autostart to newly installed components with a
			# default start.  Also include their start prereqs.
			# Note start prereqs are all inclusive, so we don't need to
			# find prereqs of prereqs
			foreach $comp ( @Components )
			{
				if ($installState{$comp} == $State_Install
					&& $ComponentInfo{$comp}{'HasStart'}
					&& ($Default_SameAutostart
						|| $ComponentInfo{$comp}{'DefaultStart'}) ) {
					$installed{$comp} = 1;
					foreach my $c ( @Components ) {
						if (comp_has_startprereq_of($comp, $c)) {
							$installed{$c} = 1;
						}
					}
				}
			}
		} else {
			foreach $comp ( @Components )
			{
				if ($installState{$comp} == $State_Install
					|| $installState{$comp} == $State_UpToDate) {
					$installed{$comp} = 1;
				} else {
					$installed{$comp} = 0;
				}
			}
		}
		show_autostart_menu(0, %installed);

		if ( $updateFirmware && ! $Skip_FirmwareUpgrade ) {
			update_hca_firmware;
		}

		# show_autostart_menu unconditionally requested user hit return,
		# update_hca_firmware will also as needed, so only request return below
		# if one of these functions does something.
		# component_start_prompts if it does anything will also request a return
		my $need_ret = 0;
		$need_ret |= check_depmod;
		$need_ret |= check_ldconfig;
		if (component_start_prompts) {
			$need_ret=0;
		}
		$need_ret |= check_need_reboot;
		if ($need_ret) {
			HitKeyCont;
		}
		return;
	}

	# we had an error above
DONE:
	if ( ! $Default_Prompt ) {
		goto DO_INS;
	}
	$exit_code = 1;
}

sub show_installed($)
{
	my $showversion = shift();	# should per comp versions be shown

	my %installed = ();
	my %statusMessage = ();
	my $comp;
	my $i;

	system "clear";
	printf ("$BRAND IB Installed Software ($VERSION)\n\n");
	my $index=0;
	for ($i=0; $i < scalar(@Components); $i++)
	{
		if ($index > 0 && ($index % 20 == 0) ) {
			HitKeyCont;
		}
		$comp = $Components[$i];
		$installed{$comp} = comp_is_installed("$comp");
		if ( $showversion && $installed{$comp} ) {
			$statusMessage{$comp} = comp_installed_version($comp);
		}
		if (! $ComponentInfo{$comp}{'Hidden'}) {
			printf ("   %-20s ", $ComponentInfo{$comp}{'Name'});
			printInstallState($installed{$comp}, 0, 0, "$statusMessage{$comp}");
			$index++;
		}
	}
	HitKeyCont;
}

sub show_uninstall_menu($)
{
	my $showversion = shift();	# should per comp versions be shown

	my %installed = ();
	my %installed_version = ();
	my %installState = ();
	my %statusMessage = ();
	my %boldMessage = ();
	my $inp;
	my $comp;
	my $i;
	my $newstate;	# most recent state change for a comp
	my $firstline = 0;
	my $maxlines=14;
	my $num_hidden_comps = count_hidden_comps();

	print "Determining what is installed on system...\n";
	DumpComponents(0);
	foreach $comp ( @Components )
	{
		$installed{$comp} = comp_is_installed("$comp");
		if ($installed{$comp}) {
			$installed_version{$comp} = comp_installed_version("$comp");
		}
		$installState{$comp}= setstate($installed{$comp},0,0,$State_DoNotInstall);
	}
DO_UNINS:
	if ( $Default_Uninstall) {
		foreach $comp ( @Components )
		{
			$installState{$comp} = $State_Uninstall;
		}
		$newstate = $State_Uninstall;
		$inp="P";
	} elsif ( $Default_CompUninstall) {
		foreach $comp ( @Components )
		{
			if ( $Default_Components{$comp} )
			{
				$installState{$comp} = $State_Uninstall;
			}
		}
		$newstate = $State_Uninstall;
		$inp="P";
	} else {
		system "clear";
		printf ("$BRAND IB Uninstall Menu ($VERSION)\n\n");
		my $screens = int((scalar(@Components)-$num_hidden_comps + $maxlines-1)/$maxlines);
		if ($screens > 1 ) {
			printf ("Please Select Uninstall Action (screen %d of $screens):\n",
						$firstline/$maxlines+1);
		} else {
			printf ("Please Select Uninstall Action:\n");
		}
		my $index=0;
		for($i=0; $i < scalar(@Components); $i++)
		{
			$comp = $Components[$i];
			if ($index >= $firstline && $index < $firstline+$maxlines) {
				if ($showversion && "$statusMessage{$comp}" eq ""
					&& $installed{$comp}) {
					$statusMessage{$comp} = $installed_version{$comp};
					$boldMessage{$comp} = 0;
				}
				if (! $ComponentInfo{$comp}{'Hidden'}) {
					printf ("%x) %-20s ", $index-$firstline, $ComponentInfo{$comp}{'Name'});
					printInstallState($installed{$comp}, ($installState{$comp} == $State_Uninstall),
						$boldMessage{$comp}, $statusMessage{$comp});
					$index++;
				}
			} elsif (! $ComponentInfo{$comp}{'Hidden'}) {
				$index++;
			}
		}

		printf ("\n");
		if ($screens > 1 ) {
			printf ("N) Next Screen\n");
		}
		printf (  "P) Perform the selected actions\n");
		printf (  "U) Uninstall All\n");
		printf (  "X) Return to Previous Menu (or ESC)\n");
			

		$inp = getch();
	
		if ($inp =~ /[qQ]/ || $inp =~ /[xX]/ || ord($inp) == $KEY_ESC)
		{
			return;
		}

		# do not clear status messages when jump between screens
		if ($inp !~ /[nN]/ )
		{
			%statusMessage = ();
			%boldMessage = ();
		}
	}

	if ($inp =~ /[nN]/ )
	{
		if (scalar(@Components) > $maxlines) {
			$firstline += $maxlines;
			if ($firstline >= scalar(@Components)) {
				$firstline=0;
			}
		}
	} elsif ($inp =~ /[uU]/ )
	{
		foreach $comp ( @Components )
		{
			$installState{$comp} = $State_Uninstall;
		}
		$newstate = $State_Uninstall;
	}
	elsif ($inp =~ /[0123456789abcdef]/)
	{
		my $value = hex($inp);
		my $index = get_comp_subscript($firstline, $maxlines, $value);
		if ( $value < $maxlines && $index < scalar(@Components)) {
			my $selected = $Components[$index];
			$installState{$selected} = shiftstate($installState{$selected},$installed{$selected},0,0);
			$newstate = $installState{$selected};
		}
	}

	if (! will_be_on_system($newstate)) {
		my $done = 0;	# we are done if we loop through with no changes
		# something is being uninstalled or not installed
		# loop through a few times to catch all coreqs, prereqs
		# and coreqs of prereqs
		while (! $done) {
			$done=1;
			foreach $comp ( @Components )
			{
				if (! will_be_on_system($installState{$comp})) {
					# comp will not be on system, make sure all its
					# pre/coreqs will also not be on system
					foreach my $c ( @Components )
					{
						if (comp_has_req_of($c, $comp)
							&& will_be_on_system($installState{$c})) {
							$statusMessage{$c}="requires $ComponentInfo{$comp}{'Name'}";
							$boldMessage{$c}=1;
							$installState{$c}=$installed{$c}?$State_Uninstall:$State_DoNotInstall;
							$done=0;
						}
					}
				}
				if ($ComponentInfo{$comp}{'Hidden'}) {
					# if no longer needed, also remove it
					my $needed = 0;	# is $comp needed
					foreach my $c ( @Components )
					{
						if (comp_has_req_of($c, $comp)
							&& will_be_on_system($installState{$c})) {
							$needed=1;
						}
					}
					if (! $needed && will_be_on_system($installState{$comp})) {
						$installState{$comp}=$installed{$comp}?$State_Uninstall:$State_DoNotInstall;
						$done=0;
					}
				}
			}
		}
	} elsif (will_be_on_system($newstate)) {
		# something is being left on system
		# loop through a few times to catch all coreqs, prereqs
		# and coreqs of prereqs
		my $done = 0;	# we are done if we loop through with no changes
		my $forcedone = 0;	# used to force infinite loop in subtle issue below
		while (! $forcedone && ! $done) {
			$done=1;
			foreach $comp ( @Components )
			{
				if (will_be_on_system($installState{$comp})) {
					# comp will be on system, make sure all its
					# pre/coreqs will also be on system
					foreach my $c ( @Components )
					{
						if (comp_has_req_of($comp, $c)
							&& ! will_be_on_system($installState{$c})) {
							if (! $installed{$c} ) {
								# pre/coreq $c not installed, can't keep comp
								# this is not expected to occur, but is
								# a safety net for corrupted systems
								$statusMessage{$comp}="requires $ComponentInfo{$c}{'Name'}";
								$boldMessage{$comp}=1;
								$installState{$comp}=$installed{$comp}?$State_Uninstall:$State_DoNotInstall;
								# bail to avoid infinite loop, especially
								# for prereq chains and missing coreqs
								# see install_menu discussion for a similar
								# related issue
								$forcedone=1;
								last;
							} else {
								# also install $c
								$statusMessage{$c}="needed by $ComponentInfo{$comp}{'Name'}";
								$boldMessage{$c}=1;
								$installState{$c}=$State_Install;
							}
							$done=0;
						}
					}
				}
			}
		}
	}

	if ($inp =~ /[pP]/)
	{
		# build a list of what will be installed after installation completes
		# use a space separate string so easier to pass and can be "grep'ed"
		my $install_list = "";
		my $uninstalling_list = "";
		foreach $comp ( @Components )
		{
			if ($installState{$comp} == $State_Install
				|| $installState{$comp} == $State_UpToDate) {
				$install_list .= " $comp ";
			}
			if ($installState{$comp} == $State_Uninstall) {
				$uninstalling_list .= " $comp ";
			}
		}

		# perform the uninstall, work backwards through list
		foreach $comp ( reverse(@Components) )
		{
			if ($installState{$comp} == $State_Uninstall)
			{
				comp_uninstall($comp, $install_list, $uninstalling_list);
				$installed{$comp} = 0;
			}
		}
		if ( "$WrapperComponent" ne "" && "$install_list" eq "" ) {
			comp_uninstall($WrapperComponent, $install_list, $uninstalling_list);
		}
		# since we did an uninstall should request a return
		my $need_ret = 1;
		$need_ret |= check_depmod;
		$need_ret |= check_ldconfig;
		$need_ret |= check_need_reboot;
		if ($need_ret) {
			HitKeyCont;
		}
		return;
	}

	if ( ! $Default_Prompt ) {
		goto DO_UNINS;
	}
}

sub reconfig_autostart()
{
	my %installed = ();
	my $comp;

	build_autostart_components_list;
	foreach $comp ( @Components ) {
		$installed{$comp} = comp_is_installed("$comp");
		DebugPrint("installed($comp)=$installed{$comp}\n");
		# fill in subcomponents to simplify tests for Default_*Components below
		# if show_autostart_menu is called, it will ignore these extra entries
		foreach my $c ( @{ $ComponentInfo{$comp}{'StartComponents'} }) {
			$installed{$c} = $installed{$comp};
		}
	}
	if (! $Default_Autostart) {
		# interactive menu, use previous value as default
		show_autostart_menu(1, %installed);
	} else {
		if ( $Default_DisableAutostart) {
			# build list of components/subcomponents to disable
			my @disabled = ();
			foreach $comp ( @AutostartComponents ) {
				if ( $installed{$comp} ) {
					if ($Default_DisabledComponents{$comp}) {
						@disabled = ( @disabled, $comp );
					}
				}
			}
			disable_components(@disabled);
		}
		if ( $Default_EnableAutostart) {
			# build list of components/subcomponents to enable
			my @enabled = ();
			foreach $comp ( @AutostartComponents ) {
				if ( $installed{$comp} ) {
					if ($Default_EnabledComponents{$comp}) {
						@enabled = ( @enabled, $comp );
					}
				} else {
				}
			}
			enable_components(@enabled);
		}
		if (! $Default_DisableAutostart && ! $Default_EnableAutostart) {
			# use component specific default as value
			show_autostart_menu(0, %installed);
		}
	}
}

sub component_start_prompts()
{
	my $comp;
	my $start = 0;

	foreach $comp ( @Components ) {
		$start ||= ($ComponentWasInstalled{$comp} && $ComponentInfo{$comp}{'HasStart'});;
	}
	# TBD disabled for now, restart of iba causes problems if other
	# drivers are running above it
	if (0 && $start && GetYesNo("Start drivers now?", "n") == 1)
	{
		foreach $comp ( @Components )
		{
			# if not already loaded, start prereqs
			# prehaps prompt for all then do the work?
			if ($ComponentWasInstalled{$comp} && $ComponentInfo{$comp}{'HasStart'})
			{
				comp_start($comp);
				$ComponentWasInstalled{$comp}=0;
			}
		}
		HitKeyCont;
		return 1;
	}
	return 0;
} 

# states:
# $Start_Start - Enable Autostart
# $Start_NoStart - Disable Autostart
sub printStartState($$$)
{
	my $enabled     = shift();
	my $boldmessage = shift();
	my $message   = shift();

	if ( $enabled )
	{
		print GREEN, "[Enable ]", RESET;
	} else {
		print RED, "[Disable]", RESET;
	}

	if ("$message" ne "" && $boldmessage) {
		print BOLD, RED "$message", RESET, "\n";
	} else {
		print "$message\n";
	}

	return;
}

# convert a screen selection into a Autostart subscript
sub get_subscript($$$@)
{
	my $firstline=shift();
	my $maxlines=shift();
	my $selection=shift();
	my @list = ( @_ );
	my $index=0;
	my $i;

	for ($i=0; $i < scalar(@list); $i++)
	{
		my $comp = $list[$i];
		if ($index >= $firstline && $index < $firstline+$maxlines) {
			if ($index - $firstline == $selection) {
				return $i;
			}
			$index++;
		} else {
			$index++;
		}
	}
	return $i	# invalid entry return 1 past number of Components
}
sub show_autostart_menu($%)
{
	my $usePrevious = shift(); # should previous setting be used as default
	my %selections = ( @_ );	# components to show

	my $inp;
	my @PromptAutostart = ();
	my %enabled = ();
	my %statusMessage = ();
	my %boldMessage = ();
	my $comp;
	my $i;
	my $newenabled = 0;	# most recent state change for a comp
	my $firstline = 0;
	my $maxlines=14;

	# figure out which to prompt for
	# while selections may include SubComponents, we only look
	# at components and include all their subcomponents in the prompts
	foreach $comp ( @Components )
	{
		if ( $selections{$comp} && $ComponentInfo{$comp}{'HasStart'} )
		{
			# StartComponents will list Components and SubComponents which
			# have start capability
			@PromptAutostart = ( @PromptAutostart, @{ $ComponentInfo{$comp}{'StartComponents'} })
		}
	}
	if ( $Default_SameAutostart ) {
		foreach $comp ( @PromptAutostart )
		{
			my $state;
			# we recreate startup files to ensure they are in the
			# startup order of the new release
			if ( comp_IsAutostart2($comp) == 1 )
			{
				comp_enable_autostart2($comp,1);
				$state = "enabled";
			} else {
				comp_disable_autostart2($comp,1);
				$state = "disabled";
			}
			my $desc = comp_autostart_desc($comp);
			NormalPrint "Leaving autostart for $desc at its previous value: $state\n";
		}
		return;
	}

	foreach $comp ( @PromptAutostart )
	{
		DebugPrint("prompt for $comp\n");
		if ($usePrevious) {
			$enabled{$comp} = comp_IsAutostart2($comp);
		} else {
			$enabled{$comp} = $ComponentInfo{$comp}{'DefaultStart'};
		}
	}
DO_AUTOSTART:
	if ( $Default_Prompt) {
		$inp='P';
	} else {
		system "clear";        
		printf ("$BRAND IB Autostart ($VERSION $DBG_FREE) Menu\n\n");
		my $screens = int((scalar(@PromptAutostart) + $maxlines-1)/$maxlines);
		if ($screens > 1 ) {
			printf ("Please Select Autostart Option (screen %d of $screens):\n",
						$firstline/$maxlines+1);
		} else {
			printf ("Please Select Autostart Option:\n");
		}
		my $index=0;
		for ($i=0; $i < scalar(@PromptAutostart); $i++)
		{
			$comp = $PromptAutostart[$i];
			if ($index >= $firstline && $index < $firstline+$maxlines) {
				printf ("%x) %-34s", $index-$firstline, comp_autostart_desc($comp));
				printStartState($enabled{$comp},
								$boldMessage{$comp}, $statusMessage{$comp});
				$index++;
			} else {
				$index++;
			}
		}
		
		printf ("\n");
		if ($screens > 1 ) {
			printf ("N) Next Screen\n");
		}
		printf (  "P) Perform the autostart changes\n");
		printf (  "S) Autostart All                     R) Autostart None\n");
		printf (  "X) Return to Previous Menu (or ESC)\n");	

		$inp = getch();                
	        
		if ($inp =~ /[qQ]/ || $inp =~ /[xX]/ || ord($inp) == $KEY_ESC ) 
		{
			return;
		}

		# do not clear status messages when jump between screens
		if ($inp !~ /[nN]/ ) {
			%statusMessage = ();
			%boldMessage = ();
		}

	}

	if ($inp =~ /[nN]/ )
	{
		if (scalar(@PromptAutostart) > $maxlines) {
			$firstline += $maxlines;
			if ($firstline >= scalar(@PromptAutostart)) {
				$firstline=0;
			}
		}
	} elsif ($inp =~ /[sS]/ )
	{
		foreach $comp ( @PromptAutostart )
		{
			$enabled{$comp} = 1;
		}
		$newenabled = 1;
	} elsif ($inp =~ /[rR]/ )
	{
		foreach $comp ( @PromptAutostart )
		{
			$enabled{$comp} = 0;
		}
		$newenabled = 0;
	} elsif ($inp =~ /[0123456789abcdef]/) {
		my $value = hex($inp);
		my $index = get_subscript($firstline, $maxlines, $value, @PromptAutostart);
		if ( $value < $maxlines && $index < scalar(@PromptAutostart)) {
			my $selected = $PromptAutostart[$index];
			$enabled{$selected} = ! $enabled{$selected};
			$newenabled = $enabled{$selected};
		}
	}

	if (! $newenabled) {
		# something is being disabled
		# loop through a few times to catch all prereqs
		# and prereqs of prereqs
		my $done = 0;	# we are done if we loop through with no changes
		while (! $done) {
			$done=1;
			foreach $comp ( @PromptAutostart )
			{
				if (! $enabled{$comp}) {
					# comp will be disabled, make sure all its
					# startprereqs will also be disabled
					foreach my $c ( @PromptAutostart )
					{
						if (comp_has_startprereq_of($c, $comp) && $enabled{$c}) {
							$statusMessage{$c}="requires $ComponentInfo{$comp}{'Name'}";
							$boldMessage{$c}=1;
							$enabled{$c}=0;
							$done=0;
						}
					}
				}
			}
		}
	} else {
		# something is being disabled
		# loop through a few times to catch all prereqs
		my $done = 0;	# we are done if we loop through with no changes
		while (! $done) {
			$done=1;
			foreach $comp ( @PromptAutostart )
			{
				if ($enabled{$comp}) {
					# comp will be enabled, make sure all its
					# startprereqs will also be enabled
					foreach my $c ( @PromptAutostart )
					{
						if (comp_has_startprereq_of($comp, $c) && ! $enabled{$c}) {
							# also enable $c
							$statusMessage{$c}="needed by $ComponentInfo{$comp}{'Name'}";
							$boldMessage{$c}=1;
							$enabled{$c}=1;
							$done=0;
						}
					}
				}
			}
		}
	}

	if ($inp =~ /[pP]/) {
		# perform the changes

		# first disable, do this in reverse order
		# so dependency issues are avoided
		foreach $comp ( reverse(@PromptAutostart) ) {
			if (! $enabled{$comp}) {
				comp_disable_autostart2($comp,0);
			}
		}
		# now enable
		foreach $comp ( @PromptAutostart ) {
			if ($enabled{$comp}) {
				comp_enable_autostart2($comp,0);
			}
		}
		HitKeyCont;
		return;
	}

	if ( ! $Default_Prompt ) {
		goto DO_AUTOSTART;
	}
	$exit_code = 1;	# unexpected
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# =============================================================================
# The functions and constants below assist in editing hotplug and blacklists
# to prevent autoloading of drivers prior to startup scripts

my $HOTPLUG_BLACKLIST_PREFIX = "";
my $HOTPLUG_BLACKLIST_FILE = "/etc/hotplug/blacklist";
my $HOTPLUG_HARDWARE_DIR = "/etc/sysconfig/hardware";
if (-f "/etc/modprobe.d/blacklist")
{
	$HOTPLUG_BLACKLIST_FILE = "/etc/modprobe.d/blacklist";
	$HOTPLUG_BLACKLIST_PREFIX = "blacklist ";
}

# add to list to prevent automatic hotplug of driver
sub add_blacklist($)
{
	my $module = shift();

	my $file = "${ROOT}${HOTPLUG_BLACKLIST_FILE}";
	my $found;

	if (! -f "$file")
	{
		return;
	}
	open (INPUT, "$file");
	open (OUTPUT, ">>$TMP_CONF");

	select (OUTPUT);
	while (($_=<INPUT>))
	{
		if (/^$module[ 	]*$/)
		{
			$found++;
		} 
		print $_;
	}
	if (!defined($found))
	{
		print "${HOTPLUG_BLACKLIST_PREFIX}$module\n";
	}
	select(STDOUT);

	close (INPUT);
	close (OUTPUT);
	system "mv $TMP_CONF $file";

	# also remove any hotplug config files which load the driver
	open hwconfig, "ls $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg* 2>/dev/null |"
			|| Abort "Unable to open pipe\n";
	while (<hwconfig>) {
		chop;
		if ( ! system("grep -q \"MODULE.*'$module'\" $_ 2>/dev/null") ) {
			system "rm -f $_"
		}
	}
	close hwconfig;
}

sub remove_blacklist($)
{
	my($module) = shift();

	my($file) = "${ROOT}${HOTPLUG_BLACKLIST_FILE}";
	if (! -f "$file")
	{
		return;
	}
	open (INPUT, "$file");
	open (OUTPUT, ">>$TMP_CONF");

	select (OUTPUT);
	while (($_=<INPUT>))
	{
		if (/^${HOTPLUG_BLACKLIST_PREFIX}$module[ 	]*$/)
		{
			next;
		} else {
			print $_;
		}
	}
	select(STDOUT);

	close (INPUT);
	close (OUTPUT);
	system "mv $TMP_CONF $file";

	# also remove any hotplug config files so open IB drivers could load
		# Tavor - Hex (SuSE 9.3)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-5a44-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-5a45-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-5a46-*";
		# Tavor - Decimal (SuSE 9.2)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-23108-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-23109-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-23110-*";
		# Arbel - Hex (SuSE 9.3)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-6278-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-6279-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-627a-*";
		# Arbel - Decimal (SuSE 9.2)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-23208-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-23209-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-23210-*";
		# Arbel Mode - Hex (SuSE 9.3)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-6282-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-6283-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-6284-*";
		# Arbel Mode - Decimal (SuSE 9.2)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-25218-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-25219-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-25220-*";
		# Sinai - Hex (SuSE 9.3)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-6274-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-6275-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-6276-*";
		# Sinai - Decimal (SuSE 9.2)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-25204-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-25205-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-25206-*";
		# Old Sinai - Hex (SuSE 9.3)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-5e8c-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-5e8d-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-15b3-5e8e-*";
		# Old Sinai - Decimal (SuSE 9.2)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-24204-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-24205-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-5555-24206-*";
		# iPath HT - Hex (SuSE 9.3)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-1fc1-000d-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-1fc1-d-*";
		# iPath HT - Decimal (SuSE 9.2)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-8129-13-*";
		# iPath PCIe - Hex (SuSE 9.3)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-1fc1-0010-*";
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-1fc1-10-*";
		# iPath PCIe - Decimal (SuSE 9.2)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-8129-16-*";
		# iPath PCIe - Hex (SuSE 9.3)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-1077-6220-*";
		# iPath PCIe - Decimal (SuSE 9.2)
	system "rm -f $ROOT/$HOTPLUG_HARDWARE_DIR/hwcfg-vpid-4215-25120-*";
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

#

#++
# "This software program is available to you under a choice of one of two 
# licenses.  You may choose to be licensed under either the GNU General Public 
# License (GPL) Version 2, June 1991, available at 
# http://www.fsf.org/copyleft/gpl.html, or the Intel BSD + Patent License, 
# the text of which follows:
# 
# "Recipient" has requested a license and Intel Corporation ("Intel") is willing
# to grant a license for the software entitled InfiniBand(tm) System Software 
# (the "Software") being provided by Intel Corporation.

# The following definitions apply to this License: 

# "Licensed Patents" means patent claims licensable by Intel Corporation which 
# are necessarily infringed by the use or sale of the Software alone or when 
# combined with the operating system referred to below.

# "Recipient" means the party to whom Intel delivers this Software.
# "Licensee" means Recipient and those third parties that receive a license to 
# any operating system available under the GNU Public License version 2.0 or 
# later.

# Copyright (c) 1996-2002 Intel Corporation. All rights reserved. 

# The license is provided to Recipient and Recipient's Licensees under the 
# following terms.  

# Redistribution and use in source and binary forms of the Software, with or 
# without modification, are permitted provided that the following conditions are 
# met: 
# Redistributions of source code of the Software may retain the above copyright 
# notice, this list of conditions and the following disclaimer. 

# Redistributions in binary form of the Software may reproduce the above 
# copyright notice, this list of conditions and the following disclaimer in the 
# documentation and/or other materials provided with the distribution. 

# Neither the name of Intel Corporation nor the names of its contributors shall 
# be used to endorse or promote products derived from this Software without 
# specific prior written permission.

# Intel hereby grants Recipient and Licensees a non-exclusive, worldwide, 
# royalty-free patent license under Licensed Patents to make, use, sell, offer 
# to sell, import and otherwise transfer the Software, if any, in source code 
# and object code form. This license shall include changes to the Software that 
# are error corrections or other minor changes to the Software that do not add 
# functionality or features when the Software is incorporated in any version of 
# a operating system that has been distributed under the GNU General Public 
# License 2.0 or later.  This patent license shall apply to the combination of 
# the Software and any operating system licensed under the GNU Public License 
# version 2.0 or later if, at the time Intel provides the Software to Recipient, 
# such addition of the Software to the then publicly available versions of such 
# operating system available under the GNU Public License version 2.0 or later 
# (whether in gold, beta or alpha form) causes such combination to be covered by 
# the Licensed Patents. The patent license shall not apply to any other 
# combinations which include the Software. No hardware per se is licensed 
# hereunder. 

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY 
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
#--
#
#
use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# IP address configuration
# used for IPoIB at present but generalized so could support VNIC or
# iPathEther also

my $MAX_IB_PORTS=20;	# maximum valid ports

# Validate the passed in IP address (or netmask).
# Verify there are enough dots '.' and same number of
# decimal numbers. This is not comprehensive.
#
# inputs:
#	IP address in dot notation.  eg:
#	'a.b.c.d' or 'a.b.c' or 'a.b'
#
# outputs:
#	0 == failure(not a valid IP address)
#	1 == Success.

sub Validate_IP_Addr($)
{
	$_ = shift();		# setup for translate & other cmds

	my($count)= 0;

	# verify there are 3 and only 3 dots, 'a.b.c.d'.
	# translate '.' to self, side-effect is the count.

	$count=(tr/\.//);
	if ( $count < 1 || $count > 3 )
	{
		return 0;
	}

	# accept only decimal digits separated by dots.
	if ( /[0-9\.]/ ) 
	{
		# because we checked dots above, any of the three below is ok
		if ( /([0-9]+)\.([0-9]+)\.([0-9]+)\.([0-9]+)/ ) 
		{
			return 1;	# Success
		}
		if ( /([0-9]+)\.([0-9]+)\.([0-9]+)/ ) 
		{
			return 1;	# Success
		}
		if ( /([0-9]+)\.([0-9]+)/ ) 
		{
			return 1;	# Success
		}
	}
	return 0;	# failure.
}


# Retrieve an IPV4 address in standard 'dot' notation from stdin.
# Perform simple IP address format validation.
#
# returns:
#	IP address string.
#

sub Get_IP_Addr($$)
{
	my($interface) = shift();
	my($default_ip) = shift();

	my($ip,$idx);

	# acquire a valid IP address.
	# sadly last & redo caused runtime errors?

	do 
	{
		if ("$default_ip" ne "")
		{
			print "Enter IPV4 address in dot notation (or dhcp) for $interface [$default_ip]: ";
		} else {
			print "Enter IPV4 address in dot notation (or dhcp) for $interface: ";
		}
		chomp($ip = <STDIN>);
		$ip=remove_whitespace($ip);

		if ( length($ip) == 0 && "$default_ip" ne "" ) 
		{
			$ip = $default_ip;
			$_ = "y";
		}
		else 
		{
			# verify there are enough chars for a valid IP address
			if ( "$ip" ne "dhcp" && Validate_IP_Addr($ip) == 0 ) 
			{
				print("Bad IPV4 address '$ip'\n");
				$_ = "n";
			}
			else 
			{
				do
				{
					# require a response
					print("Is IPV4 address '$ip' correct? (y/n): ");
					chomp($_ = <STDIN>);
					$_=remove_whitespace($_);
				} until (/[YyNn]/);
			}
		}
	} until (/[Yy]/);
	LogPrint "Enter IPV4 address in dot notation for $interface: -> $ip\n";

	return $ip;
}

# Retrieve an IPV4 netmask in standard 'dot' notation from stdin.
# Perform simple IP address format validation.
#
# returns:
#	IP address string.
#

sub Get_IP_Addr_Netmask($$)
{
	my($interface) = shift();
	my($ipaddr) = shift();

	my($idx,$default_netmask,$dot_count);
	my $netmask;

	if ( "$ipaddr" eq "dhcp" ) {
		return "";
	}
	$default_netmask = `/opt/iba/ib_tools/iba_ipcalc --netmask $ipaddr`;
	$default_netmask =~ s/NETMASK=//;
	$default_netmask =~ s/\n//;
	$_ = $ipaddr;		# setup for translate & other cmds
	$dot_count=(tr/\.//);
	do 
	{
		print "Enter IPV4 netmask in dot notation for $interface $ipaddr [$default_netmask]: ";
		chomp($netmask = <STDIN>);
		$netmask=remove_whitespace($netmask);
		$_=$netmask;

		if ( length($netmask) == 0 ) 
		{
			$netmask = $default_netmask;
			print("Is IPV4 netmask '$netmask' correct? (y/n): ");
			chomp($_ = <STDIN>);
			$_=remove_whitespace($_);
		}
		else 
		{
			# verify there are enough chars for a valid IP address
			if ( Validate_IP_Addr($netmask) == 0 ) 
			{
				print("Bad IPV4 netmask: '$netmask'\n");
				$_ = "n";
			}
			elsif ($dot_count != (tr/\.//))
			{
				print("Inappropriate IPV4 netmask for $ipaddr: '$netmask'\n");
				$_ = "n";
			}
			else 
			{
				print("Is IPV4 netmask '$netmask' correct? (y/n): ");
				chomp($_ = <STDIN>);
				$_=remove_whitespace($_);
			}
		}
	} until (/[Yy]/);
	LogPrint "Enter IPV4 netmask in dot notation for $interface $ipaddr [$default_netmask]: -> $netmask\n";
	return $netmask;
}

# return the next sequential IPV4 address. Last numeric field is incremented.
#
# Assumes a valid dot notation IP address (e.g., 7.7.7.240)
# Increment the 'host' number ('240' in the example) by 1.
#  7.7.7.240 --> 7.7.7.241
#
# input:
#	base IP address in 'dot' notation.
# output:
#	next IP address

sub NextIPaddr($)
{
	my($base) = shift();

	my($next,$hostnum,$idx,$len);

	if ( "$base" eq "dhcp" ) {
		return "$base";
	}
	# locate right-most '.'
	$idx = rindex($base, ".");
	Abort "NextIPaddr: Bad IPV4 address ".$base
		if ($idx == -1);

	$idx += 1;	# move past the dot to the last numeric field portion of
				# the IP address.

	# extract the host number
	$len = length($base);
	$hostnum = substr($base, ($idx), ($len - $idx));

	$hostnum += 1;	# next host number

	# replace the last numeric field with the incremented host number
	$next = $base;
	substr($next,$idx,length($hostnum)) = $hostnum;

	DebugPrint("Next IP '$next'\n");

	return $next
}

# return the next sequential interface name. Last numeric field is incremented.
# if the final field is not numeric, returns ""
sub NextInterface($)
{
	my($base) = shift();

	my($next,$hostnum,$idx,$len);
	my $number;
	my $prefix;

	$_ = $base;
	if ( ! /.*([0-9]+)$/ ) 
	{
		# non numeric name, can't auto-increment
		return "";
	}
	$prefix = $base;
	$prefix =~ s/(.*)([0-9]+)$/$1/;
	$number = $base;
	$number =~ s/(.*)([0-9]+)$/$2/;

	$number += 1;	# next intf number

	return "$prefix$number";
}

# build the ifcfg file for a network device
sub Build_ifcfg($$$)
{
	my($device) = shift();		# device name
	my($ipaddr) = shift();		# ip address for device or "dhcp"
	my($netmask) = shift();		# ip address netmask for device

	my($target, $SysCmd);
	my ($temp);

	$target = "$ROOT$NETWORK_CONF_DIR/ifcfg-$device";
	print("Creating ifcfg-$device for $ipaddr mask $netmask\n\n");

	if ( "$CUR_DISTRO_VENDOR" eq "UnitedLinux" || "$CUR_DISTRO_VENDOR" eq "SuSE") {
		if ( "$ipaddr" eq "dhcp" ) {
			# append boot protocol type
			$SysCmd = "echo \"BOOTPROTO=\'dhcp\'\" >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;
		} else {
			# append boot protocol type
			$SysCmd = "echo \"BOOTPROTO=\'static\'\" >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;

			# append the device instance internet protocol address
			$SysCmd = "echo \"IPADDR=\'$ipaddr\'\" >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;

			# append the netmask
			$SysCmd = "echo \"NETMASK=\'$netmask\'\" >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;

			# append the network
			$temp = `/opt/iba/ib_tools/iba_ipcalc --network $ipaddr $netmask`;
			chomp($temp);
			$temp =~ s/NETWORK=//;
			$SysCmd = "echo \"NETWORK=\'$temp\'\" >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;

			# append the broadcast
			$temp = `/opt/iba/ib_tools/iba_ipcalc --broadcast $ipaddr $netmask`;
			chomp($temp);
			$temp =~ s/BROADCAST=//;
			$SysCmd = "echo \"BROADCAST=\'$temp\'\" >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;

			$SysCmd = "echo \"REMOTE_IPADDR=\'\'\" >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;
		}

		$SysCmd = "echo \"STARTMODE=\'hotplug\'\" >> $target";
		DebugPrint("cmd '$SysCmd'\n");
		system $SysCmd;

		$SysCmd = "echo \"WIRELESS='no'\" >> $target";
		DebugPrint("cmd '$SysCmd'\n");
		system $SysCmd;

		$SysCmd = "echo \"NM_CONTROLLED='no'\" >> $target";
		DebugPrint("cmd '$SysCmd'\n");
		system $SysCmd;

		# SLES11 and newer have IPOIB_MODE option in ifcfg
		# set it consistent with openib.conf
		if ( "$CUR_VENDOR_VER" ne 'ES10') {
			my $ipoib_cm = read_openib_conf_param('SET_IPOIB_CM',"");
			if ( "$ipoib_cm" eq "yes" ) {
				$SysCmd = "echo \"IPOIB_MODE='connected'\" >> $target";
			} else {
				$SysCmd = "echo \"IPOIB_MODE='datagram'\" >> $target";
			}
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;
		}
	} else {
		# Append the device instance name
		$SysCmd = "echo DEVICE=$device > $target";
		DebugPrint("cmd '$SysCmd'\n");
		system $SysCmd;

		if ( "$ipaddr" eq "dhcp" ) {
			$SysCmd = "echo BOOTPROTO=dhcp >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;

			$SysCmd = "echo DHCPCLASS= >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;
		} else {

			$SysCmd = "echo BOOTPROTO=static >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;

			# Append the device instance Internet Protocol address
			$SysCmd = "echo IPADDR=$ipaddr >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;

			# append the network,broadcast
			$SysCmd = "/opt/iba/ib_tools/iba_ipcalc --network --broadcast $ipaddr $netmask >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;

			# append the netmask
			$SysCmd = "echo NETMASK=$netmask >> $target";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;
		}

		$SysCmd = "echo ONBOOT=yes >> $target";
		DebugPrint("cmd '$SysCmd'\n");
		system $SysCmd;

		$SysCmd = "echo NM_CONTROLLED=no >> $target";
		DebugPrint("cmd '$SysCmd'\n");
		system $SysCmd;
	}

	system "chown $OWNER $target";
	system "chgrp $GROUP $target";
	system "chmod ugo=r,u=rw $target";
}

sub Config_IP_Manually($$)
{
	my($compname) = shift();
	my($sampledev) = shift();

	print "\n$compname requires an ifcfg file for each $compname device instance.\n";
	print ("Manually create files such as '$ROOT$NETWORK_CONF_DIR/ifcfg-$sampledev'\n");
}


sub Exist_ifcfg($)
{
	my($prefix) = shift();

	my $ifcfg_wildcard="$NETWORK_CONF_DIR/ifcfg-$prefix"."[0-9]*";
	return ( `ls $ROOT$ifcfg_wildcard 2>/dev/null` ne "" );
}

#
# Generate the network interface config files for IP over IB
#	/etc/sysconfig/network-scripts/ifcfg-ibl1
#
# Assign IP (Internet Protocol) addresses in standard 'dot' notation to
# IP over IB device instances. Create IP over IB 'ifup ibX' configuration files
# located in '/etc/sysconfig/network-scripts' for each IP over IB port.
#
# **** Currently - ONLY static IP address assignment is supported.
#
# inputs:
#	[0] == are we reconfiguring, if 1, allows editing of existing ifcfg files
#
# outputs:
#	none.
#
sub Config_ifcfg($$$$$)
{
	my($reconfig) = shift();
	my($compname) = shift();
	my($prefix) = shift();
	my($firstdev) = shift();
	my($showoptions) = shift();

	my($max_ports,$port,$a,$inp,$seq,$intf_seq,$default_intf);
	my($netmask);
	my($ipaddr) = "";
	my($interface) = "";
	my(%interfaces) = ();
	my $config_dir;

	$max_ports = 0;
			
	# Check if ifcfg files are present
	my $ifcfg_wildcard="$NETWORK_CONF_DIR/ifcfg-$prefix"."[0-9]*";
	if ( `ls $ROOT$ifcfg_wildcard 2>/dev/null` ne "" )
	{
		if ($reconfig)
		{
			# always prompt regardless of previous check_keep_config answer
			clear_keep_config("$ifcfg_wildcard");
		}
		if (! $reconfig 
			|| check_keep_config("$ifcfg_wildcard", "$compname ifcfg files", "y"))
		{
			print "Leaving $ROOT$ifcfg_wildcard unchanged...\n";
			return;
		} 
		print "removing $ROOT$ifcfg_wildcard\n";
		system "rm -f $ROOT$ifcfg_wildcard";
	}
	if (GetYesNo("Configure $compname IPV4 addresses now?", "n") == 0)
	{
		# If user answered 'no', then reluctantly bail.
		Config_IP_Manually("$compname","$prefix$firstdev");
		return;
	}

	if ( $showoptions != 0 )
	{
		printf ("\nYou may configure an $compname interface for each IB port\n");
		printf ("Or you may select to have $compname only run on some IB ports\n");
		printf ("Or you may select to configure redundant IB ports with a\n");
		printf ("pair of IB ports running a single $compname interface\n");
	}
	do
	{
		printf ("How many $compname interfaces would you like to configure? [1]: ");

		$inp = <STDIN>;
		$inp=remove_whitespace($inp);

		if ( length($inp) == 0 ) 
		{
			$max_ports=1;
		} elsif ($inp < 0 || $inp > $MAX_IB_PORTS)
		{
			printf ("You must specify a number between 0 and $MAX_IB_PORTS\n");
		} elsif ($inp == 0) {
			LogPrint "How many $compname interfaces would you like to configure? -> $inp\n";
			if (GetYesNo("You specified 0, would you like to skip IP address configuration?", "n") == 1)
			{
				# If user answered to skip, then reluctantly bail.
				Config_IP_Manually("$compname","$prefix$firstdev");
				return;
			}
		} else {
			$max_ports=$inp;
			LogPrint "How many $compname interfaces would you like to configure? -> $inp\n";
		}
	} while ($max_ports == 0);

	print "\nAbout to create $compname ifcfg files in $NETWORK_CONF_DIR\n";

	# Does the user want sequential IP address assignment starting at a base
	# IP address or specify an IP address for each IB port (a.k.a. IPoIB device
	# instance). 

	if ( $max_ports > 1 ) {
		$intf_seq = GetYesNo("Configure interface names sequentially starting with $prefix$firstdev?", "y");
		$seq = GetYesNo("Assign Internet Addresses sequentially from a base IP address?", "y");
	} else {
		$intf_seq = GetYesNo("Use interface name $prefix$firstdev?", "y");
		$seq = 1;	# doesn't matter
	}

	# Allocate IP addresses and create the network config files '$prefix[firstdev...n]'.

	for($a=$firstdev; $a < $max_ports+$firstdev; $a++)
	{
		if ($intf_seq)
		{
			$interface="$prefix$a";
		} else {
			$default_intf = $interface;
			$interface = "";
			do {
				if ($default_intf eq "" )
				{
					print "Enter $compname interface name: ";
				} else {
					print "Enter $compname interface name [$default_intf]: ";
				}

				chomp($inp = <STDIN>);
				$inp=remove_whitespace($inp);
				if ( length($inp) == 0 )
				{
					$inp=$default_intf;
				}
				if ("$inp" eq "" )
				{
					printf "You must enter an interface name, such as $prefix$firstdev\n";
				} else {
					if (exists $interfaces{$inp})
					{
						print "You have already used $interface, specify a different name\n";
					} else {
						$interface=$inp;
						$interfaces{$interface} = 1;
					}
				}
			} while ("$interface" eq "");
		}
		LogPrint "Enter $compname interface name [$default_intf]: -> $interface\n";
		if ( $seq == 0 || $a == $firstdev) 
		{
			# not sequential assignment, get each IP addr.
			$ipaddr = Get_IP_Addr($interface, $ipaddr);
			$netmask = Get_IP_Addr_Netmask($interface, $ipaddr);
		}

		Build_ifcfg($interface, $ipaddr, $netmask);
		# make sure future prompts start fresh and don't auto remove
		clear_keep_config("$ifcfg_wildcard");

		# generate the next sequential IP address
		$ipaddr = NextIPaddr($ipaddr);
		$interface = NextInterface($interface);
	}
}

sub net_interface_down($)
{
	my($dev) = shift();	# base device name

	my($a);				# device instance number
	my($IF);			# interface name
	my($SysCmd);

	if ( ROOT_is_set() )
	{
		return;
	}
	# make sure the specified network interfaces are not running
	for($a=0; $a < $MAX_IB_PORTS; $a++)
	{
		$IF = "$NETWORK_CONF_DIR/ifcfg-".$dev."$a";
		if ( -r $IF )
		{
			$SysCmd = "/sbin/ifdown $dev"."$a";
			DebugPrint("cmd '$SysCmd'\n");
			system $SysCmd;
		}
	}
}


# Remove ifcfg files.
# driver should have already been unloaded.
#
sub Remove_ifcfg($$$)
{
	my($WhichDriver) = shift();	# driver name
	my($compname) = shift();
	my($prefix) = shift();

	if (IsModuleLoaded("$WhichDriver") == 1) 
	{
		print "Warning: '$WhichDriver' module still loaded? continuing...\n";
	}

	# This could be an 'update' where we might not want to clobber the
	# IPoIB config files.

	my $ifcfg_wildcard="$NETWORK_CONF_DIR/ifcfg-$prefix"."[0-9]*";
	if ( `ls $ROOT$ifcfg_wildcard 2>/dev/null` ne "" )
	{
		if (check_keep_config("$ifcfg_wildcard", "$compname ifcfg files", "y"))
		{
			print "Keeping $compname ifcfg files ...\n";
		} else {
			print "removing $ROOT$ifcfg_wildcard\n";
			system "rm -f $ROOT$ifcfg_wildcard";
		}
	}
}

sub check_network_config()
{
	my $nm=read_simple_config_param("$ROOT/etc/sysconfig/network/config", "NETWORKMANAGER");
	if ( "$nm" eq "yes" ) {
		print RED "Please set NETWORKMANAGER=no in $ROOT/etc/sysconfig/network/config", RESET "\n";
		HitKeyCont;
	}
}
#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# =============================================================================
# The functions and constants below assist in editing modules.conf or
# modprobe.conf to add IB specific entries

my $MODULE_CONF_FILE = "/etc/modules.conf";
my $MODULE_CONF_DIST_FILE;
if (substr($CUR_OS_VER,0,3) eq "2.6")
{
	$MODULE_CONF_FILE = "/etc/modprobe.conf";
	$MODULE_CONF_DIST_FILE = "/etc/modprobe.conf.dist";
}
if (-f "$(MODULE_CONF_FILE).local")
{
	$MODULE_CONF_FILE = "$(MODULE_CONF_FILE).local";
}
my $IBA_CONF="modules.conf";	## additions to modules.conf

# marker strings used in MODULES_CONF_FILE
# for entries added by installation
my $START_DRIVER_MARKER="InfiniBand Drivers Start here";
my $END_DRIVER_MARKER="InfiniBand Drivers End here";

# Keep track of whether we already did edits to avoid repeated edits
my $DidConfig=0;

sub	edit_modconf($)
{
	my($srcdir) = shift();	# directory containing $IBA_CONF file

	if ($DidConfig == 1)
	{
		return;
	}
	edit_conf_file("$srcdir/$IBA_CONF.$CUR_DISTRO_VENDOR", "$MODULE_CONF_FILE",
		"module dependencies", "$START_DRIVER_MARKER",  "$END_DRIVER_MARKER");
	$DidConfig = 1;
}

# remove iba entries from modules.conf
sub remove_modules_conf()
{
	$DidConfig = 0;
	if (check_keep_config($MODULE_CONF_FILE, "", "y"))
	{
		print "Keeping $ROOT/$MODULE_CONF_FILE changes ...\n";
	} else {
		print "Modifying $ROOT$MODULE_CONF_FILE ...\n";
		del_marks ("$START_DRIVER_MARKER", "$END_DRIVER_MARKER", 0, "$ROOT$MODULE_CONF_FILE");
	}
}

# This code is from OFED, it removes lines related to IB from
# modprobe.conf.  Used to prevent distro specific effects on OFED.
sub disable_distro_ofed()
{
	if ( "$MODULE_CONF_DIST_FILE" ne "" && -f "$ROOT$MODULE_CONF_DIST_FILE" ) {
		my $res;

		$res = open(MDIST, "$ROOT$MODULE_CONF_DIST_FILE");
		if ( ! $res ) {
			NormalPrint("Can't open $ROOT$MODULE_CONF_DIST_FILE for input: $!");
			return;
		}
		my @mdist_lines;
		while (<MDIST>) {
			push @mdist_lines, $_;
		}
		close(MDIST);

		$res = open(MDIST, ">$ROOT$MODULE_CONF_DIST_FILE");
		if ( ! $res ) {
			NormalPrint("Can't open $ROOT$MODULE_CONF_DIST_FILE for output: $!");
			return;
		}
		foreach my $line (@mdist_lines) {
			chomp $line;
			if ($line =~ /^\s*install ib_core|^\s*alias ib|^\s*alias net-pf-26 ib_sdp/) {
				print MDIST "# $line\n";
			} else {
				print MDIST "$line\n";
			}
		}
		close(MDIST);
	}
}

# =============================================================================
# The functions and constants below assist in editing limits.conf
# to add IB specific entries related to memory locking

my $LIMITS_CONF_FILE = "/etc/security/limits.conf";
my $LIMITS_CONF="limits.conf";	## additions to limits.conf

# marker strings used in LIMITS_CONF_FILE
# for entries added by installation
my $START_LIMITS_MARKER="InfiniBand Settings Start here";
my $END_LIMITS_MARKER="InfiniBand Settings End here";

# Keep track of whether we already did edits to avoid repeated edits
my $DidLimits=0;

sub	edit_limitsconf($)
{
	my($srcdir) = shift();	# directory containing $LIMITS_CONF file

	my $SourceFile;

	if ($DidLimits == 1)
	{
		return;
	}
	if (! -e "$ROOT$LIMITS_CONF_FILE")
	{
		# older distros don't have this file
		return;
	}
	# not all distros will have a update for this file
	if ( -e "$srcdir/$LIMITS_CONF.$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER" ) {
		$SourceFile="$srcdir/$LIMITS_CONF.$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER";
	} elsif ( -e "$srcdir/$LIMITS_CONF.$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER" ) {
		$SourceFile="$srcdir/$LIMITS_CONF.$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER";
	} elsif ( -e "$srcdir/$LIMITS_CONF.$CUR_DISTRO_VENDOR" )
	{
		$SourceFile="$srcdir/$LIMITS_CONF.$CUR_DISTRO_VENDOR";
	} else {
		$SourceFile="/dev/null";
	}
	edit_conf_file("$SourceFile", "$LIMITS_CONF_FILE",
		"memory locking limits", "$START_LIMITS_MARKER",  "$END_LIMITS_MARKER");
	$DidLimits = 1;
}

# remove iba entries from modules.conf
sub remove_limits_conf()
{
	$DidLimits = 0;
	if ( -e "$ROOT$LIMITS_CONF_FILE") {
		if (check_keep_config($LIMITS_CONF_FILE, "", "y"))
		{
			print "Keeping $ROOT/$LIMITS_CONF_FILE changes ...\n";
		} else {
			print "Modifying $ROOT$LIMITS_CONF_FILE ...\n";
			del_marks ("$START_LIMITS_MARKER", "$END_LIMITS_MARKER", 0, "$ROOT$LIMITS_CONF_FILE");
		}
	}
}

#
# Override the system's standard udev configuration to allow
# different access rights to some of the infiniband device files.
# Note that different distros use different configuration models.
#
# If the permissions.d directory exists, we will install the
# permissions file; if the rules directory exists we will install
# the rules file.
#
my $UDEV_PERMISSIONS_DIR = "/etc/udev/permissions.d";
my $UDEV_PERMISSIONS_FILE = "05-qib.permissions";
my $OLD_UDEV_PERMISSIONS_FILE = "05-qlogic.permissions";
my $UDEV_RULES_DIR ="/etc/udev/rules.d";
my $UDEV_RULES_FILE = "05-qib.rules";
my $OLD_UDEV_RULES_FILE = "05-qlogic.rules";
my $Default_UserQueries = 0;

AddAnswerHelp("UserQueries", "Permit non-root users to query the fabric");

sub install_udev_permissions($)
{
	my ($srcdir) = shift(); # source directory.
	my $SourceFile;

	if ($Default_UserQueries == 0) {
		$Default_UserQueries = GetYesNoWithMemory("UserQueries",0,"Permit non-root users to query the fabric?", "y");
	}

	if ($Default_UserQueries > 0) {
		if ( -e "$ROOT$UDEV_PERMISSIONS_DIR" ) {
			if ( -e "$srcdir/udev.permissions.$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER" ) {
				$SourceFile="$srcdir/udev.permissions.$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER";
			} elsif ( -e "$srcdir/udev.permissions.$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER" ) {
				$SourceFile="$srcdir/udev.permissions.$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER";
			} else {
				$SourceFile="$srcdir/udev.permissions";
			}
			print "Updating udev permissions.\n";
			#removing older file
			remove_file("$UDEV_PERMISSIONS_DIR/$OLD_UDEV_PERMISSIONS_FILE");
			copy_file("$SourceFile",
					  "$UDEV_PERMISSIONS_DIR/$UDEV_PERMISSIONS_FILE",
					  "root", "root",
					  "0644");
		}
		if ( -e "$ROOT$UDEV_RULES_DIR" ) {
			if ( -e "$srcdir/udev.rules.$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER" ) {
				$SourceFile="$srcdir/udev.rules.$CUR_DISTRO_VENDOR.$CUR_VENDOR_VER";
			} elsif ( -e "$srcdir/udev.rules.$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER" ) {
				$SourceFile="$srcdir/udev.rules.$CUR_DISTRO_VENDOR.$CUR_VENDOR_MAJOR_VER";
			} else {
				$SourceFile="$srcdir/udev.rules";
			}
			print "Updating udev rules.\n";
			#removing older file
			remove_file("$UDEV_RULES_DIR/$OLD_UDEV_RULES_FILE");
			copy_file("$SourceFile",
					  "$UDEV_RULES_DIR/$UDEV_RULES_FILE",
					  "root", "root",
					  "0644");
		}
	}
}

sub remove_udev_permissions()
{
	remove_file("$UDEV_PERMISSIONS_DIR/$OLD_UDEV_PERMISSIONS_FILE");
	remove_file("$UDEV_RULES_DIR/$OLD_UDEV_RULES_FILE");
	remove_file("$UDEV_PERMISSIONS_DIR/$UDEV_PERMISSIONS_FILE");
	remove_file("$UDEV_RULES_DIR/$UDEV_RULES_FILE");
}
#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ===========================================================================
# Host Tools

# capture host information for problem report
sub capture_report($)
{
	my($req_compname) = shift();

	my $result;
	my $inp;
	my $detail;

	if ( ! -e "/sbin/iba_capture" ) {
		printf("$req_compname not installed on this system\n");
		printf("Unable to Generate Supporting Information\n");
		HitKeyCont;
		return;
	}

GET_FILENAME:
	printf ("\n\nEnter Filename to Generate [q to quit] : ");
	$inp = <STDIN>;
	$inp=remove_whitespace($inp);
	chomp $inp;
	$_ = $inp;
		
	if (/^[Qq]$/) {
		return;
	}

	if ( length($inp) == 0 ) {
		goto GET_FILENAME;
	}

	LogPrint "Capturing $INT_VERSION Report to $inp\n";
	$detail=GetNumericValue("Capture detail level (1-Normal 2-Fabric 3-Fabric+FDB 4-Analysis):", 1, 1, 4);
	close_log;
	$result = system "/sbin/iba_capture -d $detail $inp";
	if ( $result != 0 ) {
		printf("\nError generating $inp\n");
		goto GET_FILENAME;
	}
	open_log;
	HitKeyCont;
}

# invoke FastFabric TUI
my $FabricSetupScpFromDir=".";

sub run_fastfabric($)
{
	my($req_compname) = shift();

	if ( ! -e "/sbin/fastfabric" ) {
		printf("$req_compname not installed on this system\n");
		printf("Unable to perform FastFabric (Host/Chassis/Switch Setup/Admin)\n");
		HitKeyCont;
		return;
	}
	system("/sbin/fastfabric -r '$ROOT' --fromdir $FabricSetupScpFromDir");
	return;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# =============================================================================
# The functions and constants below assist in using RPM files

# mand_target_cpu32 is for RPMs only available as 32 bit (tvflash on ppc64)
# target_cpu32 is for optional 32 bit rpms
# on platforms without 32 bit app on 64 bit OS support, these are ''
# _glob is a glob pattern version which can be used to match rpm names
# when building rpms the simple _cpu32 values should be used
my $mand_target_cpu32="";	# computed for 64 bit OS with 32 bit CPU support
my $mand_target_cpu32_glob="";	# computed for 64 bit OS with 32 bit CPU support
my $target_cpu32="";	# computed for 64 bit OS with 32 bit CPU support
my $target_cpu32_glob="";	# computed for 64 bit OS with 32 bit CPU support
my $suffix_32bit = "";	# suffix for rpm name for 32 bit rpms
my $suffix_64bit = "";	# suffix for rpm name for 64 bit rpms

my $rpm_check_dependencies = 1;	# can be set to 0 to disable rpm_check_os_prereqs

sub rpm_query_param($);
# TBD or
# my $RPM_ARCH = rpm_query_param('_target_cpu');
# chomp $RPM_ARCH;
my $RPM_ARCH=my_tolower("$ARCH");
if ( "$RPM_ARCH" eq "ia32" ) {
	$RPM_ARCH = rpm_query_param('_target_cpu');
	#$RPM_ARCH=`uname -m`; # or i386
	chomp $RPM_ARCH;
}
my $RPM_KERNEL_ARCH = `uname -m`; # typically matches $RPM_ARCH
chomp $RPM_KERNEL_ARCH;

my $RPM_DIST=`rpm -qf /etc/issue 2>/dev/null|head -1`;
chomp $RPM_DIST;
if ( "$RPM_DIST" eq "" ) {
	$RPM_DIST="unsupported";
} else {
	# This effectively gets rid of any CPU architecture suffix in RPM_DIST
	$RPM_DIST=`rpm -q --queryformat "[%{NAME}]-[%{VERSION}]-[%{RELEASE}]" $RPM_DIST 2>/dev/null`;
	chomp $RPM_DIST;
	if ( "$RPM_DIST" eq "" ) {
		$RPM_DIST="unsupported";
	}
}
sub rpm_query_release_pkg($);
my $RPM_DIST_REL = rpm_query_release_pkg($RPM_DIST);

# initialize cpu32 settings for ARCH for rpm installation
sub init_cpu32()
{
	# compute mand_target_cpu32 and initialize target_cpu32
	# set '' if no 32 bit support/need
	if ("$ARCH" eq 'X86_64') {
		if ("$CUR_DISTRO_VENDOR" eq 'SuSE') {
			$mand_target_cpu32='i586';
		} else {
			$mand_target_cpu32='i686';
		}
		$mand_target_cpu32_glob='i[3456]86';
	} elsif ( "$ARCH" eq 'PPC64') {
		$mand_target_cpu32 = 'ppc';
		$mand_target_cpu32_glob = 'ppc';
	} else {
		$mand_target_cpu32='';
		$mand_target_cpu32_glob='';
	}
	if (! $OFED_no32bit) {
		$target_cpu32 = $mand_target_cpu32;
		$target_cpu32_glob = $mand_target_cpu32_glob;
	} else {
		$target_cpu32='';
		$target_cpu32_glob='';
	}

	# SLES11 specific suffix to package names
	if ("$CUR_DISTRO_VENDOR" eq 'SuSE') {
		if ("$ARCH" eq 'PPC64' && "$CUR_VENDOR_VER" ne "ES11" ) {
			$suffix_32bit = "";
			$suffix_64bit = "-64bit";
		} else {
			$suffix_32bit = "-32bit";
			$suffix_64bit = "";
		}
	}
}

# version string for kernel used in RPM filenames uses _ instead of -
sub rpm_tr_os_version($)
{
	my($osver) = shift();	# uname -r style output
	$osver =~ s/-/_/g;
	return "$osver";
}

# query a parameter of RPM tools themselves
sub	rpm_query_param($)
{
	my($param) = shift();	# parameter name: such as _mandir, _sysconfdir, _target_cpu
	my $ret = `chroot /$ROOT $RPM --eval "%{$param}"`;
	chomp $ret;
	return $ret;
}

# query an attribute of the RPM file
sub	rpm_query_attr($$)
{
	my($rpmfile) = shift();	# .rpm file
	my($attr) = shift();	# attribute name: such as NAME or VERSION

	if ( ! -f "$rpmfile" ) {
		return "";
	}
	return `$RPM --queryformat "[%{$attr}]" -qp $rpmfile 2>/dev/null`;
}

# query an attribute of the installed RPM package
sub	rpm_query_attr_pkg($$)
{
	my($package) = shift();	# installed package
	my($attr) = shift();	# attribute name: such as NAME or VERSION

	return `chroot /$ROOT $RPM --queryformat "[%{$attr}]" -q $package 2>/dev/null`;
}

# determine if rpm parameters will allow srpms to build debuginfo rpms
sub rpm_will_build_debuginfo()
{
	# If debug_package is set to nil in .rpmmacros, srpms will not generate
	# -debuginfo rpms, so they will not be available to install
	return (rpm_query_param('debug_package') ne "");
}

# get NAME of RPM file
sub rpm_query_name($)
{
	my($rpmfile) = shift();	# .rpm file

	return rpm_query_attr($rpmfile, "NAME");
}

# get RELEASE of installed RPM package
sub rpm_query_release_pkg($)
{
	my($package) = shift();	# installed package

	return rpm_query_attr_pkg($package, "RELEASE");
}

sub rpm_query_version_release($)
{
	my($rpmfile) = shift();	# .rpm file

	my $ver = rpm_query_attr($rpmfile, "VERSION");
	my $rel = rpm_query_attr($rpmfile, "RELEASE");
	return "${ver}-${rel}";
}

# get VERSION-RELEASE of installed RPM package
sub rpm_query_version_release_pkg($)
{
	my($package) = shift();	# installed package

	my $ver = rpm_query_attr_pkg($package, "VERSION");
	my $rel = rpm_query_attr_pkg($package, "RELEASE");
	return "${ver}-${rel}";
}

# return NAME-VERSION-RELEASE.ARCH
sub rpm_query_full_name($)
{
	my($rpmfile) = shift();	# .rpm file

	if ( ! -f "$rpmfile" ) {
		return "";
	}
	return `$RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}]' -qp $rpmfile 2>/dev/null`;
}

# beware, this could return more than 1 name
#sub rpm_query_full_name_pkg($)
#{
#	my($package) = shift();	# installed package
#	return `chroot /$ROOT $RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}]' -q $package 2>/dev/null`;
#}

# this is a hack to handle tvflash not being 64 bit on PPC64 redhat
# we translate mode between user and user32 and indicate proper cpu to test
# against such that tvflash will be
# treated properly (eg.  the 32 bit app is part of user not user32 operations)
# similarly mpi-frontend is always 32 bit
# returns ( $mode, $cpu_glob )
sub rpm_adjust_mode_cpu($$)
{
	my($package) = shift();	# package name
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed

	if ("$package" eq "mpi-frontend") {
		if ("$mode" eq "user32") {
			return ("user", $RPM_ARCH);	# package should not be found
		} elsif ("$mode" eq "user" || "$mode" eq "any") {
			return ("user32", $mand_target_cpu32_glob);
		}
	} elsif ("$package" eq "tvflash" && "$CUR_DISTRO_VENDOR" eq "redhat"
		 && "$ARCH" eq "PPC64" ) {
		if ("$mode" eq "user32") {
			return ("user", $RPM_ARCH);	# package should not be found
		} elsif ("$mode" eq "user" || "$mode" eq "any") {
			return ("user32", $mand_target_cpu32_glob);
		}
	} else {
		# the typical case
		if ("$mode" eq "user32") {
			return ($mode, $mand_target_cpu32_glob);
		} elsif ("$mode" eq "user" || "$mode" eq "any") {
			return ($mode, $RPM_ARCH);
		} else {
			return ($mode, $RPM_KERNEL_ARCH);
		}
	}
}

my $last_checked;	# last checked for in rpm_is_installed
sub rpm_is_installed($$)
{
	my($package) = shift();	# package name
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed
	my $rc;
	my $cpu;

	# for now, when checking for qlogic_fm, check the ifs_fm rpm instead, as it has been renamed

	( $mode, $cpu ) = rpm_adjust_mode_cpu($package, $mode);
	if ("$mode" eq "any" ) {
		# any variation is ok
		DebugPrint("$RPM -q $package > /dev/null 2>&1\n");
		$rc = system("chroot /$ROOT $RPM -q $package > /dev/null 2>&1");
		$last_checked = "any variation";
	} elsif ("$mode" eq "user") {
		# verify $cpu version or noarch is installed
		DebugPrint "chroot /$ROOT $RPM --queryformat '[%{ARCH}\\n]' -q $package 2>/dev/null|egrep '^$cpu\$|^noarch\$' >/dev/null 2>&1\n";
		$rc = system "chroot /$ROOT $RPM --queryformat '[%{ARCH}\\n]' -q $package 2>/dev/null|egrep '^$cpu\$|^noarch\$' >/dev/null 2>&1";
		$last_checked = "for $cpu or noarch";
	} elsif ("$mode" eq "user32") {
		# verify $mand_target_cpu32 version is installed
		DebugPrint "chroot /$ROOT $RPM --queryformat '[%{ARCH}\\n]' -q $package 2>/dev/null|egrep '^$cpu\$' >/dev/null 2>&1\n";
		$rc = system "chroot /$ROOT $RPM --queryformat '[%{ARCH}\\n]' -q $package 2>/dev/null|egrep '^$cpu\$' >/dev/null 2>&1";

		$last_checked = "for $cpu";
	} else {
		# $mode is kernel rev, verify proper kernel version is installed
		# for kernel packages, RELEASE is kernel rev
		my $release = rpm_tr_os_version($mode);
		DebugPrint "chroot /$ROOT $RPM --queryformat '[%{RELEASE}\\n]' -q $package 2>/dev/null|egrep '^$release\$' >/dev/null 2>&1\n";
		$rc = system "chroot /$ROOT $RPM --queryformat '[%{RELEASE}\\n]' -q $package 2>/dev/null|egrep '^$release\$' >/dev/null 2>&1";
		$last_checked = "for kernel $release";
	}
	DebugPrint("Checked if $package $mode is installed: ".(($rc==0)?"yes":"no")."\n");
	return 0 == $rc;
}

sub rpm_is_installed_list($@)
{
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- verifies any variation of package is installed
	my(@package_list) = @_;	# package names

	foreach my $package ( @package_list )
	{
		if ( !  rpm_is_installed($package, $mode) ) {
			return 0;
		}
	}
	return 1;
}

# return 0 on success, number of errors otherwise
sub rpm_check_os_prereqs_internal($$@)
{
	my $mode = shift();	# default mode
	my $message = shift();
	my(@package_list) = @_;	# package names
	my $err=0;
	
	if ( ! $rpm_check_dependencies ) {
		return 0;
	}
	# Check installation requirements
	DebugPrint "Checking prereqs $message: @package_list\n";
	for my $package_info ( @package_list )
	{
		# expand any alias in package_info
		my $full_package_info="";
		my @alternatives = (split ('\|',$package_info));
		for my $altpackage_info ( @alternatives )
		{
			my ($package, $details) = (split (' ',$altpackage_info,2));
			if ($details ne "") {
				$details=" $details";
			}
			if ( "$full_package_info" ne "" ) {
				$full_package_info = "$full_package_info|";
			}

			# expand "g77" alias for various fortran compilers
			# and "libgfortran" alias for various fortran library
			if ("$package" eq "g77" ) {
				# on RHEL4u5-6: gcc4-gfortran, gcc-g77
				# on RHEL5.1: gcc-gfortran, compat-gcc-34-g77
				# on RHEL5.2: gcc-gfortran
				# on RHEL5.3: gcc43-gfortran
				# on sles10sp1-2: gcc-fortran
				# on sles11: gcc-fortran
				$full_package_info = "${full_package_info}gcc4-gfortran$details|gcc-g77$details|gcc-gfortran$details|compat-gcc-34-g77$details|gcc43-gfortran$details|gcc42-gfortran$details|gcc-fortran$details|gcc42-fortran$details|gcc43-fortran$details|gcc48-fortran$details"

			} elsif ("$package" eq "libgfortran") {
				# on RHEL4u5-6: libgfortran
				# on RHEL5.1: libgfortran
				# on RHEL5.2: libgfortran
				# on RHEL5.3: libgfortran43
				# on sles10sp1-2: libgfortran
				# on sles11sp0-1: libgfortran43
				# on sles11sp2: libgfortran46
				# TBD - openSUSE11.2 has libgfortran44
				$full_package_info = "${full_package_info}libgfortran$details|libgfortran42$details|libgfortran43$details|libgfortran46$details|compat-gcc-34-g77$details|libgfortran3$details";
			} else {
				$full_package_info = "${full_package_info}$altpackage_info";
			}
		}

		# now process the expanded list of alternatives
		DebugPrint "Checking prereq: $full_package_info\n";
		my $errmessage="";
		my @alternatives = (split ('\|',$full_package_info));
		for my $altpackage_info ( @alternatives )
		{
			DebugPrint "Checking prereq: $altpackage_info\n";
			my ($package, $version, $pkgmode) = (split (' ',$altpackage_info));
			if ("$pkgmode" eq "") {
				$pkgmode = $mode;
			}

			# keep things simple for callers, handle distro specific namings
			
			# distro specific naming of libstdc++
			if ("$package" eq "libstdc++" && "$CUR_DISTRO_VENDOR" eq 'SuSE'
					&& "$CUR_VENDOR_VER" eq 'ES11') {
				# hack because CUR_VENDOR_VER doesn't actually contain the minor 
				# version any more...
				my $CUR_VENDOR_MINOR_VER = `grep PATCHLEVEL /etc/SuSE-release | cut -d' ' -f 3`;
				chop($CUR_VENDOR_MINOR_VER);
				if ($CUR_VENDOR_MINOR_VER eq '0' || $CUR_VENDOR_MINOR_VER eq '1') { $package="libstdc++43"; }
				if ($CUR_VENDOR_MINOR_VER eq '2' ) { $package="libstdc++46"; }
				if ($CUR_VENDOR_MINOR_VER eq '3' ) { $package="libstdc++6"; }
				if ($CUR_VENDOR_MINOR_VER eq '4' ) { $package="libstdc++6"; }
				# SLES11 SP3 has renamed libstdc++47 as libstdc++6
				# TBD - openSUSE has libstdc++42
				# TBD - openSUSE11.2 has libstdc++44
			} elsif ("$package" eq "libstdc++-devel" && "$CUR_DISTRO_VENDOR" eq 'SuSE'
					&& "$CUR_VENDOR_VER" eq 'ES11') {
				# hack because CUR_VENDOR_VER doesn't actually contain the minor 
				# version any more...
				my $CUR_VENDOR_MINOR_VER = `grep PATCHLEVEL /etc/SuSE-release | cut -d' ' -f 3`;
				chop($CUR_VENDOR_MINOR_VER);
				if ($CUR_VENDOR_MINOR_VER eq '0' || $CUR_VENDOR_MINOR_VER eq '1') { $package="libstdc++43-devel"; }
				if ($CUR_VENDOR_MINOR_VER eq '2' ) { $package="libstdc++46-devel"; }
				if ($CUR_VENDOR_MINOR_VER eq '3') { $package="libstdc++47-devel"; }
				if ($CUR_VENDOR_MINOR_VER eq '4') { $package="libstdc++48-devel"; }
				# TBD - openSUSE has libstdc++42-devel
				# TBD - openSUSE11.2 has libstdc++44-devel
			} elsif ("$package" eq "libstdc++" && "$CUR_DISTRO_VENDOR" eq 'SuSE'
					&& "$CUR_VENDOR_VER" eq 'ES12') {
				# hack because CUR_VENDOR_VER doesn't actually contain the minor 
				# version any more...
				my $CUR_VENDOR_MINOR_VER = `grep PATCHLEVEL /etc/SuSE-release | cut -d' ' -f 3`;
				chop($CUR_VENDOR_MINOR_VER);
				if ($CUR_VENDOR_MINOR_VER eq '0' || $CUR_VENDOR_MINOR_VER eq '1') { $package="libstdc++6"; }
		 	} elsif ("$package" eq "libstdc++-devel" && "$CUR_DISTRO_VENDOR" eq 'SuSE'
					&& "$CUR_VENDOR_VER" eq 'ES12') {
				# hack because CUR_VENDOR_VER doesn't actually contain the minor 
				# version any more...
				my $CUR_VENDOR_MINOR_VER = `grep PATCHLEVEL /etc/SuSE-release | cut -d' ' -f 3`;
				chop($CUR_VENDOR_MINOR_VER);
				if ($CUR_VENDOR_MINOR_VER eq '0' || $CUR_VENDOR_MINOR_VER eq '1') { $package="libstdc++48-devel"; }
			}


			# distro specific naming of sysfsutils
			if ("$package" eq "sysfsutils" ) {
				if ("$CUR_DISTRO_VENDOR" ne 'SuSE' && "$CUR_DISTRO_VENDOR" ne 'redhat'
			    	&& "$CUR_DISTRO_VENDOR" ne 'fedora' && "$CUR_DISTRO_VENDOR" ne 'rocks') {
					$package="libsysfs";
				} elsif (($CUR_DISTRO_VENDOR eq "redhat" and ($CUR_VENDOR_VER eq "ES6" or $CUR_VENDOR_VER eq "ES7"))) {
        			$package = "libsysfs";
				}
			}

			# distro specific naming of sysfsutils-devel
			# RHEL4 used sysfsutils-devel
			# RHEL6 uses libsysfs
			# SuSE uses sysfsutils
			# others use libsysfs-devel
			if ("$package" eq "sysfsutils-devel" ) {
				if (($CUR_DISTRO_VENDOR eq "SuSE")
					or ($CUR_DISTRO_VENDOR eq "redhat" and $CUR_VENDOR_VER eq "ES5")
	) {
        			$package = "sysfsutils";
				} elsif (($CUR_DISTRO_VENDOR eq "redhat" and ($CUR_VENDOR_VER eq "ES6" or $CUR_VENDOR_VER eq "ES7"))) {
        			$package = "libsysfs";
    			} elsif (($CUR_DISTRO_VENDOR eq "rocks") or
        			($CUR_DISTRO_VENDOR eq "fedora") or
        			($CUR_DISTRO_VENDOR eq "redhat")) {
        				$package = "sysfsutils-devel";
    			} else {
        			$package = "libsysfs-devel";
    			}

			}

			# distro specific naming of binutils for development
			# SLES11 and RHEL5 have binutils-devel, others have binutils
		 	if ("$package" eq "binutils-devel"
				&& ! ("$CUR_DISTRO_VENDOR" eq 'SuSE' && "$CUR_VENDOR_VER" eq 'ES11')
				&& ! ("$CUR_DISTRO_VENDOR" eq 'redhat' && "$CUR_VENDOR_VER" eq 'ES5')
				&& ! ("$CUR_DISTRO_VENDOR" eq 'redhat' && "$CUR_VENDOR_VER" eq 'ES6')
				) {
				$package="binutils";
			}
		
			if ("$pkgmode" eq "user") {
				# SLES10 and 11 -64bit rpms report ppc as ARCH
				$package="$package$suffix_64bit";
				if ( "$suffix_64bit" ne "" ) {
					$pkgmode="any";
				}
			} elsif ("$pkgmode" eq "user32") {
				# SLES10 and 11 -32bit rpms report x86_64 as ARCH
				$package="$package$suffix_32bit";
				if ( "$suffix_32bit" ne "" ) {
					$pkgmode="user";
				}
			}
			if (! rpm_is_installed($package, $pkgmode)) {
				if ( $errmessage ne "") {
					$errmessage="$errmessage\n OR ";
				}
				$errmessage = "$errmessage$package ($last_checked)";
			#} elsif ("$version" ne "" && "$version" ne "any") {
			#	# TBD - could be multiple versions of package installed
			#	# in which case this returns merged strings, not good
			#	my $ver = rpm_query_attr_pkg($package, "VERSION");
			#	TBD - string compare not the same as proper numeric compare
			#	if ($ver lt $version) {
			#		if ( $errmessage ne "") {
			#			$errmessage="$errmessage\n OR ";
			#		}
			#		$errmessage = "$errmessage$package version $version ($last_checked)";
			#	}
			} else {
				$errmessage="";
				last;
			}
		}
		if ( $errmessage ne "" ) {
			if (scalar(@alternatives) > 1) {
				$errmessage="$errmessage\n";
			}
			NormalPrint("$errmessage is required$message\n");
			$err++;
		}
	}
	return $err;
}

sub rpm_check_os_prereqs($$@)
{
	my $comp = shift();
	my $mode = shift();
	my(@package_list) = @_;	# package names
	return rpm_check_os_prereqs_internal($mode, " by $ComponentInfo{$comp}{'Name'}", @package_list);
}

sub rpm_check_build_os_prereqs($$@)
{
	my $mode = shift();
	my $build_info = shift();
	my(@package_list) = @_;	# package names
	return rpm_check_os_prereqs_internal($mode, " to build $build_info", @package_list);
}

# get list of package rpms installed
# the list could include multiple versions and/or multiple architectures
# and/or multiple kernel releases
# all entries in returned list are complete package names in the form:
#	NAME-VERSION-RELEASE.ARCH
sub rpms_installed_pkg($$)
{
	my $package=shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed

	my @lines=();
	my $cpu;

	( $mode, $cpu ) = rpm_adjust_mode_cpu($package, $mode);
	if ( "$mode" eq "any" ) {
		DebugPrint("chroot /$ROOT $RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n]' -q $package 2>/dev/null\n");
		open(rpms, "chroot /$ROOT $RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n]' -q $package 2>/dev/null|");
	} elsif ("$mode" eq "user" ) {
		DebugPrint("chroot /$ROOT $RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n]' -q $package 2>/dev/null|egrep '\.$cpu\$|\.noarch\$' 2>/dev/null\n");
		open(rpms, "chroot /$ROOT $RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n]' -q $package 2>/dev/null|egrep '\.$cpu\$|\.noarch\$' 2>/dev/null|");
	} elsif ("$mode" eq "user32" ) {
		DebugPrint("chroot /$ROOT $RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n]' -q $package 2>/dev/null|egrep '\.$cpu\$' 2>/dev/null\n");
		open(rpms, "chroot /$ROOT $RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n]' -q $package 2>/dev/null|egrep '\.$cpu\$' 2>/dev/null|");
	} else {
		# $mode is kernel rev, verify proper kernel version is installed
		# for kernel packages, RELEASE is kernel rev
		my $release = rpm_tr_os_version($mode);
		DebugPrint("chroot /$ROOT $RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n]' -q $package 2>/dev/null|egrep '-$release\.$cpu\$' 2>/dev/null\n");
		open(rpms, "chroot /$ROOT $RPM --queryformat '[%{NAME}-%{VERSION}-%{RELEASE}.%{ARCH}\n]' -q $package 2>/dev/null|egrep '-$release\.$cpu\$' 2>/dev/null|");
	}
	@lines=<rpms>;
	close(rpms);
	if ( $? != 0) {
		# query command failed, package must not be installed
		@lines=();
	}
	chomp(@lines);
	DebugPrint("package $package $mode: installed: @lines\n");
	return @lines;
}

# identify all possible variations of the package
# based on distro/cpu and mode, -32bit and -64bit variations may be included
sub rpm_variations($$)
{
	my $package=shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed
	my @variations = ( $package );
	if ( ("$mode" eq "any" || "$mode" eq "user32") && $suffix_32bit ne "") {
		@variations = (@variations, "$package$suffix_32bit");
	}
	if ( ("$mode" eq "any" || "$mode" eq "user") && $suffix_64bit ne "") {
		@variations = (@variations, "$package$suffix_64bit");
	}
	return @variations;
}

# get list of package rpms installed
# based on distro/cpu and mode, -32bit and -64bit variations may be included
# the list could include multiple versions and/or multiple architectures
# and/or multiple kernel releases
# all entries in returned list are complete package names in the form:
#	NAME-VERSION-RELEASE.ARCH
sub rpms_variations_installed_pkg($$)
{
	my $package=shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed

	my @result=();

	foreach my $p ( rpm_variations($package, $mode) ) {
		@result = ( @result, rpms_installed_pkg($p, $mode) );
	}
	return @result;
}

# determine if given rpm contains the given file
sub rpm_has_file($$)
{
	my($rpmfile) = shift();	# .rpm file
	my($file) = shift();		# file to look for in rpm

	if ( ! -f "$rpmfile" ) {
		return 0;
	}
	return (! system("$RPM -qlp $rpmfile 2>/dev/null | grep '/${file}\$' > /dev/null 2>&1"));
}

# return names of all installed RPMs matching the given partial name and filter
sub rpm_query_all($$)
{
	my $package = shift();
	my $filter = shift();

	my $res=`chroot /$ROOT $RPM -qa 2>/dev/null|grep -i '$package'|grep '$filter'`;
	$res=~s/\n/ /g;
	return $res;
}

# uninstall all packages which match package partial name and filter
# returns 0 on sucess (or package not installed), != 0 on failure
sub rpm_uninstall_matches($$$;$)
{
	my $name = shift();	# for use only in log messages
	my $package = shift();	# part of package name
	my $filter = shift();	# any additional grep filter
	my $options = shift();	# additional rpm command options
	my $rpms = rpm_query_all("$package", "$filter");

	if ( "$rpms" ne "" ) {
		LogPrint "uninstalling $name: $RPM -e $rpms\n";
		my $out =`chroot /$ROOT $RPM -e $options $rpms 2>&1`;
		my $rc=$?;
		NormalPrint("$out");
		return $rc;
	} else {
		return 0;
	}
}

sub rpm_run_install($$$)
{
	my($rpmfile) = shift();	# .rpm file
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- will install any variation found (32 or 64 bit)
	my($options) = shift();	# additional rpm command options
						# if " -U " is part of these options, -U will be
						# unconditionally used, even if the rpm is not
						# already installed.  Otherwise -U will only be
						# used if the rpm is installed.  Note that some OFED
						# rpms do not properly handle -U for actual upgrades.
						# Hence for OFED we tend to uninstall the old rpms first
						# and the rpm -i is used to install here.

	my $chrootcmd="";
	my $Uoption= 0;

	# We require whitespace around -U so its not mistaken for filenames or other
	# multi-letter options
	if ($options =~ / -U /) {
		$Uoption=1;
		$options =~ s/ -U //;
	}
	
	if ( ! -e $rpmfile ) {
		NormalPrint "Not Found: $rpmfile $mode\n";
		return;
	}

	if (ROOT_is_set()) {
		LogPrint "  cp $rpmfile $ROOT/var/tmp/rpminstall.tmp.rpm\n";
		if (0 != system("cp $rpmfile $ROOT/var/tmp/rpminstall.tmp.rpm")) {
			LogPrint "Unable to copy $rpmfile $ROOT/var/tmp/rpminstall.tmp.rpm\n";
			return;
		}
		# just to new ROOT relative name for use in commands below
		$rpmfile = "/var/tmp/rpminstall.tmp.rpm";
		$chrootcmd="chroot $ROOT ";
	}

	my $package = rpm_query_name($rpmfile);
	my $fullname = rpm_query_full_name($rpmfile);
	my $out;

	NormalPrint "installing ${fullname}...\n";

	my $upgrade=rpm_is_installed($package, $mode);
	if ( ! $upgrade ) {
		my @obsoletes = split /[[:space:]]+/, `$RPM --queryformat '[%{OBSOLETES}\\n]' -qp $rpmfile 2>/dev/null`;
		for my $p ( @obsoletes ) {
			next if ( "$p" eq "(none)" );	
			$upgrade |= rpm_is_installed($p, $mode);
			if ($upgrade) {
				last;
			}
		}
	}

	if( $Uoption || $upgrade ) {	
		# -U option will only update this exact package and architecture
		# when multiple architectures are installed, other architecture rpms
		# are not affected by -U, however --force is needed in that case
		# also need --force for reinstall case
		LogPrint "  $chrootcmd$RPM -U --force $options $rpmfile\n";
		$out=`$chrootcmd$RPM -U --force $options $rpmfile 2>&1`;
		NormalPrint("$out");
	} else {
		# initial install of rpm
		# force not required, even if other architectures already installed
		if ("$ARCH" eq 'PPC64') {
			# PPC64 SLES10 needs --force
			$options='--force '."$options";
		}
		LogPrint "  $chrootcmd$RPM -i $options $rpmfile\n";
		$out=`$chrootcmd$RPM -i $options $rpmfile 2>&1`;
		NormalPrint("$out");
	}
	if (ROOT_is_set()) {
		system("rm -f $ROOT/var/tmp/rpminstall.tmp.rpm");
	}
}

# returns 0 on sucess (or package not installed), != 0 on failure
# uninstalls all variations of given package
# based on distro/cpu and mode, -32bit and -64bit variations may be included
sub rpm_uninstall($$$$)
{
	my($package) = shift();	# package name
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed
	my($options) = shift();	# additional rpm command options
	my($verbosity) = shift();	# verbose or silent
	my @fullnames = rpms_variations_installed_pkg($package, $mode); # already adjusts mode
	my $rc = 0;
	foreach my $fullname (@fullnames) {
		if ( "$verbosity" ne "silent" ) {
			print "uninstalling ${fullname}...\n";
		}
		LogPrint "chroot /$ROOT $RPM -e $options $fullname\n";
		my $out=`chroot /$ROOT $RPM -e $options $fullname 2>&1`;
		$rc |= $?;
		NormalPrint("$out");
	}
	return $rc;
}

# resolve rpm package filename within $rpmdir for $mode
sub rpm_resolve($$$)
{
	my $rpmdir = shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- any variation found (32 or 64 bit)
	my $package = shift();	# package name
	my $rpmfile;
	my $cpu;

	( $mode, $cpu ) = rpm_adjust_mode_cpu($package, $mode);
	if ("$mode" eq "user32") {
		return "" if ("$target_cpu32" eq "" );
		# we expect 0-1 match, ignore all other filenames returned
		DebugPrint("Checking for User Rpm: $rpmdir/${package}-[0-9]*.${cpu}.rpm\n");
		$rpmfile = file_glob("$rpmdir/${package}-[0-9]*.${cpu}.rpm");
		if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
			DebugPrint("Checking for User Rpm: $rpmdir/${package}-r[0-9]*.${cpu}.rpm\n");
			$rpmfile = file_glob("$rpmdir/${package}-r[0-9]*.${cpu}.rpm");
		}
		if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
			DebugPrint("Checking for User Rpm: $rpmdir/${package}-trunk-[0-9]*.${cpu}.rpm\n");
			$rpmfile = file_glob("$rpmdir/${package}-trunk-[0-9]*.${cpu}.rpm");
		}
	} elsif ("$mode" eq "user" ) {
		# we expect 0-1 match, ignore all other filenames returned
		DebugPrint("Checking for User Rpm: $rpmdir/${package}-[0-9]*.${cpu}.rpm\n");
		$rpmfile = file_glob("$rpmdir/${package}-[0-9]*.${cpu}.rpm");
		if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
			DebugPrint("Checking for User Rpm: $rpmdir/${package}-r[0-9]*.${cpu}.rpm\n");
			$rpmfile = file_glob("$rpmdir/${package}-r[0-9]*.${cpu}.rpm");
		}
		if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
			DebugPrint("Checking for User Rpm: $rpmdir/${package}-trunk-[0-9]*.${cpu}.rpm\n");
			$rpmfile = file_glob("$rpmdir/${package}-trunk-[0-9]*.${cpu}.rpm");
		}
		if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
			# we expect 0-1 match, ignore all other filenames returned
			DebugPrint("Checking for User Rpm: $rpmdir/${package}-[0-9]*.noarch.rpm\n");
			$rpmfile = file_glob("$rpmdir/${package}-[0-9]*.noarch.rpm");
			if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
				DebugPrint("Checking for User Rpm: $rpmdir/${package}-r[0-9]*.noarch.rpm\n");
				$rpmfile = file_glob("$rpmdir/${package}-r[0-9]*.noarch.rpm");
			}
			if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
				DebugPrint("Checking for User Rpm: $rpmdir/${package}-trunk-[0-9]*.noarch.rpm\n");
				$rpmfile = file_glob("$rpmdir/${package}-trunk-[0-9]*.noarch.rpm");
			}
		}
	} elsif ("$mode" eq "any" ) {
		# we expect 0-1 match, ignore all other filenames returned
		DebugPrint("Checking for User Rpm: $rpmdir/${package}-[0-9]*.*.rpm\n");
		$rpmfile = file_glob("$rpmdir/${package}-[0-9]*.*.rpm");
		if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
			DebugPrint("Checking for User Rpm: $rpmdir/${package}-r[0-9]*.*.rpm\n");
			$rpmfile = file_glob("$rpmdir/${package}-r[0-9]*.*.rpm");
		}
		if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
			DebugPrint("Checking for User Rpm: $rpmdir/${package}-trunk-[0-9]*.*.rpm\n");
			$rpmfile = file_glob("$rpmdir/${package}-trunk-[0-9]*.*.rpm");
		}
	} else {
		my $osver = rpm_tr_os_version("$mode");	# OS version
		# we expect 1 match, ignore all other filenames returned
		DebugPrint("Checking for Kernel Rpm: $rpmdir/${package}-[0-9]*-${osver}.${cpu}.rpm\n");
		$rpmfile = file_glob("$rpmdir/${package}-[0-9]*-${osver}.${cpu}.rpm");
		if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
			DebugPrint("Checking for Kernel Rpm: $rpmdir/${package}-r[0-9]*-${osver}.${cpu}.rpm\n");
			$rpmfile = file_glob("$rpmdir/${package}-r[0-9]*-${osver}.${cpu}.rpm");
		}
		if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
			DebugPrint("Checking for Kernel Rpm: $rpmdir/${package}-trunk-[0-9]*-${osver}.${cpu}.rpm\n");
			$rpmfile = file_glob("$rpmdir/${package}-trunk-[0-9]*-${osver}.${cpu}.rpm");
		}
	}
	VerbosePrint("Resolved $package $mode: $rpmfile\n");
	return $rpmfile;
}

sub rpm_exists($$$)
{
	my $rpmdir = shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- any variation found (32 or 64 bit)
	my $package = shift();	# package name
	my $rpmfile;

	$rpmfile = rpm_resolve($rpmdir, $mode, $package);
	return ("$rpmfile" ne "" && -e "$rpmfile");
}

sub rpm_install($$$)
{
	my $rpmdir = shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- will install any variation found (32 or 64 bit)
	my $package = shift();	# package name
	my $rpmfile;

	$rpmfile = rpm_resolve($rpmdir, $mode, $package);
	if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
		NormalPrint "Not Found: $package $mode\n";
	} else {
		if ("$mode" eq "user32" || "$mode" eq "user" || "$mode" eq "any" ) {
			rpm_run_install($rpmfile, $mode, "");
		} else {
			# kernel install
			if ("$CUR_DISTRO_VENDOR" eq 'SuSE') {
				# ofed1.3 only uses --nodeps on SuSE to workaround ksym
				# dependencies.
				rpm_run_install($rpmfile, $mode, "--nodeps");
			} else {
				rpm_run_install($rpmfile, $mode, "");
			}
		}
	}
}

sub rpm_install_with_options($$$$)
{
	my $rpmdir = shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- will install any variation found (32 or 64 bit)
	my $package = shift();	# package name
	my($options) = shift();	# additional rpm command options
	my $rpmfile;

	$rpmfile = rpm_resolve($rpmdir, $mode, $package);
	if ( "$rpmfile" eq "" || ! -e "$rpmfile" ) {
		NormalPrint "Not Found: $package $mode\n";
	} else {
		if ("$mode" eq "user32" || "$mode" eq "user" || "$mode" eq "any" ) {
			rpm_run_install($rpmfile, $mode, $options);
		} else {
			# kernel install
			if ("$CUR_DISTRO_VENDOR" eq 'SuSE') {
				# ofed1.3 only uses --nodeps on SuSE to workaround ksym
				# dependencies.
				rpm_run_install($rpmfile, $mode, "--nodeps $options");
			} else {
				rpm_run_install($rpmfile, $mode, $options);
			}
		}
	}
}

# verify the rpmfiles exist for all the RPMs listed
sub rpm_exists_list($$@)
{
	my $rpmdir = shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- any variation found (32 or 64 bit)
	my(@package_list) = @_;	# package names

	foreach my $package ( @package_list )
	{
		if (! rpm_exists($rpmdir, $mode, $package) ) {
			return 0;
		}
	}
	return 1;
}

sub rpm_install_list($$@)
{
	my $rpmdir = shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- will install any variation found (32 or 64 bit)
	my(@package_list) = @_;	# package names

	foreach my $package ( @package_list )
	{
		rpm_install($rpmdir, $mode, $package);
	}
}

sub rpm_install_list_with_options($$$@)
{
	my $rpmdir = shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- will install any variation found (32 or 64 bit)
	my($options) = shift();	# additional rpm command options
	my(@package_list) = @_;	# package names

	foreach my $package ( @package_list )
	{
		rpm_install_with_options($rpmdir, $mode, $options, $package);
	}
}

# returns 0 on success (or rpms not installed), != 0 on failure
sub rpm_uninstall_list2($$$@)
{
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed
	my($options) = shift();	# additional rpm command options
	my($verbosity) = shift();	# verbose or silent
	my(@package_list) = @_;	# package names
	my $package;
	my $ret = 0;	# assume success

	foreach $package ( reverse(@package_list) )
	{
		$ret |= rpm_uninstall($package, $mode, $options, $verbosity);
	}
	return $ret;
}

# returns 0 on success (or rpms not installed), != 0 on failure
sub rpm_uninstall_list($$@)
{
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed
	my($verbosity) = shift();	# verbose or silent
	my(@package_list) = @_;	# package names

	return rpm_uninstall_list2($mode, "", $verbosity, (@package_list));
}


# uninstall all rpms which match any of the supplied package names
# and based on mode and distro/cpu, also remove -32bit and -64bit variations
# uninstall is done in a single command so dependency issues handled
# returns 0 on success (or rpms not installed), != 0 on failure
sub rpm_uninstall_all_list($$@)
{
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed
	my($verbosity) = shift();	# verbose or silent
	my(@package_list) = @_;	# package names
	my @uninstall = ();
	my $options = "";

	if ("$mode" eq "any") {
		$options = "--allmatches";
	}
	foreach my $package ( @package_list )
	{
		foreach my $p ( rpm_variations($package, $mode) )
		{
			if (rpm_is_installed($p, $mode)) {
				if ("$mode" eq "any") {
					@uninstall = (@uninstall, $p);
				} else {
					@uninstall = (@uninstall, rpms_installed_pkg($p, $mode));
				}
			}
		}
	}
	
	if (scalar(@uninstall) != 0) {
		LogPrint "chroot /$ROOT $RPM -e $options @uninstall\n";
		my $out=`chroot /$ROOT $RPM -e $options @uninstall 2>&1`;
		my $rc=$?;
		NormalPrint("$out");
		return $rc;
	} else {
		LogPrint "None Found\n";
		return 0;	# nothing to do
	}
}

# see if prereqs for building kernel modules are installed
# return 0 on success, 1 if missing dependencies
sub check_kbuild_dependencies($$)
{
	my $osver = shift();	# kernel rev
	my $srpm = shift();	# what trying to build
	my $dir = "/lib/modules/$osver/build";

	if ( ! $rpm_check_dependencies ) {
		return 0;
	}
	if ( ! -d "$dir/scripts" ) {
		NormalPrint "Unable to build $srpm: $dir/scripts: not found\n";
		NormalPrint "kernel-source or kernel-devel is required to build $srpm\n";
		return 1;	# failure
	}
	return 0;
}

# see if basic prereqs for building RPMs are installed
# return 0 on success, or number of missing dependencies
sub check_rpmbuild_dependencies($)
{
	my $srpm = shift();	# what trying to build
	my $err = 0;

	if ("$CUR_DISTRO_VENDOR" eq 'redhat') {
		if (! rpm_is_installed("rpm-build", "any") ) {
			NormalPrint("rpm-build ($last_checked) is required to build $srpm\n");
			$err++;
		}
	}
	if ( "$CUR_DISTRO_VENDOR" ne "SuSE" && rpm_will_build_debuginfo()) {
		if (! rpm_is_installed("redhat-rpm-config", "any")) {
			NormalPrint("redhat-rpm-config ($last_checked) is required to build $srpm\n");
			$err++;
		}
	}
	return $err;
}

# see if basic prereqs for building are installed
# return 0 on success, or number of missing dependencies
sub check_build_dependencies($)
{
	my $build_info = shift();	# what trying to build
	my $err = 0;

	$err = rpm_check_build_os_prereqs('user', $build_info, ('glibc-devel'));
	return $err;
}

# see if basic prereqs for building 32 bit are installed
# return 0 on success, or number of missing dependencies
sub check_build32_dependencies($)
{
	my $build_info = shift();	# what trying to build
	my $err = 0;

	if ("$CUR_DISTRO_VENDOR" eq 'SuSE' && "$CUR_VENDOR_VER" eq "ES11" ) {
		$err = rpm_check_build_os_prereqs('user32', $build_info, ('gcc', 'glibc-devel'));
	} else {
		$err = rpm_check_build_os_prereqs('user32', $build_info, ('glibc-devel'));
	}
	return $err;
}
#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# =============================================================================
# The functions and constants below assist in doing builds such as via rpmbuild

# The functions below assume a hash of build options.  A sample is shown below
#my %ofed_kernel_ib_options = (
#	# build option		# arch & kernels supported on
#	"--with-core-mod" => "",	# supported on all
#	"--with-ehca-mod" => "PPC 2\.6\.1[6-9].* 2\.6\.20.* 2\.6\.9-55\.
#							PPC64 2\.6\.1[6-9].* 2\.6\.20.* 2\.6\.9-55\.",
#	"--with-iser-mod" => "ALL 2\.6\.16\..*-.*-.* 2\.6\..*\.el5 2\.6\.9-[3-5].*\.EL.*",
#		# all kernels except 2.6.5*  note .* wildcard need as 2nd kernelpat
#	"--with-rds-mod" => "ALL !2\.6\.5.* .*",
#	"--without-ipoibconf" => "NONE",	# essentially a comment
#			# DAPL not supported for PPC64
#	"--with-dapl" => "!PPC64",	# any kernel for !PPC64
#);

# The arch & kernels specification is quite flexible.
#
# special formats:
# 		"" -> always use option (any arch, any kernels)
# 		"NONE" -> never use option, no remaining lines are processed
#
# typical format is one line per arch, separated by newline (inside string):
# 		"arch1 kernelpat1 kernelpat2
#			arch2 kernelpat3"
# leading spaces and tabs ignored before arch
#
# arch format:
#	exact ARCH value (IA32, PPC, X86_64, etc)
#	ALL - remainder of line applies to all architectures
#			if no matches for kernel are found on this line, continues to later
#			lines
#	!arch - remainder of line applies to all architectures except arch
#			if no matches for kernel are found on this line, continues to later
#			lines.  If no kernels listed, applies to any kernel.
#	if for a given arch line, no kernels are specified, it matches any kernels
#
# kernelpat format:
#	"" -> (eg. no kernelpat specified for arch), option applies to any kernel
#			for given arch
#	 - all patterns are regex style
#		beware: . is a wildcard unless \. used
#	- !kernelpat means not on kernel, unlike !arch this indicates option is
#		not appliable to this specific kernel, but does not affect other kernels

# process osver and $ARCH against the list of allowed kernel/arch for
# a given build option to decide if option allowed for given kernel/arch
sub arch_kernel_is_allowed($$)
{
	my $osver = shift();
	my $archs = shift();

	if ( "$archs" eq "" ) {
		# option applicable to all archs all kernels
		DebugPrint "yes\n";
		return 1;
	} else {
		# newlines separate details of each arch
		my @arch_list = split /\n/, $archs;
		foreach my $archdetails ( @arch_list ) {
			# spaces separate arch and each kernelpattern
			# ignore leading and trailing tabs/spaces
			$archdetails =~ s/^[ 	]*//;	# remove leading
			$archdetails =~ s/[ 	]*$//;	# remove trailing
			# all other whitespace is just separators
			my @archkernels = split /[[:space:]]+/,$archdetails;
			# arch is 1st, rest are kernelpatterns
			my $arch = $archkernels[0];
			shift @archkernels;
			if ( "$arch" eq "NONE" ) {
				DebugPrint "no\n";
				return 0;
			} elsif ( "$ARCH" eq "$arch" || "ALL" eq "$arch"
				|| (substr($arch,0,1) eq "!" && "$ARCH" ne substr($arch,1)) ) {
				if (scalar(@archkernels) == 0) {
					# option applicable to all kernels for arch
					DebugPrint "yes\n";;
					return 1;
				} else {
					# list of kernel patterns specified
					foreach my $kernelpattern ( @archkernels ) {
#print "check $kernelpattern\n";
						if (substr($kernelpattern,0,1) eq "!") {
							$kernelpattern = substr($kernelpattern, 1);
							if ( $osver =~ /^$kernelpattern$/ ) {
								# option not available on this kernel
								DebugPrint "no\n";
								return 0;
							}
						} elsif ( $osver =~ /^$kernelpattern$/ ) {
							# option applicable to this kernel for arch
							DebugPrint "yes\n";
							return 1;
						}
					}
				}
			}
		}
	}
	DebugPrint "no\n";
	return 0;	# not specified
}

# given a build option and a kernel, decide if applicable to ARCH and kernel
# based on lookup in build_options hash
sub build_option_is_allowed($$@)
{
	my $osver = shift();
	my $build_option = shift();
	my(%build_options) = @_;	# list of options and when valid

	return arch_kernel_is_allowed($osver, $build_options{$build_option});
}

# based on $osver and $ARCH decide what build options to use
sub get_build_options($@)
{
	my $osver = shift();
	my(@build_options) = @_;	# list of options and when valid

	my $ret = "";
	my $i;
	for($i=0; $i < scalar(@build_options); $i += 2) {
		my $option = $build_options[$i];
		my $archs = $build_options[$i+1];
		if (arch_kernel_is_allowed($osver, $archs)) {
			DebugPrint "Check $option - yes\n";
			$ret="$ret $option";
		} else {
			DebugPrint "Check $option - no\n";
		}
	}
	return "$ret";
}

# execute build_cmd within srcdir
# note builds are done on local image not in $ROOT
# return 0 on success, != 0 on failure
sub run_build($$$$)
{
	my $message= shift();	# message for building output
	my $srcdir= shift();
	my $build_cmd= shift();
	my $resfileop= shift();	# "append" or "replace"

	my $rc;
	my $shfileop;
	
	if ( "$resfileop" eq "append" ) {
		$shfileop = ">>";
	} else {
		$shfileop = ">";
	}

	NormalPrint "Building $message...";

	LogPrint "\n  cd $srcdir; $build_cmd $shfileop build.res 2>&1\n";
	$rc=system "cd $srcdir; $build_cmd $shfileop build.res 2>&1";
	if ( $rc != 0 ) {
		NormalPrint "\nERROR - FAILED to build $message, see $srcdir/build.res\n";
		# TBD system("cat $srcdir/build.res >> $LogFile");
	} else {
		NormalPrint " done\n";
	}
	return $rc;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

#

#++
# "This software program is available to you under a choice of one of two 
# licenses.  You may choose to be licensed under either the GNU General Public 
# License (GPL) Version 2, June 1991, available at 
# http://www.fsf.org/copyleft/gpl.html, or the Intel BSD + Patent License, 
# the text of which follows:
# 
# "Recipient" has requested a license and Intel Corporation ("Intel") is willing
# to grant a license for the software entitled InfiniBand(tm) System Software 
# (the "Software") being provided by Intel Corporation.

# The following definitions apply to this License: 

# "Licensed Patents" means patent claims licensable by Intel Corporation which 
# are necessarily infringed by the use or sale of the Software alone or when 
# combined with the operating system referred to below.

# "Recipient" means the party to whom Intel delivers this Software.
# "Licensee" means Recipient and those third parties that receive a license to 
# any operating system available under the GNU Public License version 2.0 or 
# later.

# Copyright (c) 1996-2002 Intel Corporation. All rights reserved. 

# The license is provided to Recipient and Recipient's Licensees under the 
# following terms.  

# Redistribution and use in source and binary forms of the Software, with or 
# without modification, are permitted provided that the following conditions are 
# met: 
# Redistributions of source code of the Software may retain the above copyright 
# notice, this list of conditions and the following disclaimer. 

# Redistributions in binary form of the Software may reproduce the above 
# copyright notice, this list of conditions and the following disclaimer in the 
# documentation and/or other materials provided with the distribution. 

# Neither the name of Intel Corporation nor the names of its contributors shall 
# be used to endorse or promote products derived from this Software without 
# specific prior written permission.

# Intel hereby grants Recipient and Licensees a non-exclusive, worldwide, 
# royalty-free patent license under Licensed Patents to make, use, sell, offer 
# to sell, import and otherwise transfer the Software, if any, in source code 
# and object code form. This license shall include changes to the Software that 
# are error corrections or other minor changes to the Software that do not add 
# functionality or features when the Software is incorporated in any version of 
# a operating system that has been distributed under the GNU General Public 
# License 2.0 or later.  This patent license shall apply to the combination of 
# the Software and any operating system licensed under the GNU Public License 
# version 2.0 or later if, at the time Intel provides the Software to Recipient, 
# such addition of the Software to the then publicly available versions of such 
# operating system available under the GNU Public License version 2.0 or later 
# (whether in gold, beta or alpha form) causes such combination to be covered by 
# the Licensed Patents. The patent license shall not apply to any other 
# combinations which include the Software. No hardware per se is licensed 
# hereunder. 

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY 
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
#--
#
#
use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# Handle OpenIB stack which comes with distro or from OFED

sub disable_openib_ipoib
{
	my $changed = 0;
	my $file = $_[0];
	if (substr($CUR_OS_VER,0,3) eq "2.6" && -e "$file") {
		open (INPUT, "$file");
		open (OUTPUT, ">>$TMP_CONF");
		while (<INPUT>) {
			if (/^alias ib(\d) ib_ipoib/) {
				$_ = "#alias ib$1 ib_ipoib\n";
				$changed++;
			}
			print OUTPUT $_;
		}
		close(INPUT);
		close(OUTPUT);
		if ($changed) {
			system "mv $TMP_CONF $file";
		} else {
			system "rm -f $TMP_CONF";
		}
	}
}

sub disable_openib_stack
{
	my $changed = 0;
	if (substr($CUR_OS_VER,0,3) eq "2.6" && -e "$ROOT$MODULE_CONF_DIST_FILE") {
		open (INPUT, "$ROOT$MODULE_CONF_DIST_FILE");
		open (OUTPUT, ">>$TMP_CONF");
		while (<INPUT>) {
			if (/^install ib_core (.*)/) {
				$_ = "#install ib_core $1\n";
				$changed++;
			}
			print OUTPUT $_;
		}
		close(INPUT);
		close(OUTPUT);
		if ($changed) {
			system "mv $TMP_CONF $ROOT$MODULE_CONF_DIST_FILE";
		} else {
			system "rm -f $TMP_CONF";
		}
	}
	disable_autostart("openibd");
	disable_autostart("opensmd");
	disable_autostart("infinipath");
	disable_openib_ipoib("$ROOT$MODULE_CONF_DIST_FILE");
	disable_openib_ipoib("$ROOT$MODULE_CONF_FILE");
}

sub enable_openib_ipoib
{
	my $changed = 0;
	my $file = $_[0];
	if (substr($CUR_OS_VER,0,3) eq "2.6" && -e "$file") {
		open (INPUT, "$file");
		open (OUTPUT, ">>$TMP_CONF");
		while (<INPUT>) {
			if (/^#alias ib(\d) ib_ipoib/) {
				$_ = "alias ib$1 ib_ipoib\n";
				$changed++;
			}
			print OUTPUT $_;
		}
		close(INPUT);
		close(OUTPUT);
		if ($changed) {
			system "mv $TMP_CONF $file";
		} else {
			system "rm -f $TMP_CONF";
		}
	}
}

sub enable_openib_stack
{
	my $changed = 0;
	if (substr($CUR_OS_VER,0,3) eq "2.6" && -e "$ROOT$MODULE_CONF_DIST_FILE") {
		open (INPUT, "$ROOT$MODULE_CONF_DIST_FILE");
		open (OUTPUT, ">>$TMP_CONF");
		while (<INPUT>) {
			if (/^#install ib_core (.*)/) {
				$_ = "install ib_core $1\n";
				$changed++;
			}
			print OUTPUT $_;
		}
		close(INPUT);
		close(OUTPUT);
		if ($changed) {
			system "mv $TMP_CONF $ROOT$MODULE_CONF_DIST_FILE";
		} else {
			system "rm -f $TMP_CONF";
		}
	}
	enable_autostart("openibd");
	enable_autostart("opensmd");
	enable_autostart("infinipath");
	enable_openib_ipoib("$ROOT$MODULE_CONF_DIST_FILE");
	enable_openib_ipoib("$ROOT$MODULE_CONF_FILE");
}

# ==========================================================================
# IB Stack installation

sub remove_uvpconf
{
	# unconditionally uninstall UVP, we only support our UVP drivers for now
	#remove_conf_file("UVP", "$UVP_CONF_FILE");
	system "rm -rf $ROOT$UVP_CONF_FILE";
}

sub install_uvpconf
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};

	# Check $BASE_DIR directory ...exist 
	check_config_dirs;

	# unconditionally install UVP, we only support our UVP drivers for now
	#install_conf_file("UVP", "$UVP_CONF_FILE", "$srcdir/config/$UVP_CONF_FILE_SOURCE");
	copy_data_file("$srcdir/config/$UVP_CONF_FILE_SOURCE", "$UVP_CONF_FILE");
}

sub vapi_mst
{    
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	my @sh_library_list = (
		     "libcm_kmod"
		     ,"libhhul"
		     ,"libi2c_syscall"
		     ,"libmosal"
		     ,"libmpga"
		     ,"libmtl_common"
		     ,"libvapi_common"
		     ,"libvapi" );
		     # "libcm"
		     #,"libib_mgt"

	my @debug_sh_library_list = (
		      "libmtgetopt");

	my @module_list = ( 
		      "mst" );

	my @debug_module_list = ( 
		      "mod_hh"
		     ,"mod_ib_mgt"
		     ,"mod_mpga"
		     ,"mod_thh"
		     ,"mod_thhul"
		     ,"mod_vapi_common"
		     ,"mod_vapi"
		     ,"mod_vipkl"
		     ,"mosal"
		     ,"calib_driver"
		     ,"mosal_calib"
		     ,"mosal_ds_i2c"
		     ,"mod_i2c"
		     ,"ezusb2131"
		     ,"memtrack"
		     ,"mst_calbr" );

			 #,"dta_client"
			 #,"dta_server"
	my @binary_list = (  
		      "infiniburn"
		     ,"logset"
		     ,"ih_limit_max_rd.sh"
		     ,"sw_chipset_upgrade.sh"
			 ,"mstfwupdate"
		     ,"minit"
		     ,"mread"
		     ,"mreset"
			 ,"mstmkdev"
			 ,"mstvpd"
		     ,"mstop"
		     ,"mwrite"
		     ,"mdevices"
		     ,"open_hcas"
		     ,"perf_main"
		     ,"vstat");


	my @debug_binary_list = (  
		      "vapi"
		     ,"mtfunc"
		     ,"infinivision"
		     ,"infinivision-bin"
		     ,"infinivisionEx"
		     ,"itrace"
			 ,"mtserver"
			 ,"mremote"
		     ,"mst" );


	my $doUninstall = ($_[0] eq "uninstall"?1:0);    
	my $binary;
	my $module;
	my $library;

	foreach $library (@sh_library_list)
	{
		remove_oldshlib("$OLD_LIB_DIR/$library");
		if ($doUninstall)
		{
			remove_shlib("$LIB_DIR/$library");
		} else {
			copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/$library", "$LIB_DIR/$library", "0.0");
		}
	}
	foreach $library (@debug_sh_library_list)
	{
		remove_oldshlib("$OLD_LIB_DIR/$library");
		if ($doUninstall)
		{
			remove_shlib("$LIB_DIR/$library");
		} else {
	    	if ( "$DBG_FREE" eq "debug" )
	    	{
				copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/$library", "$LIB_DIR/$library", "0.0");
	    	}
		}
	}
	foreach $module (@module_list)
	{
		if ($doUninstall)
		{
	    	remove_driver($module,$driver_subdir, "silent");
		} else {
	    	copy_driver($module, $driver_subdir, "silent");
		}
	}
	foreach $module (@debug_module_list)
	{
		if ($doUninstall)
		{
			# always uninstall
	    	remove_driver($module,$driver_subdir, "silent");
		} else {
			# only install for debug
			if ( "$DBG_FREE" eq "debug" )
			{
	    		copy_driver($module, $driver_subdir, "silent");
			}
		}
	}
	foreach $binary (@binary_list)
	{
		if ($doUninstall)
		{
	    	system "rm -f $ROOT/sbin/$binary";
		} else {
	    	if ( "-e $srcdir/bin/$binary" )
	    	{
				copy_systool_file("$srcdir/bin/$binary", "/sbin/$binary");
	    	}
		}
	}
	foreach $binary (@debug_binary_list)
	{
		if ($doUninstall)
		{
			# always uninstall
	    	system "rm -f $ROOT/sbin/$binary";
		} else {
			# only install for debug
	    	if ( "$DBG_FREE" eq "debug" )
	    	{
				copy_systool_file("$srcdir/bin/$binary", "/sbin/$binary");
	    	}
		}
	}
}

sub vapi_dev
{    
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	my $library;
	my $doUninstall = ($_[0] eq "uninstall"?1:0);    

	my @ar_library_list = (
		     "libcm_kmod.a"
		     ,"libhhul.a"
		     ,"libi2c_syscall.a"
		     ,"libioctl_unwrap_kl.a"
		     ,"libmosal.a"
		     ,"libmpga.a"
		     ,"libmtcr.a"
		     ,"libmtl_common.a"
		     ,"libmtl_common_kl.a"
		     ,"libvapi.a"
		     ,"libvapi_common.a");
		     # "libcm.a"
		     #,"libib_mgt.a"

	my @debug_ar_library_list = (
		      "libmtgetopt.a");

	foreach $library (@ar_library_list)
	{
		remove_oldarlib("$OLD_LIB_DIR/$library");
		if ($doUninstall)
		{
	    	system "rm -f $ROOT$LIB_DIR/$library";
		} else {
			copy_arlib_file("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/$library", "$LIB_DIR/$library");
	    }
	}
	foreach $library (@debug_ar_library_list)
	{
		remove_oldarlib("$OLD_LIB_DIR/$library");
		if ($doUninstall)
		{
	    	system "rm -f $ROOT$LIB_DIR/$library";
		} elsif ( "$DBG_FREE" eq "debug" )
	    {
			copy_arlib_file("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/$library", "$LIB_DIR/$library");
	    }
	}
	if ($doUninstall) {
		system "rm -rf $ROOT/usr/include/iba/vapi";
		system "rmdir $ROOT/usr/include/iba 2>/dev/null";	# remove only if empty
		system "rm -f $ROOT/opt/iba/vapi/include";
		system "rmdir $ROOT/opt/iba/vapi 2>/dev/null";	# remove only if empty
		system "rmdir $ROOT/opt/iba 2>/dev/null";	# remove only if empty
		if ( ! $Skip_UsrLocalSymLinks ) {
			system "rm -f $ROOT/usr/local/vapi/include";
			system "rmdir $ROOT/usr/local/vapi 2>/dev/null";	# remove only if empty
		}
	} else {
		# Copy all vapi include files
		check_dir("/usr/include/iba");
		# Remove old vapi header file
		if( -d "$ROOT/usr/include/iba/vapi")
		{
			system "rm -rf $ROOT/usr/include/iba/vapi";
		}
		check_dir("/usr/include/iba/vapi");
		copy_all_data_files("$srcdir/include/vapi", "/usr/include/iba/vapi", "");
		# fix possible directory permissions problem from previous install
		system "chmod ugo=rx,u=rwx $ROOT/usr/include/iba/vapi/sys";
		check_dir("/opt/iba/vapi");
		system "rm -f $ROOT/opt/iba/vapi/include";
		system "ln -s /usr/include/iba/vapi $ROOT/opt/iba/vapi/include";
		if ( ! $Skip_UsrLocalSymLinks ) {
			check_dir("/usr/local/vapi");
			symlink_usrlocal("/usr/include/iba/vapi", "/usr/local/vapi/include");
		}
	}
}

# autostart functions are per subcomponent
sub IsAutostart2_iba()
{
	return IsAutostart("iba");
}
sub autostart_desc_iba()
{
	return "$ComponentInfo{'iba'}{'Name'} (iba)";
}
sub enable_autostart2_iba()
{
	enable_autostart("iba");
}
sub disable_autostart2_iba()
{
	disable_autostart("iba");
}
sub IsAutostart2_iba_mon()
{
	return IsAutostart("iba_mon");
}
sub autostart_desc_iba()
{
	return "$ComponentInfo{'iba_mon'}{'Name'} (iba_mon)";
}
sub enable_autostart2_iba_mon()
{
	enable_autostart("iba_mon");
}
sub disable_autostart2_iba_mon()
{
	disable_autostart("iba_mon");
}

sub start_iba
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	start_driver($ComponentInfo{'iba'}{'Info'}, "ibt", $driver_subdir, 'iba');
	if (IsModuleLoaded("ibt") == 1)  {
		start_utility($ComponentInfo{'iba_mon'}{'Name'}, "/sbin", "iba_mon", "iba_mon");
	}
}

sub stop_iba
{
	stop_utility($ComponentInfo{'iba_mon'}{'Name'}, "iba_mon", "iba_mon");
	stop_driver($ComponentInfo{'iba'}{'Info'}, "ibt", 'iba');
}

# Make $BASE_DIR directory and copy busdrv.conf file.
sub add_busdrvconf
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	#printf("Copying busdrv.conf file to $BASE_DIR...\n");

	# Check $BASE_DIR directory ...exist 
	check_config_dirs;

	copy_data_file("$srcdir/config/busdrv.conf", "$BASE_DIR/busdrv.conf");
	copy_data_file("$srcdir/config/BusDrvReadMe", "$BASE_DIR/BusDrvReadMe");
}

# detect if iPath software is installed
sub installed_ipath
{
	return (-e "$ROOT$INIT_DIR/infinipath");
}

sub available_intelhca
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "82808XA");
}

sub installed_intelhca
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	return installed_driver("82808XA", $driver_subdir);
}

sub install_intelhca
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	if (! available_intelhca() ) {
		return;
	}
	copy_driver ("82808XA", $driver_subdir, "verbose");
	add_blacklist("82808XA");
	remove_oldshlib("$OLD_UVP_LIB_DIR/lib82808XA");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/lib82808XA", "$UVP_LIB_DIR/lib82808XA", "0.0");
	# Intel Firmware
	check_dir("$BASE_DIR/intel");
	copy_data_file("$srcdir/bin/ivxbsq.bin", "$BASE_DIR/intel/ivxbsq.bin");
	copy_data_file("$srcdir/bin/ivxbrq.bin", "$BASE_DIR/intel/ivxbrq.bin");
}

sub uninstall_intelhca
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	remove_driver ("82808XA", $driver_subdir, "verbose");
	remove_blacklist("82808XA");
	remove_shlib("$UVP_LIB_DIR/lib82808XA");
	remove_oldshlib("$OLD_UVP_LIB_DIR/lib82808XA");
	system("rm -rf $ROOT$BASE_DIR/intel/");
}

sub available_rwoodhca
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "rwoodvpd");
}

sub installed_rwoodhca
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	return installed_driver("rwoodvpd", $driver_subdir);
}

sub install_rwoodhca
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	if (! available_rwoodhca() ) {
		return;
	}
	copy_driver ("rwoodvpd", $driver_subdir, "verbose");
	add_blacklist("rwoodvpd");
	remove_oldshlib("$OLD_UVP_LIB_DIR/librwoodvpd");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/librwoodvpd", "$UVP_LIB_DIR/librwoodvpd", "0.0");
}

sub uninstall_rwoodhca
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	remove_driver ("rwoodvpd", $driver_subdir, "verbose");
	remove_blacklist("rwoodvpd");
	remove_shlib("$UVP_LIB_DIR/librwoodvpd");
	remove_oldshlib("$OLD_UVP_LIB_DIR/librwoodvpd");
}

sub available_vpdmux
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "vpdmux");
}

sub installed_vpdmux
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	return installed_driver("vpdmux", $driver_subdir);
}

sub install_vpdmux
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	if (! available_vpdmux() ) {
		return;
	}
	copy_driver ("vpdmux", $driver_subdir, "verbose");
	add_blacklist("vpdmux");
	#remove_oldshlib("$OLD_UVP_LIB_DIR/libvpdmux");
	#copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/libvpdmux", "$UVP_LIB_DIR/libvpdmux", "0.0");
}

sub uninstall_vpdmux
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	remove_driver ("vpdmux", $driver_subdir, "verbose");
	remove_blacklist("vpdmux");
	#remove_shlib("$UVP_LIB_DIR/libvpdmux");
	#remove_oldshlib("$OLD_UVP_LIB_DIR/libvpdmux");
}

sub available_tavorhca
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	return (available_driver("$srcdir/bin/$ARCH", "mt23108vpd")
			|| available_driver("$srcdir/bin/$ARCH", "mt25218vpd") );
}

sub installed_tavorhca
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	return installed_driver("mt23108vpd", $driver_subdir)
			 || installed_driver("mt25218vpd", $driver_subdir);
}

sub install_tavorhca
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	if (! available_tavorhca() ) {
		return;
	}
	copy_driver ("mt23108vpd", $driver_subdir, "verbose");
	add_blacklist("mt23108vpd");
	copy_driver ("mt25218vpd", $driver_subdir, "verbose");
	add_blacklist("mt25218vpd");
	# only install for debug
	if ( "$DBG_FREE" eq "debug" )
	{
		copy_driver("VapiVpd", $driver_subdir, "silent");
	}
	remove_oldshlib("$OLD_UVP_LIB_DIR/libmt23108vpd");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/libmt23108vpd", "$UVP_LIB_DIR/libmt23108vpd", "0.0");
	remove_oldshlib("$OLD_UVP_LIB_DIR/libmt25218vpd");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/libmt25218vpd", "$UVP_LIB_DIR/libmt25218vpd", "0.0");

	# CM and GSI shims from vapi API to IBA
		# "libcm"
		#,"libib_mgt"
	remove_oldshlib("$OLD_LIB_DIR/libcm");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/libcm", "$LIB_DIR/libcm", "0.0");
	remove_oldshlib("$OLD_LIB_DIR/libib_mgt");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/libib_mgt", "$LIB_DIR/libib_mgt", "0.0");

	# Firmware
	check_dir("$BASE_DIR/mt23108");
	check_dir("$BASE_DIR/mt25208");
	check_dir("$BASE_DIR/mt25218");
	check_dir("$BASE_DIR/mt25204");

	# production firmware for SilverStorm cards
	copy_firmware($srcdir, "InfiniServ.A0", "mt23108");
	copy_firmware($srcdir, "InfiniServ.A1", "mt23108");
	# production firmware for cougar and sanmina cards
	copy_firmware($srcdir, "InfiniServC.A1", "mt23108");
	copy_firmware($srcdir, "InfiniServS.A1", "mt23108");
	# production firmware for cougarcub
	copy_firmware($srcdir, "InfiniServCC.A1", "mt23108");
	# support Tavor Eval card (Jaguar) for partners
	copy_firmware($srcdir, "TavorEval.A0", "mt23108");
	copy_firmware($srcdir, "TavorEval.A1", "mt23108");
	copy_data_file("$srcdir/bin/README.mt23108", "$BASE_DIR/mt23108/README");

	# production firmware for Arbel Lion Cub
	copy_firmware($srcdir, "InfiniServEx.A0", "mt25208");
	copy_firmware($srcdir, "InfiniServExC.A0", "mt25208");
	copy_firmware($srcdir, "InfiniServEx_D.A0", "mt25208");
	copy_firmware($srcdir, "InfiniServEx_D.20", "mt25208");
	copy_firmware($srcdir, "InfiniServExA4_D.A0", "mt25208");
	copy_firmware($srcdir, "InfiniServExA4_D.20", "mt25208");
	copy_data_file("$srcdir/bin/README.mt25208", "$BASE_DIR/mt25208/README");

	# production firmware for Lion-Cub and/or Lion-Mini cards ( Arbel in memfree mode )
	copy_firmware($srcdir, "InfiniServLM.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLM_D.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLM_D.20", "mt25218");
	copy_firmware($srcdir, "InfiniServLMA3_D.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLMA3_D.20", "mt25218");
	copy_firmware($srcdir, "InfiniServLMA4_D.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLMA4_D.20", "mt25218");
	copy_firmware($srcdir, "InfiniServLC.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLC_MemFree.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLC_C.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLC_C_MemFree.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLC_D.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLC_D.20", "mt25218");
	copy_firmware($srcdir, "InfiniServLC_D_MemFree.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLC_D_MemFree.20", "mt25218");
	copy_firmware($srcdir, "InfiniServLCA4_D.A0", "mt25218");
	copy_firmware($srcdir, "InfiniServLCA4_D.20", "mt25218");
	copy_data_file("$srcdir/bin/README.mt25218", "$BASE_DIR/mt25218/README");

	# production firmware for Tiger and/or Cheetah card ( Sinai silicon )
	copy_firmware($srcdir, "InfiniServT.A0", "mt25204");
	copy_firmware($srcdir, "InfiniServCH.A0", "mt25204");
	copy_firmware($srcdir, "InfiniServCH_D.A0", "mt25204");
	copy_firmware($srcdir, "InfiniServCH_D.20", "mt25204");
	copy_data_file("$srcdir/bin/README.mt25204", "$BASE_DIR/mt25204/README");

	# standalone VAPI libraries
	vapi_mst("install");
}

sub uninstall_tavorhca
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	remove_driver ("mt23108vpd", $driver_subdir, "verbose");
	remove_blacklist("mt23108vpd");
	remove_driver ("mt25218vpd", $driver_subdir, "verbose");
	remove_blacklist("mt25218vpd");
	remove_driver ("VapiVpd", $driver_subdir, "verbose");
	remove_shlib("$LIB_DIR/libcm");
	remove_oldshlib("$OLD_LIB_DIR/libcm");
	remove_shlib("$LIB_DIR/libib_mgt");
	remove_oldshlib("$OLD_LIB_DIR/libib_mgt");
	remove_shlib("$UVP_LIB_DIR/libmt23108vpd");
	remove_oldshlib("$OLD_UVP_LIB_DIR/libmt23108vpd");
	remove_shlib("$UVP_LIB_DIR/libmt25218vpd");
	remove_oldshlib("$OLD_UVP_LIB_DIR/libmt25218vpd");
	system("rm -rf $ROOT$BASE_DIR/mt23108/");
	system("rm -rf $ROOT$BASE_DIR/mt25208/");
	system("rm -rf $ROOT$BASE_DIR/mt25218/");
	system("rm -rf $ROOT$BASE_DIR/mt25204/");
	vapi_mst("uninstall");
}
	
sub available_dta
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	return ( -e "$srcdir/bin/iba_dta_server" );
}

sub installed_dta
{
	return ( -e "/bin/iba_dta_server" || -e "/bin/ics_dta_server" );
}

sub install_dta
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	if (! available_dta() ) {
		return;
	}
	# DTA for Plugfest/CIWG
	check_dir("$CONFIG_DIR/dta");
	system("rm -f $ROOT/bin/ics_dta_client");
	system("rm -f $ROOT/bin/ics_dta_server");
	copy_bin_file("$srcdir/bin/iba_dta_client", "/bin/iba_dta_client");
	copy_bin_file("$srcdir/bin/iba_dta_server", "/bin/iba_dta_server");
	#install_conf_file("DTA", "$CONFIG_DIR/dta/pathrecdb.xml", "$srcdir/config/pathrecdb.xml");
	#install_conf_file("DTA", "$CONFIG_DIR/dta/clientconf.xml", "$srcdir/config/clientconf.xml");
	#install_conf_file("DTA", "$CONFIG_DIR/dta/interop.xml", "$srcdir/config/interop.xml");
	copy_data_file( "$srcdir/config/pathrecdb.xml", "$CONFIG_DIR/dta/pathrecdb.xml");
	copy_data_file( "$srcdir/config/clientconf.xml", "$CONFIG_DIR/dta/clientconf.xml");
	copy_data_file("$srcdir/config/interop.xml", "$CONFIG_DIR/dta/interop.xml");
	copy_data_file("$srcdir/config/DTA_README", "$CONFIG_DIR/dta/DTA_README");
}

sub uninstall_dta
{
	system("rm -rf $ROOT/bin/ics_dta_client");
	system("rm -rf $ROOT/bin/ics_dta_server");
	system("rm -rf $ROOT/bin/iba_dta_client");
	system("rm -rf $ROOT/bin/iba_dta_server");
	#remove_conf_file("DTA", "$CONFIG_DIR/dta/pathrecdb.xml");
	#remove_conf_file("DTA", "$CONFIG_DIR/dta/clientconf.xml");
	#remove_conf_file("DTA", "$CONFIG_DIR/dta/interop.xml");
	system("rm -rf $ROOT$CONFIG_DIR/dta/pathrecdb.xml");
	system("rm -rf $ROOT$CONFIG_DIR/dta/clientconf.xml");
	system("rm -rf $ROOT$CONFIG_DIR/dta/interop.xml");
	system("rm -rf $ROOT$CONFIG_DIR/dta/DTA_README");
	system "rmdir $ROOT$CONFIG_DIR/dta 2>/dev/null";
}

sub available_iba
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "ibt");
}

sub installed_iba
{
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	return installed_driver("ibt", $driver_subdir);
}

# only called if installed_iba is true
sub installed_version_iba
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_iba is true
sub media_version_iba
{
	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub installed_iba_mon
{
	return installed_iba;
}

sub uninstall_old_inic_and_srp_drivers
{
	my $d;
	my $deletedir;
	my $path;
	my @dirstodelete;

	# A list of old device drivers directories to delete.  It is very important we
	# delete these old device drivers, or we have conflicts attempting to run old
	# device drivers with new ones.  The algorithm below is case insensitive for
	# deleting all device driver's directories from all possible module paths.

	my @deletelist = ( "icsinic" , "icsdsc" , "icssrp" );

	foreach $path (@module_dirs)
	{   
		foreach $deletedir (@deletelist) 
		{
			opendir(DIR, "$ROOT$path");

			@dirstodelete = eval { grep {m/$deletedir/i} readdir(DIR); };

			foreach $d (@dirstodelete) 
			{
				if (-e "$ROOT$d") 
				{
					printf "Found old device driver $d. ";
					system "rm -rf $ROOT$d";
					printf "Deleted.\n";
				}
			}   
			closedir DIR;
		}
	}
}

sub installed_kdapl;
sub uninstall_kdapl;

sub build_iba
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_iba($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_iba
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_iba
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'iba'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};

	my $version=media_version_iba();
	chomp $version;
	printf("Installing $ComponentInfo{'iba'}{'Info'} $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'iba'}{'Info'} $version $DBG_FREE for $CUR_OS_VER\n";
	create_driver_dirs($driver_subdir);
	edit_modconf("$srcdir/config");
	edit_limitsconf("$srcdir/config");
	add_busdrvconf;

	# Check $BASE_DIR directory ...exist 
	check_config_dirs;
	if ( "$BASE_DIR" ne "$OLD_BASE_DIR" )
	{
		system("rm -rf $ROOT$OLD_BASE_DIR");
	}
	check_dir("/opt/iba/ib_tools");
	copy_systool_file("$srcdir/bin/iba_mon", "/sbin/iba_mon");
	copy_systool_file("$srcdir/bin/ics_capture", "/sbin/ics_capture");
	copy_systool_file("$srcdir/bin/ics_capture", "/sbin/iba_capture");
	copy_systool_file("$srcdir/bin/trivialsm", "/sbin/trivialsm");
	copy_systool_file("$srcdir/bin/iba_saquery", "/sbin/saquery");
	copy_systool_file("$srcdir/bin/iba_saquery", "/sbin/iba_saquery");
	copy_systool_file("$srcdir/bin/fabric_info", "/sbin/fabric_info");
	copy_systool_file("$srcdir/bin/iba_portenable", "/sbin/iba_portenable");
	copy_systool_file("$srcdir/bin/iba_portdisable", "/sbin/iba_portdisable");
	copy_systool_file("$srcdir/bin/iba_portconfig", "/sbin/iba_portconfig");
	copy_systool_file("$srcdir/bin/dsc_path", "/sbin/dsc_path");
	copy_systool_file("$srcdir/bin/iba_startup", "/sbin/iba_start");
	copy_systool_file("$srcdir/bin/iba_startup", "/sbin/iba_stop");
	copy_systool_file("$srcdir/bin/iba_startup", "/sbin/iba_restart");
	copy_systool_file("$srcdir/bin/iba_hca_rev", "/sbin/iba_hca_rev");
	copy_systool_file("$srcdir/bin/iba_showports", "/sbin/iba_showports");
	copy_systool_file("$srcdir/bin/p1info", "/sbin/p1info");
	copy_systool_file("$srcdir/bin/p1stats", "/sbin/p1stats");
	copy_systool_file("$srcdir/bin/clear_p1stats", "/sbin/clear_p1stats");
	copy_systool_file("$srcdir/bin/p2info", "/sbin/p2info");
	copy_systool_file("$srcdir/bin/p2stats", "/sbin/p2stats");
	copy_systool_file("$srcdir/bin/clear_p2stats", "/sbin/clear_p2stats");
	copy_systool_file("$srcdir/bin/hcastats", "/sbin/hcastats");
	copy_systool_file("$srcdir/bin/clear_hcastats", "/sbin/clear_hcastats");
	system("rm -rf $ROOT/sbin/iba_read_proc_fs");
	system("rm -rf $ROOT/sbin/iba_write_proc_fs");
	system("rm -rf $ROOT/sbin/iba_list_proc_fs");
	copy_systool_file("$srcdir/bin/iba_proc_read", "/sbin/iba_proc_read");
	copy_systool_file("$srcdir/bin/iba_proc_write", "/sbin/iba_proc_write");
	copy_systool_file("$srcdir/bin/iba_proc_list", "/sbin/iba_proc_list");
	system("rm -rf $ROOT/sbin/bsd_ping"); #old location
	copy_systool_file("$srcdir/bin/bsd_ping", "/opt/iba/ib_tools/bsd_ping");
	copy_systool_file("$srcdir/bin/rdsping", "/sbin/rdsping");
	#copy_file("$srcdir/bin/bsd_ping", "/bin/bsd_ping", "$OWNER", "$GROUP", "ugo=rx,u=rwxs");
	system("rm -rf $ROOT/sbin/iba_ipcalc"); #old location
	copy_systool_file("$srcdir/bin/iba_ipcalc", "/opt/iba/ib_tools/iba_ipcalc");
	copy_data_file("$srcdir/config/supported_kernels", "$BASE_DIR/supported_kernels");
	install_dta;

	copy_driver ("ibt", $driver_subdir, "verbose");
	copy_driver("ics_dsc", $driver_subdir, "verbose");
	# ibt_utilities no longer needed, remove from any prior install
	remove_driver("ibt_utilities", $driver_subdir, "silent");

	# prevent open IB from loading
	add_blacklist("ib_mthca");
	add_blacklist("ib_ipath");

	# HCA drivers
	install_intelhca;
	install_rwoodhca;
	install_tavorhca;
	install_vpdmux;

	remove_oldshlib("$OLD_LIB_DIR/libpublic");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/libpublic", "$LIB_DIR/libpublic", "0.0");
	remove_oldshlib("$OLD_LIB_DIR/libibt");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/libibt", "$LIB_DIR/libibt", "0.0");

	# we have moved where the old srp, and inic drivers located so check and remove them	
	uninstall_old_inic_and_srp_drivers; 
	# get rid of kdapl if present, not supported
	if ( installed_kdapl() )
	{
		uninstall_kdapl();
	}
	install_conf_file("$ComponentInfo{'iba_mon'}{'Name'}", "$IBA_CONFIG_DIR/iba_mon.conf", "$srcdir/config/iba_mon.conf");    
	install_uvpconf;
	install_startup("$srcdir/config", 'iba', "$ComponentInfo{'iba'}{'Info'}");
	install_startup("$srcdir/config", "iba_mon", "$ComponentInfo{'iba_mon'}{'Name'}");
	need_reboot();
	$ComponentWasInstalled{'iba'}=1;
	disable_openib_stack();
}

sub postinstall_iba
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_iba
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	my $driver_subdir=$ComponentInfo{'iba'}{'DriverSubdir'};
	NormalPrint("Uninstalling $ComponentInfo{'iba'}{'Info'}...\n");
	stop_iba;

	# HCA drivers
	uninstall_intelhca;
	uninstall_rwoodhca;
	uninstall_tavorhca;
	uninstall_vpdmux;

	# allow open IB to load
	remove_blacklist("ib_mthca");
	remove_blacklist("ib_ipath");

	remove_driver ("ibt", $driver_subdir, "verbose");
	remove_driver ("ics_dsc", $driver_subdir, "verbose");
	remove_driver("ibt_utilities", $driver_subdir, "verbose");
	remove_shlib("$LIB_DIR/libpublic");
	remove_oldshlib("$OLD_LIB_DIR/libpublic");
	remove_shlib("$LIB_DIR/libibt");
	remove_oldshlib("$OLD_LIB_DIR/libibt");
	uninstall_dta;
	remove_startup('iba');
	remove_startup("iba_mon");
	remove_conf_file("$ComponentInfo{'iba_mon'}{'Name'}", "$IBA_CONFIG_DIR/iba_mon.conf");
	remove_uvpconf;
	# we have moved where the old srp, and inic drivers located so check and remove them
	uninstall_old_inic_and_srp_drivers;
	# get rid of kdapl if present, not supported
	if ( installed_kdapl() )
	{
		uninstall_kdapl();
	}
	# some additional removes to purge SDK3 from system
	# presently driver directories are the same /lib/modules directory as SDK3
	remove_driver ("sms", $driver_subdir, "silent");
	remove_driver ("smpt", $driver_subdir, "silent");
	system "rm -rf $ROOT/usr/local/bin/ibsm";
	system "rm -rf $ROOT/etc/intel/iba";
	system "rm -rf $ROOT/usr/local/bin/sm";
	system "rmdir $ROOT/etc/intel/iba 2>/dev/null";
	del_marks ("Subnet Manager Dependencies Start", "Subnet Manager Dependencies End", 1, "$ROOT$MODULE_CONF_FILE");
	remove_startup("ibsm");

	system("rm -rf $ROOT/sbin/ics_capture");
	system("rm -rf $ROOT/sbin/iba_capture");
	system("rm -rf $ROOT/sbin/iba_mon");
	system("rm -rf $ROOT/sbin/trivialsm");
	system("rm -rf $ROOT/sbin/saquery");
	system("rm -rf $ROOT/sbin/iba_saquery");
	system("rm -rf $ROOT/sbin/fabric_info");
	system("rm -rf $ROOT/sbin/iba_portenable");
	system("rm -rf $ROOT/sbin/iba_portdisable");
	system("rm -rf $ROOT/sbin/iba_portconfig");
	system("rm -rf $ROOT/sbin/dsc_path");
	system("rm -rf $ROOT/sbin/iba_start");
	system("rm -rf $ROOT/sbin/iba_stop");
	system("rm -rf $ROOT/sbin/iba_restart");
	system("rm -rf $ROOT/sbin/iba_hca_rev");
	system("rm -rf $ROOT/sbin/iba_showports");
	system("rm -rf $ROOT/sbin/p1info");
	system("rm -rf $ROOT/sbin/p1stats");
	system("rm -rf $ROOT/sbin/clear_p1stats");
	system("rm -rf $ROOT/sbin/p2info");
	system("rm -rf $ROOT/sbin/p2stats");
	system("rm -rf $ROOT/sbin/clear_p2stats");
	system("rm -rf $ROOT/sbin/hcastats");
	system("rm -rf $ROOT/sbin/clear_hcastats");
	system("rm -rf $ROOT/sbin/iba_read_proc_fs");
	system("rm -rf $ROOT/sbin/iba_write_proc_fs");
	system("rm -rf $ROOT/sbin/iba_list_proc_fs");
	system("rm -rf $ROOT/sbin/iba_proc_read");
	system("rm -rf $ROOT/sbin/iba_proc_write");
	system("rm -rf $ROOT/sbin/iba_proc_list");
	system("rm -rf $ROOT/sbin/bsd_ping"); #old location
	system("rm -rf $ROOT/opt/iba/ib_tools/bsd_ping");
	system("rm -rf $ROOT/sbin/rdsping");
	system("rm -rf $ROOT/sbin/ipcalc.pl");
	system("rm -rf $ROOT/sbin/iba_ipcalc"); #old location
	system("rm -rf $ROOT/opt/iba/ib_tools/iba_ipcalc");
	system("rm -rf $ROOT$BASE_DIR/BusDrvReadMe");
	system("rm -rf $ROOT$BASE_DIR/busdrv.conf");
	system("rm -rf $ROOT$BASE_DIR/supported_kernels");
	remove_driver_dirs($driver_subdir);
	remove_modules_conf;
	remove_limits_conf;
	system "rmdir $ROOT$BASE_DIR 2>/dev/null";	# remove only if empty
	system "rmdir $ROOT$IBA_CONFIG_DIR 2>/dev/null";	# remove only if empty
	need_reboot();
	$ComponentWasInstalled{'iba'}=0;
	enable_openib_stack();
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# IB Development installation

sub available_ibdev
{
	my $srcdir=$ComponentInfo{'ibdev'}{'SrcDir'};
	return ( -d "$srcdir/include/iba" );
}

sub installed_ibdev
{
	return( -d "$ROOT/usr/include/iba" );
}

# only called if installed_ibdev is true
sub installed_version_ibdev
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_ibdev is true
sub media_version_ibdev
{
	my $srcdir=$ComponentInfo{'ibdev'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub build_ibdev
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ibdev($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_ibdev
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_ibdev
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'ibdev'}{'SrcDir'};

	my $version=media_version_ibdev();
	chomp $version;
	printf("Installing $ComponentInfo{'ibdev'}{'Name'} $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'ibdev'}{'Name'} $version $DBG_FREE for $CUR_OS_VER\n";
	remove_oldarlib("$OLD_LIB_DIR/libcm.a");
	copy_arlib_file("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/libcm.a", "$LIB_DIR/libcm.a");
	remove_oldarlib("$OLD_LIB_DIR/libib_mgt.a");
	copy_arlib_file("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/libib_mgt.a", "$LIB_DIR/libib_mgt.a");
	# Copy all iba include files
	check_dir("/usr/include/iba");
	check_dir("/usr/include/linux/iba");
	copy_all_data_files("$srcdir/include/iba", "/usr/include/iba", "");
	copy_all_data_files("$srcdir/include/linux/iba", "/usr/include/linux/iba", "");
	copy_data_file("$srcdir/include/dsc_export.h", "/usr/include/dsc_export.h");
	copy_data_file("$srcdir/include/ipoib_export.h", "/usr/include/ipoib_export.h");
	vapi_dev("install");
	# remove samples installed in old location
	remove_installed_files "/usr/local/src/iba_samples";
	# Copy all ib sample applications
	check_dir("/opt/iba/src");
	check_dir("/opt/iba/src/iba_samples");
	copy_all_data_files("$srcdir/iba_samples", "/opt/iba/src/iba_samples");
	system "cd $ROOT/opt/iba/src/iba_samples; find . -type d| while read dir; do mv \$dir/Makefile.sample \$dir/Makefile 2>/dev/null; done 2>/dev/null";
	system "cd $srcdir/iba_samples; find . | sed -e 's/Makefile.sample/Makefile/' > $ROOT/opt/iba/src/iba_samples/.files 2>/dev/null";
	system "cd $srcdir/iba_samples; find * -maxdepth 1 -type d > $ROOT/opt/iba/src/iba_samples/.dirs 2>/dev/null";
	$ComponentWasInstalled{'ibdev'}=1;
}

sub postinstall_ibdev
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_ibdev
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	NormalPrint("Uninstalling $ComponentInfo{'ibdev'}{'Name'}...\n");
	remove_oldarlib("$OLD_LIB_DIR/libcm.a");
	system "rm -rf $ROOT$LIB_DIR/libcm.a";
	remove_oldarlib("$OLD_LIB_DIR/libib_mgt.a");
	system "rm -rf $ROOT$LIB_DIR/libib_mgt.a";
	vapi_dev("uninstall");
	system "rm -rf $ROOT/usr/include/iba";
	system "rm -rf $ROOT/usr/include/linux/iba";
	system "rm -rf $ROOT/usr/include/dsc_export.h";
	system "rm -rf $ROOT/usr/include/ipoib_export.h";
	# remove iba_samples we installed or user compiled, however do not remove
	# any logs or other files the user may have created
	remove_installed_files "/opt/iba/src/iba_samples";
	system "rmdir $ROOT/opt/iba/src 2>/dev/null";
	system "rmdir $ROOT/opt/iba 2>/dev/null";
	remove_installed_files "/usr/local/src/iba_samples";
	$ComponentWasInstalled{'ibdev'}=0;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# IB Boot installation

sub available_ibboot
{
	my $srcdir=$ComponentInfo{'ibboot'}{'SrcDir'};
	return ( -e "$srcdir/Firmware/InfiniServCC.A1.release.boot" );
}

sub installed_ibboot
{
	return( -e "$ROOT/$BASE_DIR/mt23108/InfiniServCC.A1.boot.bin" );
}

# only called if installed_ibboot is true
sub installed_version_ibboot
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_ibboot is true
sub media_version_ibboot
{
	my $srcdir=$ComponentInfo{'ibboot'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub build_ibboot
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ibboot($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_ibboot
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_ibboot
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'ibboot'}{'SrcDir'};

	my $version=media_version_ibboot();
	chomp $version;
	printf("Installing $ComponentInfo{'ibboot'}{'Name'} $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'ibboot'}{'Name'} $version $DBG_FREE for $CUR_OS_VER\n";

	# only selected HCAs have IB Boot enabled firmware images
	# iba is a prereq so basic firmware files are already installed
	# production firmware for cougar 
	copy_boot_firmware($srcdir, "InfiniServC.A1", "mt23108");
	# production firmware for cougarcub
	copy_boot_firmware($srcdir, "InfiniServCC.A1", "mt23108");

	# production firmware for Arbel Lion Cub
	copy_boot_firmware($srcdir, "InfiniServEx.A0", "mt25208");
	copy_boot_firmware($srcdir, "InfiniServExC.A0", "mt25208");
	copy_boot_firmware($srcdir, "InfiniServEx_D.A0", "mt25208");
	copy_boot_firmware($srcdir, "InfiniServEx_D.20", "mt25208");

	$ComponentWasInstalled{'ibboot'}=1;
}

sub postinstall_ibboot
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_ibboot
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	NormalPrint("Uninstalling $ComponentInfo{'ibboot'}{'Name'}...\n");

	# production firmware for cougar 
	remove_boot_firmware("InfiniServC.A1", "mt23108");
	# production firmware for cougarcub
	remove_boot_firmware("InfiniServCC.A1", "mt23108");

	# production firmware for Arbel Lion Cub
	remove_boot_firmware("InfiniServEx.A0", "mt25208");
	remove_boot_firmware("InfiniServExC.A0", "mt25208");
	remove_boot_firmware("InfiniServEx_D.A0", "mt25208");
	remove_boot_firmware("InfiniServEx_D.20", "mt25208");

	$ComponentWasInstalled{'ibboot'}=0;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# InfiniFibre/SRP installation

# autostart functions are per subcomponent
sub IsAutostart2_ifibre()
{
	return IsAutostart("ics_srp");
}
sub autostart_desc_ifibre()
{
	return "$ComponentInfo{'ifibre'}{'Name'} (ics_srp)";
}
sub enable_autostart2_ifibre()
{
	enable_autostart("ics_srp");
}
sub disable_autostart2_ifibre()
{
	disable_autostart("ics_srp");
}

sub start_ifibre
{
	my $driver_subdir=$ComponentInfo{'ifibre'}{'DriverSubdir'};
	start_driver($ComponentInfo{'ifibre'}{'Name'}, "ics_srp", $driver_subdir, "ics_srp");
}

sub stop_ifibre
{
	stop_driver($ComponentInfo{'ifibre'}{'Name'}, "ics_srp", "ics_srp");
}

sub available_ifibre
{
	my $srcdir=$ComponentInfo{'ifibre'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "ics_srp");
}

sub installed_ifibre
{
	my $driver_subdir=$ComponentInfo{'ifibre'}{'DriverSubdir'};
	return installed_driver("ics_srp", $driver_subdir);
}

# only called if installed_ifibre is true
sub installed_version_ifibre
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_ifibre is true
sub media_version_ifibre
{
	my $srcdir=$ComponentInfo{'ifibre'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub build_ifibre
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ifibre($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_ifibre
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_ifibre
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'ifibre'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'ifibre'}{'DriverSubdir'};

	my $version=media_version_ifibre();
	chomp $version;
	printf("Installing $ComponentInfo{'ifibre'}{'Name'} Driver $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'ifibre'}{'Name'} Driver $version $DBG_FREE for $CUR_OS_VER\n";
	check_config_dirs;

	copy_driver ("ics_srp", $driver_subdir, "verbose");
	copy_systool_file("$srcdir/bin/build_srpcfg", "/sbin/build_srpcfg");
	install_conf_file("$ComponentInfo{'ifibre'}{'Name'}", "$CONFIG_DIR/ics_srp.cfg", "$srcdir/config/ics_srp.cfg");
	install_startup("$srcdir/config", "ics_srp", "$ComponentInfo{'ifibre'}{'Name'}");
	need_reboot();
	$ComponentWasInstalled{'ifibre'}=1;
}

sub postinstall_ifibre
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_ifibre
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	my $driver_subdir=$ComponentInfo{'ifibre'}{'DriverSubdir'};
	NormalPrint("Uninstalling $ComponentInfo{'ifibre'}{'Name'} Driver...\n");
	stop_ifibre;
	remove_driver ("ics_srp", $driver_subdir, "verbose");
	system("rm -rf $ROOT/sbin/build_srpcfg");
	remove_startup("ics_srp");
	remove_conf_file("$ComponentInfo{'ifibre'}{'Name'}", "$CONFIG_DIR/ics_srp.cfg");
	need_reboot();
	$ComponentWasInstalled{'ifibre'}=0;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# InfiniNIC/VNIC installation

# autostart functions are per subcomponent
sub IsAutostart2_inic()
{
	return IsAutostart("ics_inic");
}
sub autostart_desc_inic()
{
	return "$ComponentInfo{'inic'}{'Name'} (ics_inic)";
}
sub enable_autostart2_inic()
{
	enable_autostart("ics_inic");
}
sub disable_autostart2_inic()
{
	disable_autostart("ics_inic");
}

sub start_inic
{
	my $driver_subdir=$ComponentInfo{'inic'}{'DriverSubdir'};
	start_driver($ComponentInfo{'inic'}{'Name'}, "ics_inic", $driver_subdir, "ics_inic");
}

sub stop_inic
{
	stop_driver($ComponentInfo{'inic'}{'Name'}, "ics_inic", "ics_inic");
}

sub available_inic
{
	my $srcdir=$ComponentInfo{'inic'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "ics_inic");
}

sub installed_inic
{
	my $driver_subdir=$ComponentInfo{'inic'}{'DriverSubdir'};
	return installed_driver("ics_inic", $driver_subdir);
}

# only called if installed_inic is true
sub installed_version_inic
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_inic is true
sub media_version_inic
{
	my $srcdir=$ComponentInfo{'inic'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub build_inic
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_inic($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_inic
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_inic
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'inic'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'inic'}{'DriverSubdir'};

	my $version=media_version_inic();
	chomp $version;
	printf("Installing $ComponentInfo{'inic'}{'Name'} Driver $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'inic'}{'Name'} Driver $version $DBG_FREE for $CUR_OS_VER\n";
	check_config_dirs;

	copy_driver ("ics_inic", $driver_subdir, "verbose");

	install_conf_file("$ComponentInfo{'inic'}{'Name'}", "$CONFIG_DIR/ics_inic.cfg", "$srcdir/config/ics_inic.cfg");
	install_startup("$srcdir/config", "ics_inic", "$ComponentInfo{'inic'}{'Name'}");
	add_insserv_conf("ics_inic", "network");
	need_reboot();
	$ComponentWasInstalled{'inic'}=1;
}

sub postinstall_inic
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_inic
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	my $driver_subdir=$ComponentInfo{'inic'}{'DriverSubdir'};
	NormalPrint("Uninstalling $ComponentInfo{'inic'}{'Name'} Driver...\n");
	stop_inic;
	remove_driver ("ics_inic", $driver_subdir, "verbose");
	remove_startup("ics_inic");
	del_insserv_conf("ics_inic", "network");
	remove_conf_file("$ComponentInfo{'inic'}{'Name'}", "$CONFIG_DIR/ics_inic.cfg");
	need_reboot();
	$ComponentWasInstalled{'inic'}=0;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# IPoIB installation

sub Config_IPoIB_cfg
{
	# default is reasonable
	print "\n$ComponentInfo{'ipoib'}{'Name'} requires $CONFIG_DIR/ipoib.cfg specify parameters\n";
	print "for each $ComponentInfo{'ipoib'}{'Name'} device.\n";
	print "The default configuration file provides for a 2 port redundant configuration.\n";
	print "If you desire a different configuration for $ComponentInfo{'ipoib'}{'Name'}, Manually edit the file.\n\n";
	HitKeyCont
}

my $FirstIPoIBInterface=1;	# first device is ib1

# autostart functions are per subcomponent
sub IsAutostart2_ipoib()
{
	return IsAutostart("ipoib");
}
sub autostart_desc_ipoib()
{
	return "$ComponentInfo{'ipoib'}{'Name'} (ipoib)";
}
sub enable_autostart2_ipoib()
{
	enable_autostart("ipoib");
}
sub disable_autostart2_ipoib()
{
	disable_autostart("ipoib");
}

sub start_ipoib
{
	my $driver_subdir=$ComponentInfo{'ipoib'}{'DriverSubdir'};
	start_driver($ComponentInfo{'ipoib'}{'Name'}, "ipoib", $driver_subdir, "ipoib");
}

sub stop_ipoib
{
	stop_driver($ComponentInfo{'ipoib'}{'Name'}, "ipoib", "ipoib");
}

sub available_ipoib
{
	my $srcdir=$ComponentInfo{'ipoib'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "ipoib");
}

sub installed_ipoib
{
	my $driver_subdir=$ComponentInfo{'ipoib'}{'DriverSubdir'};
	return installed_driver("ipoib", $driver_subdir);
}

# only called if installed_ipoib is true
sub installed_version_ipoib
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_ipoib is true
sub media_version_ipoib
{
	my $srcdir=$ComponentInfo{'ipoib'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub build_ipoib
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ipoib($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_ipoib
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_ipoib
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'ipoib'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'ipoib'}{'DriverSubdir'};

	my $version=media_version_ipoib();
	chomp $version;
	printf("Installing $ComponentInfo{'ipoib'}{'Name'} Driver $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'ipoib'}{'Name'} Driver $version $DBG_FREE for $CUR_OS_VER\n";
	check_config_dirs;

	copy_driver ("ipoib", $driver_subdir, "verbose");

	install_conf_file("$ComponentInfo{'ipoib'}{'Name'}", "$CONFIG_DIR/ipoib.cfg", "$srcdir/config/ipoib.cfg");    
	Config_ifcfg(0,"$ComponentInfo{'ipoib'}{'Name'}","ib", "$FirstIPoIBInterface",1);
	Config_IPoIB_cfg;
	install_startup("$srcdir/config", "ipoib", "$ComponentInfo{'ipoib'}{'Name'}");
	add_insserv_conf("ipoib", "network");
	copy_systool_file("$srcdir/bin/ipoib_path", "/sbin/ipoib_path");
	need_reboot();
	$ComponentWasInstalled{'ipoib'}=1;
}

sub postinstall_ipoib
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_ipoib
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	my $driver_subdir=$ComponentInfo{'ipoib'}{'DriverSubdir'};
	NormalPrint("Uninstalling $ComponentInfo{'ipoib'}{'Name'} Driver...\n");
	#net_interface_down("ib"); - TBD, put in stop script
	#system "sleep 3";
	stop_ipoib;
	system("rm -rf $ROOT/sbin/ipoib_path");
	remove_driver ("ipoib", $driver_subdir, "verbose");
	remove_startup("ipoib");
	del_insserv_conf("ipoib", "network");
	remove_conf_file("$ComponentInfo{'ipoib'}{'Name'}", "$CONFIG_DIR/ipoib.cfg");
	Remove_ifcfg("ipoib","$ComponentInfo{'ipoib'}{'Name'}","ib");
	need_reboot();
	$ComponentWasInstalled{'ipoib'}=0;
}

#!/usr/bin/perl
# # INTEL CONFIDENTIAL
# # Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
# # The source code contained or described herein and all documents related
# # to the source code ("Material") are owned by Intel Corporation or its
# # suppliers or licensors. Title to the Material remains with Intel Corporation
# # or its suppliers and licensors. The Material contains trade secrets and
# # proprietary and confidential information of Intel or its suppliers and
# # licensors. The Material is protected by worldwide copyright and trade
# # secret laws and treaty provisions. No part of the Material may be used,
# # copied, reproduced, modified, published, uploaded, posted, transmitted,
# # distributed, or disclosed in any way without Intel's prior express
# # written permission.
# #
# # No license under any patent, copyright, trade secret or other intellectual
# # property right is granted to or conferred upon you by disclosure or delivery
# # of the Materials, either expressly, by implication, inducement, estoppel or
# # otherwise. Any license under such intellectual property rights must be
# # express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# kDAPL installation

# autostart functions are per subcomponent
sub IsAutostart2_kdapl()
{
	return IsAutostart("kdapl");
}
sub autostart_desc_kdapl()
{
	return "$ComponentInfo{'kdapl'}{'Name'} (kdapl)";
}
sub enable_autostart2_kdapl()
{
	enable_autostart("kdapl");
}
sub disable_autostart2_kdapl()
{
	disable_autostart("kdapl");
}

sub start_kdapl
{
	my $driver_subdir=$ComponentInfo{'kdapl'}{'DriverSubdir'};
	start_driver($ComponentInfo{'kdapl'}{'Name'}, "kdapl", $driver_subdir, "kdapl");
}

sub stop_kdapl
{
	stop_driver($ComponentInfo{'kdapl'}{'Name'}, "kdapl", "kdapl");
}

sub available_kdapl
{
	my $srcdir=$ComponentInfo{'kdapl'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "kdapl");
}

sub installed_kdapl
{
	my $driver_subdir=$ComponentInfo{'kdapl'}{'DriverSubdir'};
	return installed_driver("kdapl", $driver_subdir);
}

# only called if installed_kdapl is true
sub installed_version_kdapl
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_kdapl is true
sub media_version_kdapl
{
	my $srcdir=$ComponentInfo{'kdapl'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub build_kdapl
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_kdapl($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_kdapl
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_kdapl
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'kdapl'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'kdapl'}{'DriverSubdir'};

	my $version=media_version_kdapl();
	chomp $version;
	printf("Installing $ComponentInfo{'kdapl'}{'Name'} $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'kdapl'}{'Name'} $version $DBG_FREE for $CUR_OS_VER\n";

	# Copy all dapl include files
	copy_driver ("kdapl", $driver_subdir, "verbose");
	copy_driver ("kdapltest_module", $driver_subdir, "verbose");
	copy_driver ("dat_registry", $driver_subdir, "verbose");
	install_startup("$srcdir/config", "kdapl", "$ComponentInfo{'kdapl'}{'Name'}");
	need_reboot();
	$ComponentWasInstalled{'kdapl'}=1;
}

sub postinstall_kdapl
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_kdapl
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	my $driver_subdir=$ComponentInfo{'kdapl'}{'DriverSubdir'};
	NormalPrint("Uninstalling $ComponentInfo{'kdapl'}{'Name'}...\n");
	remove_driver ("kdapl", $driver_subdir, "verbose");
	remove_driver ("kdapltest_module", $driver_subdir, "verbose");
	remove_driver ("dat_registry", $driver_subdir, "verbose");
	remove_startup("kdapl");
	need_reboot();
	$ComponentWasInstalled{'kdapl'}=0;
}

#!/usr/bin/perl
# # INTEL CONFIDENTIAL
# # Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
# # The source code contained or described herein and all documents related
# # to the source code ("Material") are owned by Intel Corporation or its
# # suppliers or licensors. Title to the Material remains with Intel Corporation
# # or its suppliers and licensors. The Material contains trade secrets and
# # proprietary and confidential information of Intel or its suppliers and
# # licensors. The Material is protected by worldwide copyright and trade
# # secret laws and treaty provisions. No part of the Material may be used,
# # copied, reproduced, modified, published, uploaded, posted, transmitted,
# # distributed, or disclosed in any way without Intel's prior express
# # written permission.
# #
# # No license under any patent, copyright, trade secret or other intellectual
# # property right is granted to or conferred upon you by disclosure or delivery
# # of the Materials, either expressly, by implication, inducement, estoppel or
# # otherwise. Any license under such intellectual property rights must be
# # express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# Reliable Datagram Sockets (RDS) installation

# autostart functions are per subcomponent
sub IsAutostart2_rds()
{
	return IsAutostart("rds");
}
sub autostart_desc_rds()
{
	return "$ComponentInfo{'rds'}{'Name'} (rds)";
}
sub enable_autostart2_rds()
{
	enable_autostart("rds");
}
sub disable_autostart2_rds()
{
	disable_autostart("rds");
}

sub start_rds
{
	my $driver_subdir=$ComponentInfo{'rds'}{'DriverSubdir'};
	start_driver($ComponentInfo{'rds'}{'Name'}, "rds", $driver_subdir, "rds");
}

sub stop_rds
{
	stop_driver($ComponentInfo{'rds'}{'Name'}, "rds", "rds");
}

sub available_rds
{
	my $srcdir=$ComponentInfo{'rds'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "rds");
}

sub installed_rds
{
	my $driver_subdir=$ComponentInfo{'rds'}{'DriverSubdir'};
	return installed_driver("rds", $driver_subdir);
}

# only called if installed_rds is true
sub installed_version_rds
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_rds is true
sub media_version_rds
{
	my $srcdir=$ComponentInfo{'rds'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub build_rds
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_rds($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_rds
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_rds
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'rds'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'rds'}{'DriverSubdir'};

	my $version=media_version_rds();
	chomp $version;
	printf("Installing $ComponentInfo{'rds'}{'Name'} Driver $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'rds'}{'Name'} Driver $version $DBG_FREE for $CUR_OS_VER\n";

	copy_driver ("ics_offload", $driver_subdir, "verbose");
	copy_driver ("rds", $driver_subdir, "verbose");

	copy_systool_file("$srcdir/bin/rdsrename", "/sbin/rdsrename");
	copy_systool_file("$srcdir/bin/rdsrevert", "/sbin/rdsrevert");

	install_startup("$srcdir/config", "rds", "$ComponentInfo{'rds'}{'Name'}");
	add_insserv_conf("rds", "network");
	need_reboot();
	$ComponentWasInstalled{'rds'}=1;
}

sub postinstall_rds
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_rds
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	my $driver_subdir=$ComponentInfo{'rds'}{'DriverSubdir'};
	NormalPrint("Uninstalling $ComponentInfo{'rds'}{'Name'} Driver...\n");
	stop_rds;
	remove_driver ("rds", $driver_subdir, "verbose");

	if ( ! installed_sdp() ) {
		remove_driver ("ics_offload", $driver_subdir, "verbose");
	}
	system("rm -rf $ROOT/sbin/rdsrename");
	system("rm -rf $ROOT/sbin/rdsrevert");
	remove_startup("rds");
	del_insserv_conf("rds", "network");
	need_reboot();
	$ComponentWasInstalled{'rds'}=0;
}

#!/usr/bin/perl
# # INTEL CONFIDENTIAL
# # Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
# # The source code contained or described herein and all documents related
# # to the source code ("Material") are owned by Intel Corporation or its
# # suppliers or licensors. Title to the Material remains with Intel Corporation
# # or its suppliers and licensors. The Material contains trade secrets and
# # proprietary and confidential information of Intel or its suppliers and
# # licensors. The Material is protected by worldwide copyright and trade
# # secret laws and treaty provisions. No part of the Material may be used,
# # copied, reproduced, modified, published, uploaded, posted, transmitted,
# # distributed, or disclosed in any way without Intel's prior express
# # written permission.
# #
# # No license under any patent, copyright, trade secret or other intellectual
# # property right is granted to or conferred upon you by disclosure or delivery
# # of the Materials, either expressly, by implication, inducement, estoppel or
# # otherwise. Any license under such intellectual property rights must be
# # express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# Socket Direct Protocol (SDP) installation

# autostart functions are per subcomponent
sub IsAutostart2_sdp()
{
	return IsAutostart("ics_sdp");
}
sub autostart_desc_sdp()
{
	return "$ComponentInfo{'sdp'}{'Name'} (ics_sdp)";
}
sub enable_autostart2_sdp()
{
	enable_autostart("ics_sdp");
}
sub disable_autostart2_sdp()
{
	disable_autostart("ics_sdp");
}

sub start_sdp
{
	my $driver_subdir=$ComponentInfo{'sdp'}{'DriverSubdir'};
	start_driver($ComponentInfo{'sdp'}{'Name'}, "ics_sdp", $driver_subdir, "ics_sdp");
}

sub stop_sdp
{
	stop_driver($ComponentInfo{'sdp'}{'Name'}, "ics_sdp", "ics_sdp");
}

sub available_sdp
{
	my $srcdir=$ComponentInfo{'sdp'}{'SrcDir'};
	return available_driver("$srcdir/bin/$ARCH", "ics_sdp");
}

sub installed_sdp
{
	my $driver_subdir=$ComponentInfo{'sdp'}{'DriverSubdir'};
	return installed_driver("ics_sdp", $driver_subdir);
}

# only called if installed_sdp is true
sub installed_version_sdp
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_sdp is true
sub media_version_sdp
{
	my $srcdir=$ComponentInfo{'sdp'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub build_sdp
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_sdp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_sdp
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_sdp
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $driver_subdir=$ComponentInfo{'sdp'}{'DriverSubdir'};
	my $srcdir=$ComponentInfo{'sdp'}{'SrcDir'};
	my $result;

	my $version=media_version_sdp();
	chomp $version;
	printf("Installing $ComponentInfo{'sdp'}{'Name'} Driver $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'sdp'}{'Name'} Driver $version $DBG_FREE for $CUR_OS_VER\n";

	copy_driver ("ics_offload", $driver_subdir, "verbose");
	copy_driver ("ics_sdp", $driver_subdir, "verbose");

	copy_systool_file("$srcdir/bin/sdprename", "/sbin/sdprename");
	copy_systool_file("$srcdir/bin/sdprevert", "/sbin/sdprevert");

	install_startup("$srcdir/config", "ics_sdp", "$ComponentInfo{'sdp'}{'Name'}");
	add_insserv_conf("ics_sdp", "network");

	NormalPrint "Enabling NFS over SDP\n";

	$result=`/sbin/sdprename`;
	NormalPrint "$result\n";
		
	need_reboot();
	$ComponentWasInstalled{'sdp'}=1;
}

sub postinstall_sdp
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_sdp
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	my $result;
	my $driver_subdir=$ComponentInfo{'sdp'}{'DriverSubdir'};

	NormalPrint("Uninstalling $ComponentInfo{'sdp'}{'Name'} Driver...\n");
	stop_sdp;
	remove_driver ("ics_sdp", $driver_subdir, "verbose");

	$result=`/sbin/sdprevert`;
	NormalPrint "$result\n";

	if ( ! installed_rds() ) {
        remove_driver ("ics_offload", $driver_subdir, "verbose");
    }

	system("rm -rf $ROOT/sbin/sdprename");
	system("rm -rf $ROOT/sbin/sdprevert");
	remove_startup("ics_sdp");
	del_insserv_conf("ics_sdp", "network");
	need_reboot();
	$ComponentWasInstalled{'sdp'}=0;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# MPI Runtime installation

sub available_mpi
{
	my $srcdir=$ComponentInfo{'mpi'}{'SrcDir'};
	return ( -e "$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/mpi/libmpicm.so.1.0" && ! installed_ipath);
}

sub installed_mpi
{
	return (-e "$ROOT$LIB_DIR/libmpicm.so.1.0" || -e "$ROOT$OLD_LIB_DIR/libmpicm.so.1.0");
}

# only called if installed_mpi is true
sub installed_version_mpi
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_mpi is true
sub media_version_mpi
{
	my $srcdir=$ComponentInfo{'mpi'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

my(@mpi_shared_lib_list) = ( 'libmpich', 'libfmpich', 'libpmpich');

my(@mpi_bin_list) = ( 'mpirun_rsh', 'mpirun', 'mpirun.args', 'mpirun_dbg.dbx',
	'mpirun_dbg.ddd', 'mpirun_dbg.gdb', 'mpirun_dbg.ladebug',
	'mpirun_dbg.totalview', 'mpirun_dbg.xxgdb', 'mpirun.vapi',
	'mpirun.vapi.args', 'read_params.pl', 'tarch', 'tdevice', 'mpd', 'mpdcon',
	'mpdman', 'startmpidaemons', 'setupmpdlink', 'rmmpdlink', 'setupmpd');

sub build_mpi
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_mpi($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_mpi
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_mpi
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $file;
	my $srcdir=$ComponentInfo{'mpi'}{'SrcDir'};

	my $version=media_version_mpi();
	chomp $version;
	printf("Installing $ComponentInfo{'mpi'}{'Name'} $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'mpi'}{'Name'} $version $DBG_FREE for $CUR_OS_VER\n";
	check_config_dirs;

	# Create the shared object directory.
	check_dir("$OPTIBALIB_DIR/shared");
	if ( ! $Skip_UsrLocalSymLinks ) {
		check_dir("$USRLOCALLIB_DIR/shared");
	}
	foreach $file ( @mpi_shared_lib_list) {
		copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/mpi/$file", "$OPTIBALIB_DIR/shared/$file", "1.0");
		if ( ! $Skip_UsrLocalSymLinks ) {
			remove_oldshlib("$OLD_USRLOCALLIB_DIR/shared/$file");
			symlink_usrlocal_shlib("$OPTIBALIB_DIR/shared/$file", "$USRLOCALLIB_DIR/shared/$file", "1.0");
		}
	}
	# Keep the cm library in /lib so that users don't inadvertently blow it away.
	remove_oldshlib("$OLD_LIB_DIR/libmpicm");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/mpi/libmpicm", "$LIB_DIR/libmpicm", "1.0");

	install_conf_file("$ComponentInfo{'mpi'}{'Name'}", "$CONFIG_DIR/mpi.param", "$srcdir/config/param.sample");
	install_conf_file("$ComponentInfo{'mpi'}{'Name'}", "$CONFIG_DIR/mpi.param.microbench", "$srcdir/config/mpi.param.microbench");
	install_conf_file("$ComponentInfo{'mpi'}{'Name'}", "$CONFIG_DIR/mpi.param.safe", "$srcdir/config/mpi.param.safe");
	
	# Copy required bin files
	check_dir("/opt/iba/bin");
	if ( ! $Skip_UsrLocalSymLinks ) {
		check_dir("/usr/local/bin");
	}
	foreach $file ( @mpi_bin_list) {
		copy_bin_file("$srcdir/bin/mpi/$file", "/opt/iba/bin/$file");
		if ( ! $Skip_UsrLocalSymLinks ) {
			symlink_usrlocal("/opt/iba/bin/$file", "/usr/local/bin/$file");
		}
	}
	copy_data_file("$srcdir/bin/mpi/mpd.hosts","/opt/iba/bin/mpd.hosts");
	if ( ! $Skip_UsrLocalSymLinks ) {
		symlink_usrlocal("/opt/iba/bin/mpd.hosts",  "/usr/local/bin/mpd.hosts");
	}
	system("ROOT=/$ROOT MPICH_PREFIX=/opt/iba $ROOT/opt/iba/bin/setupmpdlink");
	if ( ! $Skip_UsrLocalSymLinks ) {
		system("ROOT=/$ROOT MPICH_PREFIX=/usr/local $ROOT/opt/iba/bin/setupmpdlink");
	}
	
	$ComponentWasInstalled{'mpi'}=1;
}

sub postinstall_mpi
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_mpi
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	my $file;

	NormalPrint("Uninstalling $ComponentInfo{'mpi'}{'Name'}...\n");
	
	# list of files that should be uninstalled.  Items should never be
	# removed from this list to support uninstalling previous installations.

	system("ROOT=/$ROOT MPICH_PREFIX=/opt/iba $ROOT/opt/iba/bin/rmmpdlink 2>/dev/null");
	if ( ! $Skip_UsrLocalSymLinks ) {
		system("ROOT=/$ROOT MPICH_PREFIX=/usr/local $ROOT/opt/iba/bin/rmmpdlink 2>/dev/null");
	}
	foreach $file ( @mpi_shared_lib_list) {
		remove_shlib("$OPTIBALIB_DIR/shared/$file");
		if ( ! $Skip_UsrLocalSymLinks ) {
			remove_shlib("$USRLOCALLIB_DIR/shared/$file");
			remove_oldshlib("$OLD_USRLOCALLIB_DIR/shared/$file");
		}
	}
	remove_shlib("$LIB_DIR/libmpicm");
	remove_oldshlib("$OLD_LIB_DIR/libmpicm");
	remove_conf_file("$ComponentInfo{'mpi'}{'Name'}", "$CONFIG_DIR/mpi.param");
	remove_conf_file("$ComponentInfo{'mpi'}{'Name'}", "$CONFIG_DIR/mpi.param.microbench");
	remove_conf_file("$ComponentInfo{'mpi'}{'Name'}", "$CONFIG_DIR/mpi.param.safe");
	foreach $file ( @mpi_bin_list) {
		remove_file("/opt/iba/bin/$file");
		if ( ! $Skip_UsrLocalSymLinks ) {
			remove_file("/usr/local/bin/$file");
		}
	}
	remove_file("/opt/iba/bin/mpd.hosts");
	if ( ! $Skip_UsrLocalSymLinks ) {
		remove_file("/usr/local/bin/mpd.hosts");
	}
	remove_shlib("$LIB_DIR/libmpich");
	remove_shlib("$OLD_LIB_DIR/libmpich");
	#remove_shlib("$LIB_DIR/libfmpich");
	#remove_oldshlib("$OLD_LIB_DIR/libfmpich");
	#remove_shlib("$LIB_DIR/libpmpich");
	#remove_oldshlib("$OLD_LIB_DIR/libpmpich");
	system "rmdir $ROOT$OPTIBALIB_DIR/shared 2>/dev/null";	# remove only if empty
	if ( ! $Skip_UsrLocalSymLinks ) {
		system "rmdir $ROOT$USRLOCALLIB_DIR/shared 2>/dev/null";	# remove only if empty
	}
	system "rmdir $ROOT$OPTIBALIB_DIR 2>/dev/null";	# remove only if empty
	system "rmdir $ROOT/opt/iba/bin 2>/dev/null";	# remove only if empty
	system "rmdir $ROOT/opt/iba 2>/dev/null";	# remove only if empty
	$ComponentWasInstalled{'mpi'}=0;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# MPI Sample Applications sub-component installation

# remove the files built from source or installed
# (as listed in .files and .dirs)
# $0 = dirname relative to $ROOT
sub remove_mpi_apps($)
{
	my $dirname = shift();

	if ( -d "$ROOT/$dirname" ) {
		system "cd $ROOT/$dirname; make clean >/dev/null 2>&1";
		system "cd $ROOT/$dirname; cat .files 2>/dev/null|xargs rm -f 2>/dev/null";
		system "cd $ROOT/$dirname; cat .files 2>/dev/null|sort -r|xargs rmdir 2>/dev/null";
		system "rm -f $ROOT/$dirname/.files 2>/dev/null";
		system "rmdir $ROOT/$dirname/hpl-config 2>/dev/null";
		system "rmdir $ROOT/$dirname/ 2>/dev/null";
	}
}

sub uninstall_mpi_apps();

sub install_mpi_apps($)
{
	my $srcdir=shift();

	my $file;

	# clean existing mpi sample applications
	uninstall_mpi_apps;

	# Copy all mpi sample applications
	check_dir("/opt/iba/src");
	check_dir("/opt/iba/src/mpi_apps");
	if ( ! $Skip_UsrLocalSymLinks ) {
		# move any other user files to new location
		if ( -d "$ROOT/usr/local/src/mpi_apps" && ! -l "$ROOT/usr/local/src/mpi_apps" ) {
			system("mv -f $ROOT/usr/local/src/mpi_apps/* $ROOT/opt/iba/src/mpi_apps");
			system("mv -f $ROOT/usr/local/src/mpi_apps/.* $ROOT/opt/iba/src/mpi_apps 2>/dev/null");
			system("rmdir $ROOT/usr/local/src/mpi_apps");
		}
	}
	if ( -e "$srcdir/mpi/mpi_apps/mpi_apps.tgz" )
	{
		system("tar xfvz $srcdir/mpi/mpi_apps/mpi_apps.tgz --directory $ROOT/opt/iba/src/mpi_apps > $ROOT/opt/iba/src/mpi_apps/.files");
	}
	# allow all users to read the files so they can copy and use
	system("chmod -R ugo+r $ROOT/opt/iba/src/mpi_apps");
	system("find $ROOT/opt/iba/src/mpi_apps -type d|xargs chmod ugo+x");
	if ( ! $Skip_UsrLocalSymLinks ) {
		check_dir("/usr/local/src");
		symlink_usrlocal("/opt/iba/src/mpi_apps", "/usr/local/src/mpi_apps");
	}
}

sub uninstall_mpi_apps()
{
	# remove mpi_apps we installed or user compiled, however do not remove
	# any logs or other files the user may have created
	if ( ! $Skip_UsrLocalSymLinks ) {
		remove_mpi_apps "/usr/local/src/mpi_apps";
		system "rm -f $ROOT/usr/local/src/mpi_apps";
		system "rmdir $ROOT/usr/local/src/mpi_apps 2>/dev/null";	# only if empty
		system "rmdir $ROOT/usr/local/src 2>/dev/null";	# only if empty
	}
	remove_mpi_apps "/opt/iba/src/mpi_apps";
	system "rmdir $ROOT/opt/iba/src 2>/dev/null";	# remove only if empty
	system "rmdir $ROOT/opt/iba 2>/dev/null";	# remove only if empty
}

# ==========================================================================
# SHMEM Sample Applications sub-component installation

# remove the files built from source or installed
# (as listed in .files and .dirs)
# $0 = dirname relative to $ROOT
sub remove_shmem_apps($)
{
	my $dirname = shift();

	if ( -d "$ROOT/$dirname" ) {
		system "cd $ROOT/$dirname; make clean >/dev/null 2>&1";
		system "cd $ROOT/$dirname; cat .files 2>/dev/null|xargs rm -f 2>/dev/null";
		system "cd $ROOT/$dirname; cat .files 2>/dev/null|sort -r|xargs rmdir 2>/dev/null";
		system "rm -f $ROOT/$dirname/.files 2>/dev/null";
		system "rmdir $ROOT/$dirname/ 2>/dev/null";
	}
}

sub uninstall_shmem_apps();

sub install_shmem_apps($)
{
	my $srcdir=shift();

	my $file;

	# clean existing shmem sample applications
	uninstall_shmem_apps;

	# Copy all shmem sample applications
	check_dir("/opt/iba/src");
	check_dir("/opt/iba/src/shmem_apps");
	if ( -e "$srcdir/shmem/shmem_apps/shmem_apps.tgz" )
	{
		system("tar xfvz $srcdir/shmem/shmem_apps/shmem_apps.tgz --directory $ROOT/opt/iba/src/shmem_apps > $ROOT/opt/iba/src/shmem_apps/.files");
	}
	# allow all users to read the files so they can copy and use
	system("chmod -R ugo+r $ROOT/opt/iba/src/shmem_apps");
	system("find $ROOT/opt/iba/src/shmem_apps -type d|xargs chmod ugo+x");
}

sub uninstall_shmem_apps()
{
	# remove shmem_apps we installed or user compiled, however do not remove
	# any logs or other files the user may have created
	remove_shmem_apps "/opt/iba/src/shmem_apps";
	system "rmdir $ROOT/opt/iba/src 2>/dev/null";	# remove only if empty
	system "rmdir $ROOT/opt/iba 2>/dev/null";	# remove only if empty
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# MPI Development installation

sub available_mpidev
{
	my $srcdir=$ComponentInfo{'mpidev'}{'SrcDir'};
	return ( -e "$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/mpi/libmpich.a" && ! installed_ipath);
}

sub installed_mpidev
{
	return (-e "$ROOT$LIB_DIR/.mpidev" || -e "$ROOT$OLD_LIB_DIR/.mpidev");
}

# only called if installed_mpidev is true
sub installed_version_mpidev
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_mpidev is true
sub media_version_mpidev
{
	my $srcdir=$ComponentInfo{'mpidev'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

my(@mpi_arlib_list) = ( 'libmpich.a', 'libfmpich.a', 'libpmpich.a',
	'libmpe.a', 'libampe.a', 'liblmpe.a', 'libtmpe.a', 'libmpichfarg.a',
	'libmpichfsup.a', 'libpmpich++.a');

sub build_mpidev
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_mpidev($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_mpidev
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_mpidev
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $file;
	my $srcdir=$ComponentInfo{'mpidev'}{'SrcDir'};

	my $version=media_version_mpidev();
	chomp $version;
	printf("Installing $ComponentInfo{'mpidev'}{'Name'} $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'mpidev'}{'Name'} $version $DBG_FREE for $CUR_OS_VER\n";

	system "echo > $ROOT$LIB_DIR/.mpidev";
	foreach $file ( @mpi_arlib_list) {
		copy_arlib_file("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/mpi/$file", "$OPTIBALIB_DIR/$file");
		if ( ! $Skip_UsrLocalSymLinks ) {
			remove_oldarlib("$OLD_USRLOCALLIB_DIR/$file");
			symlink_usrlocal("$OPTIBALIB_DIR/$file", "$USRLOCALLIB_DIR/$file");
		}
	}

	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/mpi/libtvmpich", "$OPTIBALIB_DIR/libtvmpich", "1.0");
	if ( ! $Skip_UsrLocalSymLinks ) {
		remove_oldshlib("$OLD_USRLOCALLIB_DIR/libtvmpich");
		symlink_usrlocal_shlib("$OPTIBALIB_DIR/libtvmpich", "$USRLOCALLIB_DIR/libtvmpich", "1.0");
	}

	# Copy all mpi include files
	check_dir("/opt/iba/include");
	copy_all_data_files("$srcdir/include/mpi", "/opt/iba/include", "/usr/local/include");
	
	# Copy all mpi man pages
	check_dir("/opt/iba/man/man1");
	check_dir("/opt/iba/man/man3");
	check_dir("/opt/iba/man/man4");
	if ( ! $Skip_UsrLocalSymLinks ) {
		check_dir("/usr/local/man/man1");
		check_dir("/usr/local/man/man3");
		check_dir("/usr/local/man/man4");
	}
	copy_all_data_files("$srcdir/doc/mpi/man/man1", "/opt/iba/man/man1", "/usr/local/man/man1");
	copy_all_data_files("$srcdir/doc/mpi/man/man3", "/opt/iba/man/man3", "/usr/local/man/man3");
	copy_all_data_files("$srcdir/doc/mpi/man/man4", "/opt/iba/man/man4", "/usr/local/man/man4");

	my(@mpi_compiler_list) = ( 'mpicc', 'mpiCC', 'mpicxx', 'mpif77', 'mpif90');
	check_dir("/opt/iba/bin");
	if ( ! $Skip_UsrLocalSymLinks ) {
		check_dir("/usr/local/bin");
	}
	foreach $file ( @mpi_compiler_list) {
		copy_bin_file("$srcdir/bin/mpi/$file", "/opt/iba/bin/$file");
		symlink_usrlocal("/opt/iba/bin/$file", "/usr/local/bin/$file");
	}

	system "rm -f $ROOT/usr/local/include/LICENSE.TXT 2>/dev/null"; #old file no longer released
	install_mpi_apps($srcdir);
	$ComponentWasInstalled{'mpidev'}=1;
}

sub postinstall_mpidev
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_mpidev
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	NormalPrint("Uninstalling $ComponentInfo{'mpidev'}{'Name'}...\n");

	# list of files that should be uninstalled.  Items should never be
	# removed from this list to support uninstalling previous installations.
	my(@mpi_hdr_list) = ( 'attr.h', 'mpe.h', 'mpidmpi.h', 'mpi.h', 'ptrcvt.h', 
		'basex11.h', 'mpe_log.h', 'mpi_errno.h', 'mpiimpl.h', 'sbcnst.h', 
		'binding.h', 'mpetools.h', 'mpi_error.h', 'mpiops.h', 'sendq.h', 
		'LICENSE.TXT', 'mpichconf.h', 'mpif.f90', 'mpiprof.h', 'mpeexten.h', 
		'MPICH_COPYRIGHT', 'mpif.h', 'mpipt2pt.h', 'mpef.h', 'mpicoll.h', 
		'MVICH_LICENSE.TXT', 'COPYRIGHT_MVAPICH', 'mpio.h',
		'mpi_fortdefs.h', 'patchlevel.h', 'mpe_graphics.h', 'mpidefs.h', 
		'mpifort.h', 'protofix.h' );
	my(@mpi_man_list) = ( 'man1/chp4_servs.1.gz', 'man1/MPI.1.gz', 
		'man1/mpif90.1.gz', 'man1/tstmachines.1.gz', 'man1/cleanipcs.1.gz', 
		'man1/mpicc.1.gz', 'man1/mpiman.1.gz', 'man1/mpiCC.1.gz', 
		'man1/mpicxx.1.gz', 
		'man1/mpireconfig.1.gz', 'man1/Jumpshots.1.gz', 'man1/mpif77.1.gz',
		'man1/mpirun.1.gz',
		'man3/Constants.3.gz', 'man3/MPI_Finalized.3.gz',
		'man3/MPI_FLOAT.3.gz',
		'man3/MPI_2COMPLEX.3.gz', 'man3/MPI_FLOAT_INT.3.gz',
		'man3/MPI_2DOUBLE_COMPLEX.3.gz', 'man3/MPI_Gather.3.gz',
		'man3/MPI_2DOUBLE_PRECISION.3.gz', 'man3/MPI_Gatherv.3.gz',
		'man3/MPI_2INT.3.gz', 'man3/MPI_Get_count.3.gz',
		'man3/MPI_2INTEGER.3.gz', 'man3/MPI_Get_elements.3.gz',
		'man3/MPI_2REAL.3.gz', 'man3/MPI_Get_processor_name.3.gz',
		'man3/MPI_Abort.3.gz', 'man3/MPI_Get_version.3.gz',
		'man3/MPI_Address.3.gz', 'man3/MPI_GRAPH.3.gz',
		'man3/MPI_Aint.3.gz', 'man3/MPI_Graph_create.3.gz',
		'man3/MPI_Allgather.3.gz', 'man3/MPI_Graphdims_get.3.gz',
		'man3/MPI_Allgatherv.3.gz', 'man3/MPI_Graph_get.3.gz',
		'man3/MPI_Allreduce.3.gz', 'man3/MPI_Graph_map.3.gz',
		'man3/MPI_Alltoall.3.gz', 'man3/MPI_Graph_neighbors.3.gz',
		'man3/MPI_Alltoallv.3.gz', 'man3/MPI_Graph_neighbors_count.3.gz',
		'man3/MPI_ANY_SOURCE.3.gz', 'man3/MPI_Group_compare.3.gz',
		'man3/MPI_ANY_TAG.3.gz', 'man3/MPI_Group_difference.3.gz',
		'man3/MPI_Attr_delete.3.gz', 'man3/MPI_GROUP_EMPTY.3.gz',
		'man3/MPI_Attr_get.3.gz', 'man3/MPI_Group_excl.3.gz',
		'man3/MPI_Attr_put.3.gz', 'man3/MPI_Group_free.3.gz',
		'man3/MPI_BAND.3.gz', 'man3/MPI_Group_incl.3.gz',
		'man3/MPI_Barrier.3.gz', 'man3/MPI_Group_intersection.3.gz',
		'man3/MPI_Bcast.3.gz', 'man3/MPI_GROUP_NULL.3.gz',
		'man3/MPI_BOR.3.gz', 'man3/MPI_Group_range_excl.3.gz',
		'man3/MPI_BOTTOM.3.gz', 'man3/MPI_Group_range_incl.3.gz',
		'man3/MPI_Bsend.3.gz', 'man3/MPI_Group_rank.3.gz',
		'man3/MPI_Bsend_init.3.gz', 'man3/MPI_Group_size.3.gz',
		'man3/MPI_BSEND_OVERHEAD.3.gz', 'man3/MPI_Group_translate_ranks.3.gz',
		'man3/MPI_Buffer_attach.3.gz', 'man3/MPI_Group_union.3.gz',
		'man3/MPI_Buffer_detach.3.gz', 'man3/MPI_Handler_function.3.gz',
		'man3/MPI_BXOR.3.gz', 'man3/MPI_HOST.3.gz',
		'man3/MPI_BYTE.3.gz', 'man3/MPI_Ibsend.3.gz',
		'man3/MPI_Cancel.3.gz', 'man3/MPI_IDENT.3.gz',
		'man3/MPI_CART.3.gz', 'man3/MPI_Info_c2f.3.gz',
		'man3/MPI_Cart_coords.3.gz', 'man3/MPI_Info_create.3.gz',
		'man3/MPI_Cart_create.3.gz', 'man3/MPI_Info_delete.3.gz',
		'man3/MPI_Cartdim_get.3.gz', 'man3/MPI_Info_dup.3.gz',
		'man3/MPI_Cart_get.3.gz', 'man3/MPI_Info_f2c.3.gz',
		'man3/MPI_Cart_map.3.gz', 'man3/MPI_Info_free.3.gz',
		'man3/MPI_Cart_rank.3.gz', 'man3/MPI_Info_get.3.gz',
		'man3/MPI_Cart_shift.3.gz', 'man3/MPI_Info_get_nkeys.3.gz',
		'man3/MPI_Cart_sub.3.gz', 'man3/MPI_Info_get_nthkey.3.gz',
		'man3/MPI_CHAR.3.gz', 'man3/MPI_Info_get_valuelen.3.gz',
		'man3/MPI_Comm_compare.3.gz', 'man3/MPI_Info_set.3.gz',
		'man3/MPI_Comm_create.3.gz', 'man3/MPI_Init.3.gz',
		'man3/MPI_Comm_dup.3.gz', 'man3/MPI_Initialized.3.gz',
		'man3/MPI_Comm_free.3.gz', 'man3/MPI_Init_thread.3.gz',
		'man3/MPI_Comm_get_name.3.gz', 'man3/MPI_Int2handle.3.gz',
		'man3/MPI_Comm_group.3.gz', 'man3/MPI_INT.3.gz',
		'man3/MPI_COMM_NULL.3.gz', 'man3/MPI_INTEGER1.3.gz',
		'man3/MPI_Comm_rank.3.gz', 'man3/MPI_INTEGER2.3.gz',
		'man3/MPI_Comm_remote_group.3.gz', 'man3/MPI_INTEGER.3.gz',
		'man3/MPI_Comm_remote_size.3.gz', 'man3/MPI_INTEGER4.3.gz',
		'man3/MPI_COMM_SELF.3.gz', 'man3/MPI_Intercomm_create.3.gz',
		'man3/MPI_Comm_set_name.3.gz', 'man3/MPI_Intercomm_merge.3.gz',
		'man3/MPI_Comm_size.3.gz', 'man3/MPI_IO.3.gz',
		'man3/MPI_Comm_split.3.gz', 'man3/MPI_Iprobe.3.gz',
		'man3/MPI_Comm_test_inter.3.gz', 'man3/MPI_Irecv.3.gz',
		'man3/MPI_COMM_WORLD.3.gz', 'man3/MPI_Irsend.3.gz',
		'man3/MPI_COMPLEX.3.gz', 'man3/MPI_Isend.3.gz',
		'man3/MPI_CONGRUENT.3.gz', 'man3/MPI_Issend.3.gz',
		'man3/MPI_Copy_function.3.gz', 'man3/MPI_Keyval_create.3.gz',
		'man3/MPI_DATATYPE_NULL.3.gz', 'man3/MPI_Keyval_free.3.gz',
		'man3/MPI_Delete_function.3.gz', 'man3/MPI_KEYVAL_INVALID.3.gz',
		'man3/MPI_Dims_create.3.gz', 'man3/MPI_LAND.3.gz',
		'man3/MPI_DOUBLE.3.gz', 'man3/MPI_LB.3.gz',
		'man3/MPI_DOUBLE_COMPLEX.3.gz', 'man3/MPI_LOGICAL.3.gz',
		'man3/MPI_DOUBLE_INT.3.gz', 'man3/MPI_LONG.3.gz',
		'man3/MPI_DOUBLE_PRECISION.3.gz', 'man3/MPI_LONG_DOUBLE.3.gz',
		'man3/MPI_DUP_FN.3.gz', 'man3/MPI_LONG_DOUBLE_INT.3.gz',
		'man3/MPI_ERR_ARG.3.gz', 'man3/MPI_LONG_INT.3.gz',
		'man3/MPI_ERR_BAD_ARGS.3.gz', 'man3/MPI_LONG_LONG_INT.3.gz',
		'man3/MPI_ERR_BUFFER.3.gz', 'man3/MPI_LOR.3.gz',
		'man3/MPI_ERR_BUFFER_EXISTS.3.gz', 'man3/MPI_LXOR.3.gz',
		'man3/MPI_ERR_COMM.3.gz', 'man3/MPI_MAX.3.gz',
		'man3/MPI_ERR_COMM_INTER.3.gz', 'man3/MPI_MAX_ERROR_STRING.3.gz',
		'man3/MPI_ERR_COMM_INTRA.3.gz', 'man3/MPI_MAXLOC.3.gz',
		'man3/MPI_ERR_COMM_NULL.3.gz', 'man3/MPI_MAX_PROCESSOR_NAME.3.gz',
		'man3/MPI_ERR_COUNT.3.gz', 'man3/MPI_MIN.3.gz',
		'man3/MPI_ERR_DIMS.3.gz', 'man3/MPI_MINLOC.3.gz',
		'man3/MPI_ERR_ERRORCODE.3.gz', 'man3/MPI_NULL_COPY_FN.3.gz',
		'man3/MPI_ERR_EXHAUSTED.3.gz', 'man3/MPI_NULL_DELETE_FN.3.gz',
		'man3/MPI_ERR_GROUP.3.gz', 'man3/MPI_Op_create.3.gz',
		'man3/MPI_Errhandler_create.3.gz', 'man3/MPI_Op_free.3.gz',
		'man3/MPI_Errhandler_free.3.gz', 'man3/MPI_OP_NULL.3.gz',
		'man3/MPI_Errhandler_get.3.gz', 'man3/MPIO_Request_c2f.3.gz',
		'man3/MPI_ERRHANDLER_NULL.3.gz', 'man3/MPIO_Request_f2c.3.gz',
		'man3/MPI_Errhandler_set.3.gz', 'man3/MPIO_Test.3.gz',
		'man3/MPI_ERR_INIT.3.gz', 'man3/MPIO_Wait.3.gz',
		'man3/MPI_ERR_IN_STATUS.3.gz', 'man3/MPI_Pack.3.gz',
		'man3/MPI_ERR_INTERN.3.gz', 'man3/MPI_PACKED.3.gz',
		'man3/MPI_ERR_LASTCODE.3.gz', 'man3/MPI_Pack_size.3.gz',
		'man3/MPI_ERR_LIMIT.3.gz', 'man3/MPI_Pcontrol.3.gz',
		'man3/MPI_ERR_NOMATCH.3.gz', 'man3/MPI_Probe.3.gz',
		'man3/MPI_ERR_NULL.3.gz', 'man3/MPI_PROC_NULL.3.gz',
		'man3/MPI_ERR_OP.3.gz', 'man3/MPI_PROD.3.gz',
		'man3/MPI_ERROR.3.gz', 'man3/MPI_REAL.3.gz',
		'man3/MPI_Error_class.3.gz', 'man3/MPI_REAL4.3.gz',
		'man3/MPI_ERRORS_ARE_FATAL.3.gz', 'man3/MPI_REAL8.3.gz',
		'man3/MPI_ERRORS_RETURN.3.gz', 'man3/MPI_Recv.3.gz',
		'man3/MPI_Error_string.3.gz', 'man3/MPI_Recv_init.3.gz',
		'man3/MPI_ERR_OTHER.3.gz', 'man3/MPI_Reduce.3.gz',
		'man3/MPI_ERR_PERM_KEY.3.gz', 'man3/MPI_Reduce_scatter.3.gz',
		'man3/MPI_ERR_PERM_OP.3.gz', 'man3/MPI_Request_c2f.3.gz',
		'man3/MPI_ERR_PERM_TYPE.3.gz', 'man3/MPI_Request_free.3.gz',
		'man3/MPI_ERR_PRE_INIT.3.gz', 'man3/MPI_REQUEST_NULL.3.gz',
		'man3/MPI_ERR_RANK.3.gz', 'man3/MPI_Rsend.3.gz',
		'man3/MPI_ERR_REQUEST.3.gz', 'man3/MPI_Rsend_init.3.gz',
		'man3/MPI_ERR_ROOT.3.gz', 'man3/MPI_Scan.3.gz',
		'man3/MPI_ERR_TAG.3.gz', 'man3/MPI_Scatter.3.gz',
		'man3/MPI_ERR_TOPOLOGY.3.gz', 'man3/MPI_Scatterv.3.gz',
		'man3/MPI_ERR_TRUNCATE.3.gz', 'man3/MPI_Send.3.gz',
		'man3/MPI_ERR_TYPE.3.gz', 'man3/MPI_Send_init.3.gz',
		'man3/MPI_ERR_UNKNOWN.3.gz', 'man3/MPI_Sendrecv.3.gz',
		'man3/MPI_File_c2f.3.gz', 'man3/MPI_Sendrecv_replace.3.gz',
		'man3/MPI_File_close.3.gz', 'man3/MPI_SHORT.3.gz',
		'man3/MPI_File_delete.3.gz', 'man3/MPI_SHORT_INT.3.gz',
		'man3/MPI_File_f2c.3.gz', 'man3/MPI_SIMILAR.3.gz',
		'man3/MPI_File_get_amode.3.gz', 'man3/MPI_SOURCE.3.gz',
		'man3/MPI_File_get_atomicity.3.gz', 'man3/MPI_Ssend.3.gz',
		'man3/MPI_File_get_byte_offset.3.gz', 'man3/MPI_Ssend_init.3.gz',
		'man3/MPI_File_get_errhandler.3.gz', 'man3/MPI_Start.3.gz',
		'man3/MPI_File_get_group.3.gz', 'man3/MPI_Startall.3.gz',
		'man3/MPI_File_get_info.3.gz', 'man3/MPI_Status_c2f.3.gz',
		'man3/MPI_File_get_position.3.gz', 'man3/MPI_Status_set_cancelled.3.gz',
		'man3/MPI_File_get_position_shared.3.gz', 'man3/MPI_Status_set_elements.3.gz',
		'man3/MPI_File_get_size.3.gz', 'man3/MPI_SUCCESS.3.gz',
		'man3/MPI_File_get_type_extent.3.gz', 'man3/MPI_SUM.3.gz',
		'man3/MPI_File_get_view.3.gz', 'man3/MPI_TAG.3.gz',
		'man3/MPI_File_iread.3.gz', 'man3/MPI_TAG_UB.3.gz',
		'man3/MPI_File_iread_at.3.gz', 'man3/MPI_Test.3.gz',
		'man3/MPI_File_iread_shared.3.gz', 'man3/MPI_Testall.3.gz',
		'man3/MPI_File_iwrite.3.gz', 'man3/MPI_Testany.3.gz',
		'man3/MPI_File_iwrite_at.3.gz', 'man3/MPI_Test_cancelled.3.gz',
		'man3/MPI_File_iwrite_shared.3.gz', 'man3/MPI_Testsome.3.gz',
		'man3/MPI_File_open.3.gz', 'man3/MPI_Topo_test.3.gz',
		'man3/MPI_File_preallocate.3.gz', 'man3/MPI_Type_commit.3.gz',
		'man3/MPI_File_read.3.gz', 'man3/MPI_Type_contiguous.3.gz',
		'man3/MPI_File_read_all.3.gz', 'man3/MPI_Type_create_darray.3.gz',
		'man3/MPI_File_read_all_begin.3.gz', 'man3/MPI_Type_create_indexed_block.3.gz',
		'man3/MPI_File_read_all_end.3.gz', 'man3/MPI_Type_create_subarray.3.gz',
		'man3/MPI_File_read_at.3.gz', 'man3/MPI_Type_extent.3.gz',
		'man3/MPI_File_read_at_all.3.gz', 'man3/MPI_Type_free.3.gz',
		'man3/MPI_File_read_at_all_begin.3.gz', 'man3/MPI_Type_get_contents.3.gz',
		'man3/MPI_File_read_at_all_end.3.gz', 'man3/MPI_Type_get_envelope.3.gz',
		'man3/MPI_File_read_ordered.3.gz', 'man3/MPI_Type_hindexed.3.gz',
		'man3/MPI_File_read_ordered_begin.3.gz', 'man3/MPI_Type_hvector.3.gz',
		'man3/MPI_File_read_ordered_end.3.gz', 'man3/MPI_Type_indexed.3.gz',
		'man3/MPI_File_read_shared.3.gz', 'man3/MPI_Type_lb.3.gz',
		'man3/MPI_File_seek.3.gz', 'man3/MPI_Type_size.3.gz',
		'man3/MPI_File_seek_shared.3.gz', 'man3/MPI_Type_struct.3.gz',
		'man3/MPI_File_set_atomicity.3.gz', 'man3/MPI_Type_ub.3.gz',
		'man3/MPI_File_set_errhandler.3.gz', 'man3/MPI_Type_vector.3.gz',
		'man3/MPI_File_set_info.3.gz', 'man3/MPI_UB.3.gz',
		'man3/MPI_File_set_size.3.gz', 'man3/MPI_UNDEFINED.3.gz',
		'man3/MPI_File_set_view.3.gz', 'man3/MPI_UNDEFINED_RANK.3.gz',
		'man3/MPI_File_sync.3.gz', 'man3/MPI_UNEQUAL.3.gz',
		'man3/MPI_File_write.3.gz', 'man3/MPI_Unpack.3.gz',
		'man3/MPI_File_write_all.3.gz', 'man3/MPI_UNSIGNED.3.gz',
		'man3/MPI_File_write_all_begin.3.gz', 'man3/MPI_UNSIGNED_CHAR.3.gz',
		'man3/MPI_File_write_all_end.3.gz', 'man3/MPI_UNSIGNED_LONG.3.gz',
		'man3/MPI_File_write_at.3.gz', 'man3/MPI_UNSIGNED_SHORT.3.gz',
		'man3/MPI_File_write_at_all.3.gz', 'man3/MPI_User_function.3.gz',
		'man3/MPI_File_write_at_all_begin.3.gz', 'man3/MPI_Wait.3.gz',
		'man3/MPI_File_write_at_all_end.3.gz', 'man3/MPI_Waitall.3.gz',
		'man3/MPI_File_write_ordered.3.gz', 'man3/MPI_Waitany.3.gz',
		'man3/MPI_File_write_ordered_begin.3.gz', 'man3/MPI_Waitsome.3.gz',
		'man3/MPI_File_write_ordered_end.3.gz', 'man3/MPI_Wtick.3.gz',
		'man3/MPI_File_write_shared.3.gz', 'man3/MPI_Wtime.3.gz',
		'man3/MPI_Finalize.3.gz', 'man3/MPI_WTIME_IS_GLOBAL.3.gz',
		'man4/CLOG_commtype.4.gz', 'man4/MPE_Draw_line.4.gz',
		'man4/CLOG_cput.4.gz', 'man4/MPE_Draw_logic.4.gz',
		'man4/CLOG_csync.4.gz', 'man4/MPE_Draw_point.4.gz',
		'man4/CLOG_Finalize.4.gz', 'man4/MPE_Draw_points.4.gz',
		'man4/CLOG_get_new_event.4.gz', 'man4/MPE_Draw_string.4.gz',
		'man4/CLOG_get_new_state.4.gz', 'man4/MPE_Fill_circle.4.gz',
		'man4/CLOG_Init.4.gz', 'man4/MPE_Fill_rectangle.4.gz',
		'man4/CLOG_init_buffers.4.gz', 'man4/MPE_Finish_log.4.gz',
		'man4/CLOG_mergelogs.4.gz', 'man4/MPE_Get_mouse_press.4.gz',
		'man4/CLOG_mergend.4.gz', 'man4/MPE_GetTags.4.gz',
		'man4/CLOG_msgtype.4.gz', 'man4/MPE_Iget_mouse_press.4.gz',
		'man4/CLOG_newbuff.4.gz', 'man4/MPE_Initialized_logging.4.gz',
		'man4/CLOG_nodebuffer2disk.4.gz', 'man4/MPE_Init_log.4.gz',
		'man4/CLOG_Output.4.gz', 'man4/MPE_IO_Stdout_to_file.4.gz',
		'man4/CLOG_procbuf.4.gz', 'man4/MPE_Line_thickness.4.gz',
		'man4/CLOG_reclen.4.gz', 'man4/MPE_Log_event.4.gz',
		'man4/CLOG_rectype.4.gz', 'man4/MPE_Log_get_event_number.4.gz',
		'man4/CLOG_reinit_buff.4.gz', 'man4/MPE_Log_receive.4.gz',
		'man4/CLOG_treesetup.4.gz', 'man4/MPE_Log_send.4.gz',
		'man4/MPE_Make_color_array.4.gz',
		'man4/MPE.4.gz', 'man4/MPE_Num_colors.4.gz',
		'man4/MPE_Add_RGB_color.4.gz', 'man4/MPE_Open_graphics.4.gz',
		'man4/MPE_CaptureFile.4.gz', 'man4/MPE_Print_datatype_pack_action.4.gz',
		'man4/MPE_Close_graphics.4.gz', 'man4/MPE_Print_datatype_unpack_action.4.gz',
		'man4/MPE_Comm_global_rank.4.gz', 'man4/MPE_ReturnTags.4.gz',
		'man4/MPE_Counter_create.4.gz', 'man4/MPE_Seq_begin.4.gz',
		'man4/MPE_Counter_free.4.gz', 'man4/MPE_Seq_end.4.gz',
		'man4/MPE_Counter_nxtval.4.gz', 'man4/MPE_Start_log.4.gz',
		'man4/MPE_Decomp1d.4.gz', 'man4/MPE_Stop_log.4.gz',
		'man4/MPE_Describe_event.4.gz', 'man4/MPE_TagsEnd.4.gz',
		'man4/MPE_Describe_state.4.gz', 'man4/MPE_Update.4.gz',
		'man4/MPE_Draw_circle.4.gz' );

	remove_file_list("$OPTIBALIB_DIR", @mpi_arlib_list);
	remove_shlib("$OPTIBALIB_DIR/libtvmpich");
	remove_file_list("/opt/iba/include", @mpi_hdr_list);
	system "rm -rf $ROOT/opt/iba/include/mpi2c++";
	remove_file_list("/opt/iba/bin", "mpicc", "mpiCC", "mpicxx", "mpif77", "mpif90");
	remove_file_list("/opt/iba/man", @mpi_man_list);
	system "rmdir $ROOT/opt/iba/include 2>/dev/null";	# only if empty
	system "rmdir $ROOT/opt/iba/bin 2>/dev/null";	# only if empty
	system "rmdir $ROOT/opt/iba/man/man1 2>/dev/null";	# only if empty
	system "rmdir $ROOT/opt/iba/man/man3 2>/dev/null";	# only if empty
	system "rmdir $ROOT/opt/iba/man/man4 2>/dev/null";	# only if empty
	system "rmdir $ROOT/opt/iba/man 2>/dev/null";	# only if empty
	if ( ! $Skip_UsrLocalSymLinks ) {
		remove_file_list("$USRLOCALLIB_DIR", @mpi_arlib_list);
		remove_file_list("$OLD_USRLOCALLIB_DIR", @mpi_arlib_list);
		remove_oldshlib("$OLD_USRLOCALLIB_DIR/libtvmpich");
		remove_shlib("$USRLOCALLIB_DIR/libtvmpich");
		remove_file_list("/usr/local/include", @mpi_hdr_list);
		system "rm -rf $ROOT/usr/local/include/mpi2c++";
		remove_file_list("/usr/local/bin", "mpicc", "mpiCC", "mpicxx", "mpif77", "mpif90");
		remove_file_list("/usr/local/man", @mpi_man_list);
	}
	# keep this in case we're cleaning up an old install.
	system "rm -rf $ROOT/usr/include/iba/mpi";
	remove_file_list("$LIB_DIR", "libmpich.a", "libmpe.a", "libmpichfarg.a");
	remove_file_list("$OLD_LIB_DIR", "libmpich.a", "libmpe.a", "libmpichfarg.a");
	#remove_file_list("$LIB_DIR", "libfmpich.a", "libpmpich.a");
	#remove_file_list("$OLD_LIB_DIR", "libfmpich.a", "libpmpich.a");
	uninstall_mpi_apps;
	remove_file("$LIB_DIR/.mpidev");
	remove_file("$OLD_LIB_DIR/.mpidev");
	system "rmdir $ROOT$OPTIBALIB_DIR 2>/dev/null";	# remove only if empty
	system "rmdir $ROOT/opt/iba 2>/dev/null";	# remove only if empty
	$ComponentWasInstalled{'mpidev'}=0;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# MPI Source installation

sub available_mpisrc
{
	my $srcdir=$ComponentInfo{'mpisrc'}{'SrcDir'};
	return ( -e "$srcdir/mpi/mpich.tgz" && ! installed_ipath);
}

sub installed_mpisrc
{
	return (-e "$ROOT/usr/local/src/InfiniServMPI/.mpisrc" ||
			-e "$ROOT/opt/iba/src/InfiniServMPI/.mpisrc");
}

# only called if installed_mpisrc is true
sub installed_version_mpisrc
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_mpisrc is true
sub media_version_mpisrc
{
	my $srcdir=$ComponentInfo{'mpisrc'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

# remove the files built from source or installed
# (as listed in .files and .dirs)
# $0 = dirname relative to $ROOT
sub remove_mpisrc_files
{
	my $dirname = $_[0];

	# remove files we installed or user compiled, however do not remove
	# any logs or other files the user may have created
	if ( -d "$ROOT/$dirname" ) {
		#system "cd $ROOT/$dirname/mpich; make clean distclean >/dev/null 2>&1";
		#system "cd $ROOT/$dirname/mpich2 && make clean distclean >/dev/null 2>&1";
		#system "cd $ROOT/$dirname; cat .files 2>/dev/null|xargs rm -f 2>/dev/null";
		#system "cd $ROOT/$dirname; cat .files 2>/dev/null|sort -r|xargs rmdir 2>/dev/null";
		#system "rm -f $ROOT/$dirname/.files 2>/dev/null";
		#system "rmdir $ROOT/$dirname/ 2>/dev/null";
		remove_file("/$dirname/.mpisrc");
		#system "rmdir $ROOT/$dirname/ 2>/dev/null";
		# TBD - mpich distclean still leaves a lot of files around
		# so we just remove it all
		system "rm -rf $ROOT/$dirname/ 2>/dev/null";
	}
}

sub build_mpisrc
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_mpisrc($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_mpisrc
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_mpisrc
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'mpisrc'}{'SrcDir'};

	my $version=media_version_mpisrc();
	chomp $version;
	printf("Installing $ComponentInfo{'mpisrc'}{'Name'} $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'mpisrc'}{'Name'} $version $DBG_FREE for $CUR_OS_VER\n";

	# remove files from old install location
	if ( ! $Skip_UsrLocalSymLinks ) {
		system "rm -f $ROOT/usr/local/src/InfiniServMPI 2>/dev/null";
		remove_mpisrc_files "/usr/local/src/InfiniServMPI";
	}
	check_dir("/opt/iba/src");
	check_dir("/opt/iba/src/InfiniServMPI");
	system "echo > $ROOT/opt/iba/src/InfiniServMPI/.mpisrc";
	system "> $ROOT/opt/iba/src/InfiniServMPI/.mpisrc";
	if ( -e "$srcdir/mpi/mpich.tgz" )
	{
		system("tar xfvz $srcdir/mpi/mpich.tgz --directory $ROOT/opt/iba/src/InfiniServMPI > $ROOT/opt/iba/src/InfiniServMPI/.files");
	}
	if ( -e "$srcdir/mpi/mpich2.tgz" )
	{
		system("tar xfvz $srcdir/mpi/mpich2.tgz --directory $ROOT/opt/iba/src/InfiniServMPI >> $ROOT/opt/iba/src/InfiniServMPI/.files");
	}
	if ( ! $Skip_UsrLocalSymLinks ) {
		check_dir("/usr/local/src");
		system "rm -f $ROOT/usr/local/src/InfiniServMPI 2>/dev/null";
		system "ln -s /opt/iba/src/InfiniServMPI $ROOT/usr/local/src/InfiniServMPI";
	}
	$ComponentWasInstalled{'mpisrc'}=1;
}

sub postinstall_mpisrc
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_mpisrc
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	NormalPrint("Uninstalling $ComponentInfo{'mpisrc'}{'Name'}...\n");

	remove_mpisrc_files "/opt/iba/src/InfiniServMPI";
	if ( ! $Skip_UsrLocalSymLinks ) {
		system "rm -f $ROOT/usr/local/src/InfiniServMPI 2>/dev/null";
		remove_mpisrc_files "/usr/local/src/InfiniServMPI";
	}
	system "rmdir $ROOT/opt/iba/src/ 2>/dev/null";	# remove only if empty
	system "rmdir $ROOT/opt/iba 2>/dev/null";	# remove only if empty
	$ComponentWasInstalled{'mpisrc'}=0;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# uDAPL installation

# autostart functions are per subcomponent
sub IsAutostart2_udapl()
{
	return IsAutostart("udapl");
}
sub autostart_desc_udapl()
{
	return "$ComponentInfo{'udapl'}{'Name'} (udapl)";
}
sub enable_autostart2_udapl()
{
	enable_autostart("udapl");
}
sub disable_autostart2_udapl()
{
	disable_autostart("udapl");
}

sub start_udapl
{
	my $driver_subdir=$ComponentInfo{'udapl'}{'DriverSubdir'};
	start_driver($ComponentInfo{'udapl'}{'Name'}, "udapl", $driver_subdir, "udapl");
}

sub stop_udapl
{
	stop_driver($ComponentInfo{'udapl'}{'Name'}, "udapl", "udapl");
}

sub available_udapl
{
	my $srcdir=$ComponentInfo{'udapl'}{'SrcDir'};
	return ( -e "$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/dapl/libdat.so" && ! installed_ipath);
}

sub installed_udapl
{
	return( -e "$ROOT$LIB_DIR/libdat.so.0.0" || -e "$ROOT$OLD_LIB_DIR/libdat.so.0.0" );
}

# only called if installed_udapl is true
sub installed_version_udapl
{
	if ( -e "$ROOT$BASE_DIR/version" ) {
		return `cat $ROOT$BASE_DIR/version`;
	} else {
		return "";
	}
}

# only called if available_udapl is true
sub media_version_udapl
{
	my $srcdir=$ComponentInfo{'udapl'}{'SrcDir'};
	return `cat "$srcdir/version"`;
}

sub build_udapl
{
	my $osver = $_[0];
	my $debug = $_[1];	# enable extra debug of build itself
	my $build_temp = $_[2];	# temp area for use by build
	my $force = $_[3];	# force a rebuild
	return 0;	# success
}

sub need_reinstall_udapl($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return "no";
}

sub preinstall_udapl
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
	return 0;	# success
}

sub install_udapl
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'udapl'}{'SrcDir'};
	my $driver_subdir=$ComponentInfo{'udapl'}{'DriverSubdir'};

	my $version=media_version_udapl();
	chomp $version;
	printf("Installing $ComponentInfo{'udapl'}{'Name'} $version $DBG_FREE...\n");
	LogPrint "Installing $ComponentInfo{'udapl'}{'Name'} $version $DBG_FREE for $CUR_OS_VER\n";

	check_config_dirs;
	remove_oldshlib("$OLD_LIB_DIR/libdapl");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/dapl/libdapl", "$LIB_DIR/libdapl", "0.0");
	remove_oldshlib("$OLD_LIB_DIR/libdat");
	copy_shlib("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/dapl/libdat", "$LIB_DIR/libdat", "0.0");
	remove_oldarlib("$OLD_LIB_DIR/libdapl.a");
	copy_arlib_file("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/dapl/libdapl.a", "$LIB_DIR/libdapl.a");
	remove_oldarlib("$OLD_LIB_DIR/libdat.a");
	copy_arlib_file("$srcdir/bin/$ARCH/$CUR_OS_VER/lib/$DBG_FREE/dapl/libdat.a", "$LIB_DIR/libdat.a");

	# Copy all dapl include files
	check_dir("/usr/include/iba");
	check_dir("/usr/include/iba/dapl");
	copy_all_data_files("$srcdir/include/dapl", "/usr/include/iba/dapl", "");
	install_conf_file("$ComponentInfo{'udapl'}{'Name'}", "/etc/dat.conf", "$srcdir/config/$DAT_CONF_FILE_SOURCE");
	remove_driver ("iba_udapl_module", $driver_subdir, "silent");
	copy_driver ("udapl_module", $driver_subdir, "verbose");
	# 2.1.1 and before used dapl as name for this script
	remove_startup("dapl");
	install_startup("$srcdir/config", "udapl", "$ComponentInfo{'udapl'}{'Name'}");
	$ComponentWasInstalled{'udapl'}=1;
}

sub postinstall_udapl
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled
}

sub uninstall_udapl
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	my $driver_subdir=$ComponentInfo{'udapl'}{'DriverSubdir'};
	NormalPrint("Uninstalling $ComponentInfo{'udapl'}{'Name'}...\n");
	remove_shlib("$LIB_DIR/libdapl");
	remove_oldshlib("$OLD_LIB_DIR/libdapl");
	remove_shlib("$LIB_DIR/libdat");
	remove_oldshlib("$OLD_LIB_DIR/libdat");
	remove_file("$LIB_DIR/libdapl.a");
	remove_file("$OLD_LIB_DIR/libdapl.a");
	remove_file("$LIB_DIR/libdat.a");
	remove_file("$OLD_LIB_DIR/libdat.a");
	system "rm -rf $ROOT/usr/include/iba/dapl";
	system "rmdir $ROOT/usr/include/iba 2>/dev/null";    # remove only if empty
	remove_conf_file("$ComponentInfo{'udapl'}{'Name'}", "/etc/dat.conf");
	remove_driver ("iba_udapl_module", $driver_subdir, "silent");
	remove_driver ("udapl_module", $driver_subdir, "verbose");
	# 2.1.1 and before used dapl as name for this script
	remove_startup("dapl");
	remove_startup("udapl");
	$ComponentWasInstalled{'udapl'}=0;
}

#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

#
# Copyright (c) 2006 Mellanox Technologies. All rights reserved.
#
# This Software is licensed under one of the following licenses:
#
# 1) under the terms of the "Common Public License 1.0" a copy of which is
#    available from the Open Source Initiative, see
#    http://www.opensource.org/licenses/cpl.php.
#
# 2) under the terms of the "The BSD License" a copy of which is
#    available from the Open Source Initiative, see
#    http://www.opensource.org/licenses/bsd-license.php.
#
# 3) under the terms of the "GNU General Public License (GPL) Version 2" a
#    copy of which is available from the Open Source Initiative, see
#    http://www.opensource.org/licenses/gpl-license.php.
#
# Licensee has the right to choose one of the above licenses.
#
# Redistributions of source code must retain the above copyright
# notice and one of the license notices.
#
# Redistributions in binary form must reproduce both the above copyright
# notice, one of the license notices in the documentation
# and/or other materials provided with the distribution.

#++
# "This software program is available to you under a choice of one of two 
# licenses.  You may choose to be licensed under either the GNU General Public 
# License (GPL) Version 2, June 1991, available at 
# http://www.fsf.org/copyleft/gpl.html, or the Intel BSD + Patent License, 
# the text of which follows:
# 
# "Recipient" has requested a license and Intel Corporation ("Intel") is willing
# to grant a license for the software entitled InfiniBand(tm) System Software 
# (the "Software") being provided by Intel Corporation.

# The following definitions apply to this License: 

# "Licensed Patents" means patent claims licensable by Intel Corporation which 
# are necessarily infringed by the use or sale of the Software alone or when 
# combined with the operating system referred to below.

# "Recipient" means the party to whom Intel delivers this Software.
# "Licensee" means Recipient and those third parties that receive a license to 
# any operating system available under the GNU Public License version 2.0 or 
# later.

# Copyright (c) 1996-2002 Intel Corporation. All rights reserved. 

# The license is provided to Recipient and Recipient's Licensees under the 
# following terms.  

# Redistribution and use in source and binary forms of the Software, with or 
# without modification, are permitted provided that the following conditions are 
# met: 
# Redistributions of source code of the Software may retain the above copyright 
# notice, this list of conditions and the following disclaimer. 

# Redistributions in binary form of the Software may reproduce the above 
# copyright notice, this list of conditions and the following disclaimer in the 
# documentation and/or other materials provided with the distribution. 

# Neither the name of Intel Corporation nor the names of its contributors shall 
# be used to endorse or promote products derived from this Software without 
# specific prior written permission.

# Intel hereby grants Recipient and Licensees a non-exclusive, worldwide, 
# royalty-free patent license under Licensed Patents to make, use, sell, offer 
# to sell, import and otherwise transfer the Software, if any, in source code 
# and object code form. This license shall include changes to the Software that 
# are error corrections or other minor changes to the Software that do not add 
# functionality or features when the Software is incorporated in any version of 
# a operating system that has been distributed under the GNU General Public 
# License 2.0 or later.  This patent license shall apply to the combination of 
# the Software and any operating system licensed under the GNU Public License 
# version 2.0 or later if, at the time Intel provides the Software to Recipient, 
# such addition of the Software to the then publicly available versions of such 
# operating system available under the GNU Public License version 2.0 or later 
# (whether in gold, beta or alpha form) causes such combination to be covered by 
# the Licensed Patents. The patent license shall not apply to any other 
# combinations which include the Software. No hardware per se is licensed 
# hereunder. 

# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL INTEL OR ITS CONTRIBUTORS BE LIABLE FOR ANY 
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
#--
#
#
use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ==========================================================================
# OFED installation, includes ib_stack and OFED supplied ULPs

my $OFED_CONFIG = "$OFED_CONFIG_DIR/openib.conf";
my $default_prefix="/usr";

my $RPMS_SUBDIR = "RPMS";	# within ComponentInfo{'ib_stack'}{'SrcDir'}
my $SRPMS_SUBDIR = "SRPMS";	# within ComponentInfo{'ib_stack'}{'SrcDir'}

# list of components which are part of OFED
# can be a superset or subset of @Components
# ofed_vnic
my @ofed_components = ( "ib_stack", "ofed_mlx4", "ib_stack_dev", "ofed_ipoib",
	   			 "ofed_ib_bonding", 
				 #"ofed_sdp",
				 #"ofed_rds", 
				 "ofed_udapl", "ofed_udaplRest", "ofed_srp",
				 "ofed_srpt", "ofed_iser",
				 "mpi_selector", "mvapich2", "openmpi",
				 "ofed_mpisrc", "mpiRest",
				 "ofed_iwarp", "opensm", "ofed_nfsrdma",
				 "ofed_debug", # must be last real component
);

# information about each component in ofed_components
# Fields:
#	KernelRpms => kernel rpms for given component, in dependency order
#				  These are package packages which are kernel version specific and
#				  will have kernel uname -r in rpm package name.
#				  For a given distro a separate version of each of these rpms
#				  may exist per kernel.  These are always architecture dependent
#	UserRpms => user rpms for given component, in dependency order
#				These are rpms which are not kernel specific.  For a given
#				distro a single version of each of these rpms will
#				exist per distro/arch combination.  Some of these may
#				be architecture independent (noarch).
#	Drivers => used so we can load compat-rdma rpm, then remove drivers for
#				ULPs which are not desired.  Ugly but a workaround for fact
#				that compat-rdma has all the ULP drivers in it
#				specifies drivers and subdirs which are within compat-rdma and
#				specific to each component
#	StartupScript => name of startup script which controls startup of this
#					component
#	StartupParams => list of parameter names in $OFED_CONFIG which control
#					startup of this component (set to yes/no values)
#
# Note KernelRpms are always installed before UserRpms
my %ofed_comp_info = (
	'ib_stack' => {
					KernelRpms => [ "compat-rdma" ], # special case
					UserRpms =>	  [ "ofed-scripts",
									"libibverbs", "libibverbs-utils",
									#"libibcommon",
									"libibumad",
									"libibmad",
									"libibcm",
									"librdmacm", "librdmacm-utils",
									"libmthca",
									"libipathverbs",
									"libehca",
									#"libibcommon-compat",
									#"libibumad-compat",
									"libibumad-compat-2",
									#"libibmad-compat",
									"ibacm",
									"ibpd",
									"libibscif",
									#"infinipath-psm",
# TBD - in future OFED dependency on opensm-libs will go away and can
# move opensm-libs into opensm component
									"opensm-libs",
									"mstflint",
									"ofed-docs",
# TBD move these to a performance tests package
									"perftest", "qperf",
# TBD move these to an OFED Tools package [near end of list]
									"ibutils", "infiniband-diags",
								  ],
					DebugRpms =>  [ "libibverbs-debuginfo",
									#"libibcommon-debuginfo",
									"libibumad-debuginfo",
									"libibmad-debuginfo",
									"libibcm-debuginfo",
									"librdmacm-debuginfo",
									"libmthca-debuginfo",
									"libipathverbs-debuginfo",
									"libehca-debuginfo",
									"qperf-debuginfo",
								  ],
					Drivers => "", 	# we don't need to list these here
							# ib stack startup is controlled by
							# ONBOOT and openibd script
							# other parameters are left enabled so we can
							# manually start the stack
							# those include: RDMA_CM_LOAD, RDMA_UCM_LOAD,
							# MTHCA_LOAD, IPATH_LOAD, QIB_LOAD, KCOPY_LOAD
							# MLX4_EN_LOAD, UCM_LOAD
							# and perhaps future ehca flags
					StartupScript => "openibd",
					StartupParams => [ "ONBOOT" ],
					},
	'ofed_mlx4' => {
					KernelRpms => [ ],
					UserRpms =>	  [ "libmlx4",
									"libmlx4-devel",
								  ],
					DebugRpms =>  [ "libmlx4-debuginfo",
								  ],
					Drivers => "mlx4_ib drivers/infiniband/hw/mlx4
						 		mlx4_core drivers/net/mlx4",
					StartupScript => "openibd",
					StartupParams => [ "MLX4_LOAD" ],
					},
	'ib_stack_dev' => {
					KernelRpms => [ "compat-rdma-devel" ],
					UserRpms =>	  [ "libibverbs-devel",
									"libibverbs-devel-static",
									#"libibcommon-devel", "libibcommon-static",
									"libibumad-devel", "libibumad-static",
									"libibmad-devel", "libibmad-static",
									"libibcm-devel",
									"librdmacm-devel",
									"libmthca-devel-static",
									"libipathverbs-devel",
									"libehca-devel-static",
									#"infinipath-psm-devel",
# TBD - in future OFED dependency on opensm-libs will go away and can
# move opensm-devel and opensm-static into opensm component and perhaps ibsim
									"opensm-devel", "opensm-static",
									"ibsim",
								  ],
					DebugRpms =>  [ "ibsim-debuginfo", ],
					Drivers => "", 	# none
					StartupScript => "",
					StartupParams => [ ],
					},
	'ofed_ipoib' => {
					KernelRpms => [ ],
					UserRpms =>	  [ ],
					DebugRpms =>  [ ],
					Drivers => "ib_ipoib drivers/infiniband/ulp/ipoib",
					StartupScript => "openibd",
					StartupParams => [ "IPOIB_LOAD" ],
					},
	'ofed_ib_bonding' => {
					# code assumes ib-bonding is only Rpm
					KernelRpms => [ "ib-bonding", ],
					UserRpms =>	  [ ],
					DebugRpms =>  [ "ib-bonding-debuginfo", ],
					Drivers => "", # none from compat-rdma
					StartupScript => "",
					StartupParams => [ ],
					},
#	'ofed_sdp' => {
#					KernelRpms => [ ],
#					UserRpms =>	  [ "libsdp", "sdpnetstat",
#									"libsdp-devel", # requires libsdp
#								  ],
#					DebugRpms =>  [ "libsdp-debuginfo", ],
#					Drivers => "ib_sdp drivers/infiniband/ulp/sdp",
#					StartupScript => "openibd",
#					StartupParams => [ "SDP_LOAD" ],
#					},
	'ofed_rds' => {
					KernelRpms => [ ],
					UserRpms =>	  [ "rds-tools", "rds-devel", ],
					DebugRpms =>  [ ],
					Drivers => "rds net/rds",
					StartupScript => "openibd",
					StartupParams => [ "RDS_LOAD" ],
					},
	'ofed_udapl' => {
					KernelRpms => [ ],
					UserRpms =>	  [ "dapl", "dapl-devel",
									"dapl-devel-static",
									"dapl-utils",
								  ],
					DebugRpms =>  [ "dapl-debuginfo", ],
					Drivers => "", # none
					StartupScript => "",
					StartupParams => [ ],
					},
	# ofed install does not install these
	# due to conflicts can't install both this and dapl-2 versions
	'ofed_udaplRest' => {
					KernelRpms => [ ],
					UserRpms =>	  [ ],
					DebugRpms =>  [ ],	# leave in UserRpms not used
					Drivers => "", # none
					StartupScript => "",
					StartupParams => [ ],
					},
	'ofed_srp' => {
					KernelRpms => [ ],
					UserRpms =>	  [ "srptools", ],
					Drivers => "ib_srp drivers/infiniband/ulp/srp",
					DebugRpms =>  [ ],
					StartupScript => "openibd",
					StartupParams => [ "SRP_LOAD" ],
					},
	'ofed_srpt' => {
					KernelRpms => [ ],
					UserRpms =>	  [ ],
					DebugRpms =>  [ ],
					Drivers => "ib_srpt drivers/infiniband/ulp/srpt",
					StartupScript => "openibd",
					StartupParams => [ "SRPT_LOAD" ],
					},
	'ofed_iser' => {
					# starting with 1.5.2rc3 iser no longer needed OFED iscsi
					KernelRpms => [ ],
					UserRpms =>	  [ ],
					DebugRpms =>  [ ],
					Drivers => "ib_iser drivers/infiniband/ulp/iser",
					StartupScript => "openibd",
					StartupParams => [ "ISER_LOAD" ],
					},
	'ofed_nfsrdma' => {
					KernelRpms => [ ],
					#UserRpms =>	  [ "rnfs-utils" ],
					#DebugRpms =>  [ "rnfs-utils-debuginfo" ],
					UserRpms =>	  [ ],
					DebugRpms =>  [ ],
					Drivers => "auth_rpcgss net/sunrpc/auth_gss
								rpcsec_gss_krb5 net/sunrpc/auth_gss
								rpcsec_gss_spkm3 net/sunrpc/auth_gss
								exportfs fs/exportfs
								lockd fs/lockd
								nfs_acl fs/nfs_common
								nfsd fs/nfsd
								nfs fs/nfs
								sunrpc net/sunrpc
								svcrdma net/sunrpc/xprtrdma
								xprtrdma net/sunrpc/xprtrdma",
					StartupScript => "",	# not affected by OFED install
					StartupParams => [ ],
					},
	'mpi_selector' => {
					KernelRpms => [ ],
					UserRpms =>	  [ "mpi-selector" ],
					DebugRpms =>  [ ],
					Drivers => "", # none
					StartupScript => "",
					StartupParams => [ ],
					},
	'mvapich2' => {
					KernelRpms => [ ],
					UserRpms =>	  [ "mvapich2_gcc", "mpitests_mvapich2_gcc" ],
					DebugRpms =>  [ ],
					Drivers => "", # none
					StartupScript => "",
					StartupParams => [ ],
					},
	'openmpi' => {
					KernelRpms => [ ],
					UserRpms =>	  [ "openmpi_gcc", "mpitests_openmpi_gcc" ],
					DebugRpms =>  [ ],
					Drivers => "", # none
					StartupScript => "",
					StartupParams => [ ],
					},
	'ofed_mpisrc' => {	# nothing to build, just copies srpms
					KernelRpms => [ ],
					UserRpms =>	  [ ],
					DebugRpms =>  [ ],
					Drivers => "", # none
					StartupScript => "",
					StartupParams => [ ],
					},
	'mpiRest' => {	# rest of MPI stuff which customer can build via do_build
					# this is included here so we can uninstall
					KernelRpms => [ ],
					UserRpms =>	  [
									"mvapich2_pgi",
									"mvapich2_intel", "mvapich2_pathscale",
									"openmpi_pgi",
									"openmpi_intel", "openmpi_pathscale",
									"mpitests_mvapich2_pgi",
									"mpitests_mvapich2_intel",
									"mpitests_mvapich2_pathscale",
									"mpitests_openmpi_pgi",
									"mpitests_openmpi_intel",
									"mpitests_openmpi_pathscale",
								  ],
					DebugRpms =>  [ ],
					Drivers => "", # none
					StartupScript => "",
					StartupParams => [ ],
					},
	'ofed_iwarp' => {
					KernelRpms => [ ],
					UserRpms =>	  [ "libcxgb3",
									"libcxgb3-devel",
									"libcxgb4",
									"libcxgb4-devel",
									"libnes",
									"libnes-devel-static",
								  ],
					DebugRpms =>  [ "libcxgb3-debuginfo",
									"libcxgb4-debuginfo",
									"libnes-debuginfo",
								  ],
					Drivers => "iw_cxgb3 drivers/infiniband/hw/cxgb3
						 		cxgb3 drivers/net/cxgb3
								iw_cxgb4 drivers/infiniband/hw/cxgb4
						 		cxgb4 drivers/net/cxgb4
						 		iw_nes drivers/infiniband/hw/nes",
					StartupScript => "openibd",
					StartupParams => [ "CXGB3_LOAD", "CXGB4_LOAD", "NES_LOAD" ],
					},
	'opensm' => {
					KernelRpms => [ ],
					UserRpms =>	  [ "opensm", ],
					DebugRpms =>  [ "opensm-debuginfo", ],
					Drivers => "", # none
					StartupScript => "opensmd",
					StartupParams => [ ],
					},
	'ofed_debug' => {
					KernelRpms => [ ],
					UserRpms =>	  [ ],
					DebugRpms =>  [ ],	# listed by comp above
					Drivers => "", # none
					StartupScript => "",
					StartupParams => [ ],
					},
);

# options for building compat-rdma srpm and what platforms they
# are each available for
my %ofed_kernel_ib_options = (
	# build option		# arch & kernels supported on
						# (see util_build.pl for more info on format)
	"--with-core-mod" => "",
	"--with-user_mad-mod" => "",
	"--with-user_access-mod" => "",
	"--with-addr_trans-mod" => "",
	"--with-mthca-mod" => "",
	"--with-mlx4-mod" => "",
	# TBD - disable Connect-X Ethernet NIC driver, sysctl changes undesirable
# TBD - enable this now, the sysctl changes are also done by IPoIB
	"--with-mlx4_en-mod" => "",
	"--with-cxgb3-mod" => "ALL !2\.6\.18\.8-xen.* .*",
	"--with-cxgb4-mod" => "ALL !2\.6\.18\.8-xen.* !2\.6\.18\.19[4-9].*el5.* !2\.6\.18\.2[0-2][0-9].*el5.* !2\.6\.18\.23[0-7].*el5.* .*",
	"--with-nes-mod" => "ALL !2\.6\.18\.8-xen.* .*",
	# ipath_inf has been replaced with qib
	#"--with-ipath_inf-mod" => "X86_64 2\.6\.9-42.* 2\.6\.9-55.* 2\.6\.9-67.* 2\.6\.9-78.* 2\.6\.16\..*-.*-.* 2\.6\.1[7-9].* 2\.6\.2[0-9].*
	#						PPC64 2\.6\.16\..*-.*-.* 2\.6\.1[7-9].* 2\.6\.2[0-9].*",
	# RHEL4u8 2.6.9-[89-999]*
	# RHEL5u2 2.6.18-[84 - 127]*el5*
	# RHEL5u3 2.6.18.[128-163]*el5*
	# RHEL5u4 2.6.18.[164-193]*el5*
	# RHEL5u5 2.6.18.[194-237]*el5*
	# RHEL5u6 2.6.18.[238-273]*el5*
	# RHEL5u7 2.6.18.[>=274]*el5*
	# RHEL6   2.6.32-[>=71]*.el6*
	# RHEL6.1   2.6.32-[>=131].el6*
	# RHEL6.2   2.6.32-[>=220].el6*
	# SLES10sp2 2.6.16.[>=60]*
	# SLES10sp3 2.6.16.60-0.[>=54]*
	# SLES10sp4 2.6.16.60-0.[>=85]*
	# SLES11 2.6.27.*
	# SLES11sp1 2.6.32.*
	# SLES11sp2 3.0.*-*
	"--with-qib-mod" => "X86_64 !2\.6\.18\.8-xen.* 2\.6\.18-[0-9]*\..*el5.* 2\.6\.16\.[6-9][0-9]-.*-.* 2\.6\.27\..*-.* 2\.6\.3[2789]\..*-.* 2\.6\.9-89\..* 2\.6\.9-9[0-9]\..* 2\.6\.9-[1-9][0-9][0-9]\..* 2\.6\.32-.*\.el6.* 3\.0\..*-.* 3\.10\..* 3\.12\..*",
	"--with-kcopy-mod" => "X86_64 !2\.6\.18\.8-xen.* 2\.6\.18-[0-9]*\..*el5.* 2\.6\.16\.[6-9][0-9]-.*-.* 2\.6\.27\..*-.* 2\.6\.3[2789]\..*-.* 2\.6\.9-89\..* 2\.6\.9-9[0-9]\..* 2\.6\.9-[1-9][0-9][0-9]\..* 2\.6\.32-.*\.el6.* 3\.0\..*-.* 3\.10\..* 3\.12\..*",
	# TBD - disable ehca build, causing PPC build failures
	"--with-ehca-mod" => "NONE",
	#"--with-ehca-mod" => "PPC 2\.6\.1[6-9].* 2\.6\.2[0-9].* 2\.6\.9-67.* 2\.6\.9-78.* 2\.6\.3[0-2].*
	#						PPC64 2\.6\.1[6-9].* 2\.6\.2[0-9].* 2\.6\.9-67.* 2\.6\.9-78.*" 2\.6\.3[0-2].*",
	"--with-ipoib-mod" => "",
	#"--with-sdp-mod" => "",
	"--with-srp-mod" => "",
	# fixed up in init_ofed_rpm_info
	#"--with-srp-target-mod" => "ALL 2\.6\.2[7-9].* 2\.6\.3[0-2].*",
		# only SLES10 and RHEL5
	#"--with-iser-mod" => "ALL 2\.6\.9-42.* 2\.6\.9-55.* 2\.6\.9-67.* 2\.6\.9-78.* 2\.6\.16\.[0-9].*-[A-Za-z0-9.]* 2\.6\..*\.el5.*",
	"--with-iser-mod" => "ALL !2\.6\..*\.el6.* 2\.6\.3[0-2].* 2\.6\.18-164.*",
	# RHEL6.1 and newer  and SLES11sp1
	#"--with-nfsrdma-mod" => "ALL !2\.6\.32-[7-9][0-9]\..* !2\.6\.32-1[0-2][0-9]\..* !2\.6\.32-130\..* !2\.6\.32-358\..* !2\.6\.32-365\..* !2\.6\.32-431\..* !2\.6\.32-504\..* 2\.6\.3[0-9]\.* 2\.6\.40.* !3\.0.* !3\.10\..*",
	#"--with-nfsrdma-mod" => "",
	#"--with-rds-mod" => "ALL !2\.6\.9.* .*",
	# there is no overhead associated with always building this
	" --with-madeye-mod" => "",
);

# all kernel srpms
# these are in the order we must build/process them to meet basic dependencies
my @ofed_kernel_srpms = ( 'compat-rdma', 'ib-bonding' );

# all user space srpms
# these are in the order we must build/process them to meet basic dependencies
my @ofed_user_srpms = (
		"ofed-scripts", "libibverbs", "libmthca", "libmlx4", "libcxgb3",
	   	"libcxgb4", "libnes", "libipathverbs", "libehca",
	   	#"libibcommon",
	   	"libibumad",
		"libibmad", "libibcm", "librdmacm", 
		#"libsdp", 
		"opensm", "ibsim",
		#"libibcommon-compat", 
		#"libibumad-compat", 
		"libibumad-compat-2", 
		#"libibmad-compat",
		#"infinipath-psm",
		"ibacm", "perftest", "mstflint","ibpd","libibscif",
		#"sdpnetstat",
		"srptools", "rds-tools", 
		"ibutils", "infiniband-diags", "qperf",
		"ofed-docs", "mpi-selector", "dapl",
 		"mvapich2", "openmpi",
		# "mpitests", # handled by do_build as if build from mpi source itself
		# "rnfs-utils"
);

# rpms not presently automatically built
my @ofed_other_srpms = ( );

my @ofed_srpms = ( @ofed_kernel_srpms, @ofed_user_srpms, @ofed_other_srpms );

# This provides information for all kernel and user space srpms
# Fields:
#	Available => indicate which platforms each srpm can be built for
#	Available32 => indicate which platforms each srpm can be built 32 bit for
#				64 bit OS.
#	PostReq => after building each srpm, some of its generated rpms will
#				need to be installed so that later srpms will build properly
#				this lists all the rpms which may be needed by subsequent srpms
#	Builds => list of kernel and user rpms built from each srpm
#				caller must know if user/kernel rpm is expected
#	PartOf => ofed_components this srpm is part of
#			  this is filled in at runtime based on ofed_comp_info
#			  cross referenced to Builds
#	BuildPrereq => OS prereqs needed to build this srpm
#				List in the form of "rpm version mode" for each.
#				version is optional, default is "any"
#				mode is optional, default is "any"
#				Typically mode should be "user" for libraries
#				See rpm_is_installed for more information about mode
#	Build32Prereq => OS prereqs needed to build 32 bit version of this srpm
#				List in the form of "rpm version mode" for each.
#				version is optional, default is "any"
#				mode is optional, default is "any"
#				Typically mode should be "user32" for libraries
#				See rpm_is_installed for more information about mode
my %ofed_srpm_info = (
	"compat-rdma" =>	{ Available => "",
					  Available32 => "NONE",
					  Builds => "compat-rdma compat-rdma-devel",
					  # compat-rdma-devel needs compat-rdma, compat-rdma-devel is
					  # needed by vnic and srp build
					  PostReq => "compat-rdma compat-rdma-devel",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	#"ib-bonding" =>	{ Available => "ALL 2\.6\.9-67.* 2\.6\.9-78.* 2\.6\.9-89.* 2\.6\.16\.[0-9.]*-[0-9.]*-[A-Za-z0-9.]* 2\.6\.18-128.* 2\.6\.18-164.* 2\.6\..*fc6.*",
	"ib-bonding" =>	{ Available => "ALL 2\.6\.9-67.* 2\.6\.9-78.* 2\.6\.9-89.* 2\.6\.16\.[0-9.]*-[0-9.]*-[A-Za-z0-9.]* 2\.6\..*el5.* 2\.6\..*fc6.*",
					  Available32 => "NONE",
					  Builds => "ib-bonding ib-bonding-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"ofed-scripts" => { Available => "",
					  Available32 => "NONE",
					  Builds => "ofed-scripts",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"libibverbs" =>	{ Available => "",
					  Available32 => "",
					  Builds => "libibverbs libibverbs-devel libibverbs-devel-static libibverbs-utils libibverbs-debuginfo",
					  PostReq => "libibverbs libibverbs-devel libibverbs-devel-static",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [ 'gcc 3.3.3', 'glibc-devel any user', 'libstdc++ any user' ],
					  Build32Prereq => [ 'gcc 3.3.3', 'glibc-devel any user', 'libstdc++ any user' ],
					},
	"libmthca" =>	{ Available => "",
					  Available32 => "",
					  Builds => "libmthca libmthca-devel-static libmthca-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"libmlx4" =>	{ Available => "",
					  Available32 => "",
					  Builds => "libmlx4 libmlx4-devel libmlx4-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"libcxgb3" => 	{ Available => "$ofed_kernel_ib_options{'--with-cxgb3-mod'}",
					  Available32 => "$ofed_kernel_ib_options{'--with-cxgb3-mod'}",
					  Builds => "libcxgb3 libcxgb3-devel libcxgb3-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"libcxgb4" => 	{ Available => "$ofed_kernel_ib_options{'--with-cxgb4-mod'}",
					  Available32 => "$ofed_kernel_ib_options{'--with-cxgb4-mod'}",
					  Builds => "libcxgb4 libcxgb4-devel libcxgb4-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"libnes" => 	{ Available => "$ofed_kernel_ib_options{'--with-nes-mod'}",
					  Available32 => "$ofed_kernel_ib_options{'--with-nes-mod'}",
					  Builds => "libnes libnes-devel-static libnes-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"libipathverbs" => { Available => "$ofed_kernel_ib_options{'--with-qib-mod'}",
					  Available32 => "$ofed_kernel_ib_options{'--with-qib-mod'}",
					  Builds => "libipathverbs libipathverbs-devel libipathverbs-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"libehca" =>	{ Available => "$ofed_kernel_ib_options{'--with-ehca-mod'}",
					  Available32 => "$ofed_kernel_ib_options{'--with-ehca-mod'}",
					  Builds => "libehca libehca-devel-static libehca-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
#	"libibcommon" => { Available => "",
#					  Available32 => "",
#					  Builds => "libibcommon libibcommon-devel libibcommon-static libibcommon-debuginfo",
#					  PostReq => "libibcommon libibcommon-devel",
#					  PartOf => "", # filled in at runtime
#					  BuildPrereq => [ 'libtool any user' ],
#					  Build32Prereq => [ 'libtool any user' ],
#					},
	"libibumad" =>	{ Available => "",
					  Available32 => "",
					  Builds => "libibumad libibumad-devel libibumad-static libibumad-debuginfo",
					  PostReq => "libibumad libibumad-devel",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [ 'libtool any user' ],
					  Build32Prereq => [ 'libtool any user' ],
					},
	"libibmad" =>	{ Available => "",
					  Available32 => "",
					  Builds => "libibmad libibmad-devel libibmad-static libibmad-debuginfo",
					  PostReq => "libibmad libibmad-devel",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [ 'libtool any user' ],
					  Build32Prereq => [ 'libtool any user' ],
					},
#	"libibcommon-compat" => { Available => "",
#					  Available32 => "",
#					  Builds => "libibcommon-compat",
#					  PostReq => "libibcommon-compat",
#					  PartOf => "", # filled in at runtime
#					  BuildPrereq => [ 'libtool any user' ],
#					  Build32Prereq => [ 'libtool any user' ],
#					},
#	"libibumad-compat" =>   { Available => "",
#					  Available32 => "",
#					  Builds => "libibumad-compat",
#					  PostReq => "libibumad-compat",
#					  PartOf => "", # filled in at runtime
#					  BuildPrereq => [],
#					  Build32Prereq => [],
#					},
	"libibumad-compat-2" =>   { Available => "",
					  Available32 => "",
					  Builds => "libibumad-compat-2",
					  PostReq => "libibumad-compat-2",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
#	"libibmad-compat" =>    { Available => "",
#					  Available32 => "",
#					  Builds => "libibmad-compat",
#					  PostReq => "libibmad-compat",
#					  PartOf => "", # filled in at runtime
#					  BuildPrereq => [ 'libtool any user' ],
#					  Build32Prereq => [ 'libtool any user' ],
#					},
	"libibcm" =>	{ Available => "",
					  Available32 => "",
					  Builds => "libibcm libibcm-devel libibcm-debuginfo",
					  PostReq => "libibcm libibcm-devel",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"ibacm" =>		{ Available => "",
					  Available32 => "NONE",
					  Builds => "ibacm",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"librdmacm" =>	{ Available => "",
					  Available32 => "",
					  Builds => "librdmacm librdmacm-devel librdmacm-debuginfo librdmacm-utils",
					  PostReq => "librdmacm librdmacm-devel",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"libibscif" =>	{ Available => "",
					  Available32 => "",
					  Builds => "libibscif",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"ibpd" =>		{ Available => "",
					  Available32 => "",
					  Builds => "ibpd",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
#	"libsdp" =>		{ Available => "",
#					  Available32 => "",
#					  Builds => "libsdp libsdp-devel libsdp-debuginfo",
#					  PostReq => "",
#					  PartOf => "", # filled in at runtime
#					  BuildPrereq => [],
#					  Build32Prereq => [],
#					},
	"opensm" =>		{ Available => "",
					  Available32 => "",
					  Builds => "opensm-libs opensm opensm-devel opensm-static opensm-debuginfo",
					  PostReq => "opensm-libs opensm-devel",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [ 'bison', 'flex' ],
					  Build32Prereq => [ 'bison', 'flex' ],
					},
	"ibsim" =>		{ Available => "",
					  Available32 => "NONE",
					  Builds => "ibsim ibsim-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"compat-dapl" =>	{ Available => "",
					  Available32 => "",
					  # TBD - are these all still built?
					  Builds => "compat-dapl compat-dapl-devel compat-dapl-devel-static compat-dapl-utils compat-dapl-debuginfo",
					  PostReq => "compat-dapl compat-dapl-devel compat-dapl-devel-static",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"dapl" =>	{ Available => "",
					  Available32 => "",
					  Builds => "dapl dapl-devel dapl-devel-static dapl-utils dapl-debuginfo",
					  PostReq => "dapl dapl-devel dapl-devel-static",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"perftest" =>	{ Available => "",
					  Available32 => "NONE",
					  Builds => "perftest",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"mstflint" =>	{ Available => "",
					  Available32 => "NONE",
					  Builds => "mstflint",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [ 'zlib-devel any user', 'libstdc++ any user', 'libstdc++-devel any user', 'gcc-c++' ],
					  Build32Prereq => [ 'zlib-devel any user', 'libstdc++ any user', 'libstdc++-devel any user', 'gcc-c++' ],
					},
#	"sdpnetstat" =>	{ Available => "",
#					  Available32 => "NONE",
#					  Builds => "sdpnetstat",
#					  PostReq => "",
#					  PartOf => "", # filled in at runtime
#					  BuildPrereq => [],
#					  Build32Prereq => [],
#					},
	"srptools" =>	{ Available => "",
					  Available32 => "NONE",
					  Builds => "srptools",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"rds-tools" =>	{ Available => "$ofed_kernel_ib_options{'--with-rds-mod'}",
					  Available32 => "NONE",
					  Builds => "rds-tools rds-devel",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"ibutils" =>	{ Available => "",
					  Available32 => "NONE",
					  Builds => "ibutils",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [ 'tcl 8.4', 'tcl-devel 8.4', 'tk', 'libstdc++-devel any user' ],
					  Build32Prereq => [],
					},
	"infiniband-diags" => { Available => "",
					  Available32 => "NONE",
					  Builds => "infiniband-diags",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"qperf" =>		{ Available => "",
					  Available32 => "NONE",
					  Builds => "qperf qperf-debuginfo",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"ofed-docs" =>	{ Available => "",
					  Available32 => "NONE",
					  Builds => "ofed-docs",
					  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [],
					  Build32Prereq => [],
					},
	"mpi-selector" => { Available => "",
					  Available32 => "NONE",
					  Builds => "mpi-selector",
					  PostReq => "mpi-selector",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [ 'tcsh' ],
					  Build32Prereq => [ 'tcsh' ],
					},
	"mvapich2" =>	{ Available => "",
					  Available32 => "NONE",
						# mpitests are built by do_mvapich2_build
		 			  Builds => "mvapich2_gcc mpitests_mvapich2_gcc",
		 			  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [ 'libstdc++ any user',
					  				   'libstdc++-devel any user',
									   'sysfsutils any user',
									   'sysfsutils-devel any user',
					  				   'g77', 'libgfortran any user'
								   	],
					  Build32Prereq => [],
					},
	"openmpi" =>	{ Available => "",
					  Available32 => "NONE",
						# mpitests are built by do_openmpi_build
		 			  Builds => "openmpi_gcc mpitests_openmpi_gcc",
		 			  PostReq => "",
					  PartOf => "", # filled in at runtime
					  BuildPrereq => [ 'libstdc++ any user',
					  				   'libstdc++-devel any user',
					  				   'g77', 'libgfortran any user',
									   'binutils-devel'
								   	],
					  Build32Prereq => [],
					},
	# mpitests built via do_build scripts used for mvapich1/2, and openmpi
	# "mpitests" =>	{ Available => "",
	#				  Available32 => "NONE",
	#	 			  Builds => RPMS depend on MPI and CC option supplied
	#	 			  PostReq => "",
	#				  PartOf => "", # filled in at runtime
	#				  BuildPrereq => [],
	#				  Build32Prereq => [],
	#				},
	
	#"rnfs-utils" =>	{ Available => "$ofed_kernel_ib_options{'--with-nfsrdma-mod'}",
	#				  Available32 => "NONE",
	#				  Builds => "rnfs-utils rnfs-utils-debuginfo",
	#				  PostReq => "",
	#				  PartOf => "", # filled in at runtime
	#				  BuildPrereq => [],
	#				  Build32Prereq => [],
	#				},
);

# This provides information for all kernel and user space rpms
# This is built based on information in ofed_srpm_info and ofed_comp_info
# Fields:
#	Available => boolean indicating if rpm can be available for this platform
#	Available32 => boolean indicating if 32 bit on 64 bit OS version of rpm
#				can be available for this platform
#	Parent => srpm which builds this rpm
#	PartOf => space separate list of components this rpm is part of
#	Mode => mode of rpm (kernel or user)
my %ofed_rpm_info = ();
my @ofed_rpms = ();

# RPMs from previous versions of OFED
# as new RPMs are added above for present release, also add them here
my @ofed1_2_5_and_1_3_release_rpms = (
			"compat-rdma",
			"ofed-scripts",
 			"libibverbs", "libibverbs-utils", "libibverbs-debuginfo",
			"libibcommon", "libibcommon-debuginfo",
			"libibumad", "libibumad-debuginfo",
			"libibmad", "libibmad-debuginfo",
			"libibcm", "libibcm-debuginfo",
			"librdmacm", "librdmacm-utils", "librdmacm-debuginfo",
			"libmlx4", "libmlx4-debuginfo",
			"libmthca", "libmthca-debuginfo",
			"libipathverbs", "libipathverbs-debuginfo",
			"libehca", "libehca-debuginfo",
			"libosmcomp", "libosmvendor", "libopensm", 
			"opensm-libs",
			"mstflint", "tvflash",
			"ofed-docs",
			"perftest", "qperf", "qperf-debuginfo",
			"ibutils", "infiniband-diags", "openib-diags",

			"compat-rdma-devel",
			"libibverbs-devel", "libibverbs-devel-static",
			"libibcommon-devel", "libibcommon-static",
			"libibumad-devel", "libibumad-static",
			"libibmad-devel", "libibmad-static",
			"libibcm-devel",
			"librdmacm-devel",
			"libmlx4-devel-static",
			"libmthca-devel-static",
			"libipathverbs-devel",
			"libehca-devel-static",
			"opensm-devel", "opensm-static",
			"libosmcomp-devel", "libosmvendor-devel", "libopensm-devel",
			"ibsim", "ibsim-debuginfo",
			"ib-bonding", "ib-bonding-debuginfo", "ipoibtools",
			"libsdp", "libsdp-debuginfo", "sdpnetstat",
			"libsdp-devel",
			#"rds-tools",
			"dapl", "dapl-devel", "dapl-devel-static",
			"dapl-utils", "dapl-debuginfo",

			# redhat renamed 1.2.5 OFED as follows:
			"compat-dapl-devel-1.2.5", "compat-dapl-static-1.2.5",
			"compat-dapl-1.2.5",
			"dapl-static", "dapl-devel", "dapl",
 			"librdmacm-static", "libibcm-static", "libibverbs-static",
			"libmlx4-static", "libmthca-static", "libipathverbs-static",
			"libcxgb3-static", "libcxgb4-static", "libnes-static",

			"srptools", "ibvexdmtools", "qlvnictools", "mpi-selector",
			"mvapich2", "mvapich2_gcc", "mvapich2_pgi", "mvapich2_intel",
			"mvapich2_pathscale",
			"openmpi", "openmpi_gcc", "openmpi_pgi", "openmpi_intel",
			"openmpi_pathscale",
			"mpitests",
			"mpitests_mvapich2",
			"mpitests_mvapich2_gcc", "mpitests_mvapich2_pgi",
			"mpitests_mvapich2_intel", "mpitests_mvapich2_pathscale",
			"mpitests_openmpi",
			"mpitests_openmpi_gcc", "mpitests_openmpi_pgi",
			"mpitests_openmpi_intel", "mpitests_openmpi_pathscale",
			"libcxgb3", "libcxgb3-debuginfo", "libcxgb3-devel",
			"libcxgb4", "libcxgb4-debuginfo", "libcxgb4-devel",
			"libnes", "libnes-debuginfo", "libnes-devel-static", "libnes-devel",
			"opensm", "opensm-debuginfo",
);
# new ones since 1.3
my @ofed1_4_release_rpms = (
			"compat-dapl", "compat-dapl-devel", "compat-dapl-devel-static",
		   	"compat-dapl-utils", "compat-dapl-debuginfo",
			"libmlx4-devel",
		   	# "tgt-generic", "tgt",
			"scsi-target-utils", 
			"tvflash-debuginfo",
			# a few which RHEL 5.3 chose to rename
			"compat-dapl-static", "mpitests-mvapich2",
			"mpitests-openmpi",
);
my @ofed1_4_1_release_rpms = (
			"rnfs-utils", "rnfs-utils-debuginfo",
);
my @ofed1_5_2_release_rpms = (
			"ibacm-devel", "ibacm", "infinipath-psm", "infinipath-psm-devel",
);
# A list of the OFED rpms that PathScale/QLogic may have distributed in previous
# releases.  Omits rpms already listed above
my @qlgc_old_rpms = ( "rhel4-ofed-fixup", "qlogic-mpi-register",
			"infinipath-kernel", "infinipath", "infinipath-libs",
			"infinipath-libs-32bit", "infinipath-doc", "infinipath-devel",
			"mpi-frontend", "mpi-benchmark", "mpi-libs", "mpi-libs-32bit",
			"mpi-doc", "mpi-devel", "tmi", 
			"openmpi_pgi_qlc", "openmpi_pathscale_qlc", "openmpi_intel_qlc",
			"openmpi_gcc_qlc",
			"mvapich2_pgi_qlc", "mvapich2_pathscale_qlc", "mvapich2_intel_qlc",
			"mvapich2_gcc_qlc",
			"mpitests_openmpi_pgi_qlc", "mpitests_openmpi_pathscale_qlc",
			"mpitests_openmpi_intel_qlc", "mpitests_openmpi_gcc_qlc",
			"mpitests_mvapich2_pgi_qlc", "mpitests_mvapich2_pathscale_qlc",
			"mpitests_mvapich2_intel_qlc", "mpitests_mvapich2_gcc_qlc",
			"mpi-noship-tests",
			);
my @sles11_ofed_rpms = (
			# these are in SLES11 and are renames of some OFED 1.4 rpms
			"libcxgb3-rdmav2", "libcxgb4-rdmav2",
		   	"libmthca-rdmav2", "libmlx4-rdmav2",
			"libcxgb3-rdmav2-devel", "libcxgb4-rdmav2-devel",
		   	"libmthca-rdmav2-devel", "libmlx4-rdmav2-devel",
			"libibcommon1", "libibumad1", "libibmad1",
		   	"ofed-1.4.0", "ofed-1.4.1", "ofed-1.4.2", "ofed-1.5.2",
			"ofa",
			"libnes-rdmav2", "libamso-rdmav2",
			"libnes-rdmav2-devel", "libamso-rdmav2-devel",
			"ofed-doc", "ofed-kmp", "ofed-kmp-smp", "ofed-kmp-default",
		   	"ofed-kmp-debug", "ofed-kmp-kdump",
		   	"ofed-cxgb3-NIC-kmp-smp", "ofed-cxgb3-NIC-kmp-default",
		   	"ofed-cxgb3-NIC-kmp-debug", "ofed-cxgb3-NIC-kmp-kdump",
		   	"ofed-cxgb4-NIC-kmp-smp", "ofed-cxgb4-NIC-kmp-default",
		   	"ofed-cxgb4-NIC-kmp-debug", "ofed-cxgb4-NIC-kmp-kdump",
			# given naming convention, these MIGHT appear in SLES11 at some time
			"libipathverbs-rdmav2", "libehca-rdmav2",
			"libipathverbs-rdmav2-devel", "libehca-rdmav2-devel",
			);
my @sles12_ofed_rpms = (
			#  these are in SLES12
			"libpsm_infinipath1", "libibverbs-runtime", "libibverbs1", "librdmacm1-32bit",
			"librdmacm1", "libibdm1", "opensm-libs3", "patterns-sles-ofed", "libibcm1",
			);
my @prev_release_rpms = (
			@ofed1_2_5_and_1_3_release_rpms, @ofed1_4_release_rpms,
			@ofed1_4_1_release_rpms, @ofed1_5_2_release_rpms,
			@qlgc_old_rpms, @sles11_ofed_rpms, @sles12_ofed_rpms,
			"rdma-ofa-agent", "libibumad3", "libibmad5",
			"mpich_mlx", "ibtsal", "openib", "opensm", "opensm-devel", "opensm-libs",
			"mpi_osu", "mpi_ncsa", "thca", "ib-osm", "osm", "diags", "ibadm", "ib-diags",
			"ibgdiag", "ibdiag", "ib-management",
			"ib-verbs", "ib-ipoib", "ib-cm", "ib-sdp", "ib-dapl", "udapl",
			"udapl-devel", "libdat", "libibat", "ib-kdapl", "ib-srp",
			"ib-srp_target", "oiscsi-iser-support", "ofed-docs", "ofed-scripts"
);

# RPMs from OFED in Redhat
my @redhat_rpms = (
			"udapl", "udapl-devel", "dapl", "dapl-devel", "libibcm",
			"libibcm-devel", "libibcommon", "libibcommon-devel",
			"libibmad", "libibmad-devel", "libibumad", "libibumad-devel",
			"libibverbs", "libibverbs-devel", "libibverbs-utils",
			"libipathverbs", "libipathverbs-devel", "libmthca",
			"libmthca-devel", "libmlx4", "libmlx4-devel",
			"libehca", "libehca-devel",
			"libsdp", "librdmacm", "librdmacm-devel", "librdmacm-utils",
			"openib",
			"openib-diags", "openib-mstflint", "openib-perftest",
			"openib-srptools", "openib-tvflash",
			"openmpi", "openmpi-devel", "openmpi-libs", "openmpi11",
		   	"opensm", "opensm-devel", "opensm-libs", "compat-opensm-libs",
			"ibutils", "ibutils2", "ibutils-devel", "ibutils2-devel", "ibutils-libs",
			"rdma",
			"compat-openmpi", "compat-openmpi-psm",
		   	"mvapich2-psm", "mvapich2-psm-devel", "mpitests-mvapich2-psm",
		   	"openmpi-psm", "openmpi-psm-devel", "mpitests-openmpi-psm",
);

# RPMs from OFED in SuSE
my @suse_rpms = (
			"libamso", "libamso-devel", "dapl2", "dapl2-devel", "mvapich2",
		   	"mvapich2-devel"
);

my %ofed_autostart_save = ();
# ==========================================================================
# OFED ib_stack build in prep for installation

# based on %ofed_srpm_info{}{'Available' or 'Available32'} determine if the given SRPM is
# buildable and hence available on this CPU for $osver combination
# "user" and kernel rev values for mode are treated same
sub available_srpm($$$)
{
	my $srpm = shift();
	# $mode can be user32 or any other value,
	# only used to select Available or Available32
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
	my $osver = shift();
	my $avail;

	if ( "$mode" eq "user32" ) {
		$avail="Available32";
		if ( "$target_cpu32" eq "" ) {
			return 0;
		}
	} else {	# must be "user" or kernel rev
		$avail="Available";
	}

	DebugPrint("checking $srpm $mode $osver against '$ofed_srpm_info{$srpm}{$avail}'\n");
	return arch_kernel_is_allowed($osver, $ofed_srpm_info{$srpm}{$avail});
}

# initialize ofed_rpm_info based on specified osver for present system
sub init_ofed_rpm_info($)
{
	my $osver = shift();

	# compute mand_target_cpu32 and initialize target_cpu32
	init_cpu32();

	# srp target kernel module does not build for kernels older than 3.5.
#	if ( "$CUR_DISTRO_VENDOR" eq "SuSE" ) {
#		# available for SLES10 and 11
#		$ofed_kernel_ib_options{'--with-srp-target-mod'}="";
#	} elsif ( "$CUR_DISTRO_VENDOR" eq "redhat" && "$CUR_VENDOR_VER" eq "ES5") {
#		# available for RHEL5.3 and newer (2.6.18-128 and newer)
#		$ofed_kernel_ib_options{'--with-srp-target-mod'}="ALL 2\.6\.18-12[8-9]\..*el5.* 2\.6\.18-1[3-9][0-9]\..*el5.*";
#	} else {
#		# available for newer kernel.org
#		$ofed_kernel_ib_options{'--with-srp-target-mod'}="ALL 2\.6\.2[7-9].* 2\.6\.3[0-2].*";
#	}

	%ofed_rpm_info = ();	# start fresh

	# first get information based on all srpms
	foreach my $srpm ( @ofed_srpms ) {
		my @package_list = split /[[:space:]]+/, $ofed_srpm_info{$srpm}{'Builds'};
		foreach my $package ( @package_list ) {
			next if ( "$package" eq '' );	# handle leading spaces
			$ofed_rpm_info{$package}{'Available'} = available_srpm($srpm, "user", $osver);
			$ofed_rpm_info{$package}{'Available32'} = available_srpm($srpm, "user32", $osver);
			$ofed_rpm_info{$package}{'Parent'} = "$srpm";
		}
	}

	# now fill in PartOf and Mode based on all components
	# allow for the case where a package could be part of more than 1 component
	# however assume User vs Kernel is consistent
	foreach my $comp ( @ofed_components ) {
		foreach my $package ( @{ $ofed_comp_info{$comp}{'UserRpms'}} ) {
			$ofed_rpm_info{$package}{'PartOf'} .= " $comp";
			$ofed_rpm_info{$package}{'Mode'} = "user";
		}
		foreach my $package ( @{ $ofed_comp_info{$comp}{'KernelRpms'}} ) {
			$ofed_rpm_info{$package}{'PartOf'} .= " $comp";
			$ofed_rpm_info{$package}{'Mode'} = "kernel";
		}
		foreach my $package ( @{ $ofed_comp_info{$comp}{'DebugRpms'}} ) {
			$ofed_rpm_info{$package}{'PartOf'} .= " ofed_debug";
			# this is the only debuginfo with kernel rev in its name
			if ( "$package" eq "ib-bonding-debuginfo" ) {
				$ofed_rpm_info{$package}{'Mode'} = "kernel";
			} else {
				$ofed_rpm_info{$package}{'Mode'} = "user";
			}
		}
	}
	@ofed_rpms = ( keys %ofed_rpm_info );	# list of all rpms
	# fixup Available for those in "*Rest" but not in ofed_srpm_info{*}{Builds}
	foreach my $package ( @ofed_rpms ) {
		if ("$ofed_rpm_info{$package}{'Available'}" eq "" ) {
			$ofed_rpm_info{$package}{'Available'}=0;
		}
		if ("$target_cpu32" eq "" || "$ofed_rpm_info{$package}{'Available32'}" eq "" ) {
			$ofed_rpm_info{$package}{'Available32'}=0;
		}
	}

	# -debuginfo is not presently supported on SuSE or Centos
	# also .rpmmacros overrides can disable debuginfo availability
	if ( "$CUR_DISTRO_VENDOR" eq "SuSE"
		|| ! rpm_will_build_debuginfo()) {
		foreach my $package ( @ofed_rpms ) {
			if ($package =~ /-debuginfo/) {
				$ofed_rpm_info{$package}{'Available'} = 0;
				$ofed_rpm_info{$package}{'Available32'} = 0;
			}
		}
	}
	# -debuginfo, opensm and some utils not supported for 32 bit builds
	foreach my $package ( @ofed_rpms ) {
		if ($package =~ /-debuginfo/
			|| "$package" eq "opensm"
			|| "$package" eq "librdmacm-utils" 
			|| "$package" eq "libibverbs-utils"
			|| "$package" eq "compat-dapl-utils"
			|| "$package" eq "dapl-utils") {
			$ofed_rpm_info{$package}{'Available32'} = 0;
		}
	}

	# every package must be part of some component (could be a dummy component)
	foreach my $package ( @ofed_rpms ) {
		if ( "$ofed_rpm_info{$package}{'PartOf'}" eq "" ) {
			LogPrint "$package: Not PartOf anything\n";
		}
	}

	# build $ofed_srpm_info{}{PartOf}
	foreach my $srpm ( @ofed_srpms ) {
		$ofed_srpm_info{$srpm}{'PartOf'} = '';
	}
	foreach my $package ( @ofed_rpms ) {
		my @complist = split /[[:space:]]+/, $ofed_rpm_info{$package}{'PartOf'};
		my $srpm = $ofed_rpm_info{$package}{'Parent'};
		foreach my $comp ( @complist ) {
			next if ( "$comp" eq '' );	# handle leading spaces
			if ( " $ofed_srpm_info{$srpm}{'PartOf'} " !~ / $comp / ) {
				$ofed_srpm_info{$srpm}{'PartOf'} .= " $comp";
			}
		}
	}
	# fixup special case for compat-rdma, its part of all ofed comp w/ Drivers
	my $srpm = $ofed_rpm_info{'compat-rdma'}{'Parent'};
	foreach my $comp ( @ofed_components ) {
		if ("$ofed_comp_info{$comp}{'Drivers'}" ne "" ) {
			if ( " $ofed_srpm_info{$srpm}{'PartOf'} " !~ / $comp / ) {
				$ofed_srpm_info{$srpm}{'PartOf'} .= " $comp";
			}
		}
	}

	if (DebugPrintEnabled() ) {
		# dump all SRPM info
		DebugPrint "\nSRPMs:\n";
		foreach my $srpm ( @ofed_srpms ) {
			DebugPrint("$srpm => Builds: '$ofed_srpm_info{$srpm}{'Builds'}'\n");
			DebugPrint("           PostReq: '$ofed_srpm_info{$srpm}{'PostReq'}'\n");
			DebugPrint("           Available: '$ofed_srpm_info{$srpm}{'Available'}'\n");
			DebugPrint("           Available32: '$ofed_srpm_info{$srpm}{'Available32'}'\n");
			DebugPrint("           Available: ".available_srpm($srpm, "user", $osver)." Available32: ".available_srpm($srpm, "user32", $osver)." PartOf '$ofed_srpm_info{$srpm}{'PartOf'}'\n");
		}

		# dump all RPM info
		DebugPrint "\nRPMs:\n";
		foreach my $package ( @ofed_rpms ) {
			DebugPrint("$package => Parent: '$ofed_rpm_info{$package}{'Parent'}' Available: $ofed_rpm_info{$package}{'Available'} Available32: $ofed_rpm_info{$package}{'Available32'}\n");
			DebugPrint("           Mode: $ofed_rpm_info{$package}{'Mode'} PartOf: '$ofed_rpm_info{$package}{'PartOf'}'\n");
		}

		# dump all OFED component info
		DebugPrint "\nOFED Components:\n";
		foreach my $comp ( @ofed_components ) {
			DebugPrint("   $comp: KernelRpms: @{ $ofed_comp_info{$comp}{'KernelRpms'}}\n");
			DebugPrint("           UserRpms: @{ $ofed_comp_info{$comp}{'UserRpms'}}\n");
			DebugPrint("           DebugRpms: @{ $ofed_comp_info{$comp}{'DebugRpms'}}\n");
			DebugPrint("           Drivers: $ofed_comp_info{$comp}{'Drivers'}\n");
			DebugPrint("           StartupParams: @{ $ofed_comp_info{$comp}{'StartupParams'}}\n");
		}
		DebugPrint "\n";
	}
}

init_ofed_rpm_info($CUR_OS_VER);

# ofed specific rpm functions,
# install available user or kernel rpms in list
# install 32 bit user rpms if available
# returns 1 if compat-rdma was installed
sub ofed_rpm_install_list($$$@)
{
	my $rpmdir = shift();
	my $osver = shift();	# OS version
	my $skip_kernelib = shift();	# should compat-rdma be skipped if in package_list
	my(@package_list) = @_;	# package names
	my $ret = 0;

	# user space RPM installs
	foreach my $package ( @package_list )
	{
		if ($ofed_rpm_info{$package}{'Available'} ) {
			if ( "$ofed_rpm_info{$package}{'Mode'}" eq "kernel" ) {
				if ( " $package " =~ / compat-rdma / ) {
					next if ( $skip_kernelib);
					$ret = 1;
				}
				rpm_install($rpmdir, $osver, $package);
			} else {
				rpm_install($rpmdir, "user", $package);
			}
		}
		# Available32 is only set for user space rpms
		if ($ofed_rpm_info{$package}{'Available32'} ) {
			rpm_install($rpmdir, "user32", $package);
		}
	}
	return $ret;
}

# verify all rpms in list are installed
# verifies both 32 bit and native rpms are installed when both are available
sub ofed_rpm_is_installed_list($@)
{
	my $osver = shift();
	my(@package_list) = @_;	# package names

	foreach my $package ( @package_list )
	{
		if ($ofed_rpm_info{$package}{'Available'} ) {
			if ( "$ofed_rpm_info{$package}{'Mode'}" eq "kernel" ) {
				if (! rpm_is_installed($package, $osver) ) {
					return 0;
				}
			} else {
				if (! rpm_is_installed($package, "user") ) {
					return 0;
				}
			}
		}
		if ($ofed_rpm_info{$package}{'Available32'} ) {
			if (! rpm_is_installed($package, "user32") ) {
				return 0;
			}
		}
	}
	return 1;
}
# verify the rpmfiles exist for all the kernel RPMs listed
sub ofed_rpm_exists_list($$@)
{
	my $rpmdir = shift();
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
	my(@package_list) = @_;	# package names
	my $avail;

	if ( "$mode" eq "user32" ) {
		$avail="Available32";
	} else {	# must be "user" or kernel rev
		$avail="Available";
	}
	foreach my $package ( @package_list )
	{
		next if ( "$package" eq '' );
		if ($ofed_rpm_info{$package}{$avail} ) {
			if (! rpm_exists($rpmdir, $mode, $package) ) {
				return 0;
			}
		}
	}
	return 1;
}

# returns install prefix for presently installed OFED
sub ofed_get_prefix()
{
	my $prefix = "/usr";	# default
	if ( -e "$ROOT/etc/infiniband/info" ) {
		$prefix = `chroot /$ROOT /etc/infiniband/info 2>/dev/null|grep -w prefix|cut -d '=' -f 2`;
		chomp $prefix;
		if ( "$prefix" eq "" ) {
			$prefix = "/usr";	# fallback to default
		}
	}
	return "$prefix";
}

# unfortunately OFED mpitests leaves empty directories on uninstall
# this can confuse QLogic MPI tools because correct MPI to use
# cannot be identified.  This remove such empty directories for all
# compilers in all possible prefixes for OFED
sub ofed_cleanup_mpitests()
{
	my $prefix = ofed_get_prefix();

	if ( -e "$ROOT$prefix/mpi") {
		system("cd '$ROOT$prefix/mpi'; rmdir -p */*/tests/* >/dev/null 2>&1");
	}
	if ( -e "$ROOT/usr/mpi") {
		system("cd $ROOT/usr/mpi; rmdir -p */*/tests/* >/dev/null 2>&1");
	}
	if ( -e "$ROOT/$OFED_prefix/mpi") {
		system("cd '$ROOT/$OFED_prefix/mpi'; rmdir -p */*/tests/* >/dev/null 2>&1");
	}
}

# uninstall rpms which are in package_list and are not needed by
# any components in install_list
# all variations of the specified packages are uninstalled
sub ofed_rpm_uninstall_not_needed_list($$$$@)
{
	my $install_list = shift();	# components which will remain on system
	my $uninstalling_list = shift();	# components which are being uninstalled
	my $comp = shift();	# component being uninstalled
	my $verbosity = shift();
	my(@package_list) = @_;	# package names to consider for uninstall

RPM: foreach my $package ( reverse(@package_list) ) {
		my @install_list = split /[[:space:]]+/, $install_list;
		foreach my $c ( @install_list ) {
			next if ( "$c" eq '' ); # handling leading spaces
			# see if package is part of a component we are interested in
			if ( " @ofed_components " =~ / $c /
				 && " $ofed_rpm_info{$package}{'PartOf'} " =~ / $c / ) {
				next RPM;	# its still needed, leave it installed
			}
		}
		# if we get here, package is not in any component we are interested in
		if ( "$uninstalling_list" ne "" && "$comp" ne "" ) {
			# we are doing an explicit uninstall, we must be careful
			# about rpms which are part of more than 1 component
			# uninstalling_list is in dependency order and is executed
			# backwards, so once we get to processing the 1st component
			# in uninstalling list which has this package, we know its
			# safe to remove the package
			my @uninstalling = split /[[:space:]]+/, $uninstalling_list;
			foreach my $c ( @uninstalling ) {
				next if ( "$c" eq '' ); # handling leading spaces
				if ( " @ofed_components " =~ / $c /
					&& " $ofed_rpm_info{$package}{'PartOf'} " =~ / $c / ) {
					# found 1st uninstalled component with package
					if ("$c" ne "$comp") {
						next RPM;	# don't remove til get to $c's uninstall
					} else {
						last;	# exit this loop and uninstall package
					}
				}
			}
		}
		rpm_uninstall($package, "any", "", $verbosity);
	}
}


# resolve filename within $srcdir/$SRPMS_SUBDIR
# and return filename relative to $srcdir
sub ofed_srpm_file($$)
{
	my $srcdir = shift();
	my $globname = shift(); # in $srcdir

	my $result = file_glob("$srcdir/$SRPMS_SUBDIR/$globname");
	$result =~ s|^$srcdir/||;
	return $result;
}

# indicate where OFED built RPMs can be found
sub ofed_rpms_dir()
{
	my $srcdir=$ComponentInfo{'ib_stack'}{'SrcDir'};
	# we purposely use a different directory than OFED, this way
	# runs of OFED install or build scripts will not confuse the QLogic
	# wrapped install
	##return "$srcdir/$RPMS_SUBDIR/$RPM_DIST/";
	if (-d "$srcdir/$RPMS_SUBDIR/$CUR_DISTRO_VENDOR-$CUR_VENDOR_VER"
		|| ! -d "$srcdir/$RPMS_SUBDIR/$CUR_DISTRO_VENDOR-$CUR_VENDOR_MAJOR_VER") {
		return "$srcdir/$RPMS_SUBDIR/$CUR_DISTRO_VENDOR-$CUR_VENDOR_VER";
	} else {
		return "$srcdir/$RPMS_SUBDIR/$CUR_DISTRO_VENDOR-$CUR_VENDOR_MAJOR_VER";
	}
}

#
# get prefix used when last built rpms
sub get_ofed_rpm_prefix($)
{
	my $rpmsdir = shift();

	my $prefix_file = "$rpmsdir/Prefix";
	if ( ! -e "$prefix_file") {
		return "invalid and unknown";	# unknown, play it safe and rebuild
	} else {
		my $prefix = `cat $prefix_file 2>/dev/null`;
		chomp $prefix;
		return $prefix;
	}
}
sub save_ofed_rpm_prefix($$)
{
	my $rpmsdir = shift();
	my $prefix = shift();

	my $prefix_file = "$rpmsdir/Prefix";
	system("mkdir -p $rpmsdir");
	system "echo $prefix > $prefix_file";
}

# verify if all rpms have been built from the given srpm
sub is_built_srpm($$)
{
	my $srpm = shift();	# srpm name prefix
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
	my $srcdir=$ComponentInfo{'ib_stack'}{'SrcDir'};
	my $rpmsdir = ofed_rpms_dir();

	my @rpmlist = split /[[:space:]]+/, $ofed_srpm_info{$srpm}{'Builds'};
	return ( ofed_rpm_exists_list("$rpmsdir", $mode, @rpmlist) );
}

# see if srpm is part of any of the components being installed/reinstalled
sub need_srpm_for_install($$$$)
{
	my $srpm = shift();	# srpm name prefix
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
	my $osver = shift();
	# add space at start and end so can search
	# list with spaces around searched comp
	my $installing_list = " ".shift()." "; # items being installed/reinstalled

	if (! available_srpm($srpm, $mode, $osver)) {
		DebugPrint("$srpm $mode $osver not available\n");
		return 0;
	}

	my @complist = split /[[:space:]]+/, $ofed_srpm_info{$srpm}{'PartOf'};
	foreach my $comp (@complist) {
		next if ("$comp" eq '');
		DebugPrint("Check for $comp in ( $installing_list )\n");
		if ($installing_list =~ / $comp /) {
			return 1;
		}
	}
	return 0;
}

sub need_build_srpm($$$$$$)
{
	my $srpm = shift();	# srpm name prefix
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
	my $osver = shift();	# kernel rev
	my $installing_list = shift(); # what items are being installed/reinstalled
	my $force = shift();	# force a rebuild
	my $prompt = shift();	# prompt (only used if ! $force)
	
	# when user32 not available, need_srpm_for_install will return 0
	return ( need_srpm_for_install($srpm, $mode, $osver, $installing_list)
			&& ($force
				|| ! is_built_srpm($srpm, $mode)
				|| ($prompt && GetYesNo("Rebuild $srpm src RPM for $mode?", "n"))));
}

sub need_install_rpm_list($$$@)
{
	my $osver = shift();
	my $force = shift();
	my $prompt = shift();	# prompt (only used if ! $force)
	my(@package_list) = @_;	# package names
	my $found = 0;
	my @available_list = ();

	foreach my $package ( @package_list ) {
		if ($ofed_rpm_info{$package}{'Available'}
			|| $ofed_rpm_info{$package}{'Available32'} ) {
			@available_list = ( @available_list, $package );
		}
	}
	if (! scalar(@available_list)) {
		return 0;	# nothing to consider for install
	}
	return ($force
			|| ! ofed_rpm_is_installed_list($osver, @available_list)
			|| ($prompt && GetYesNo("Reinstall @available_list for use during build?", "n")));
}

# move rpms from build tree (srcdir) to install tree (destdir)
sub ofed_move_rpms($$)
{
	my $srcdir = shift();
	my $destdir = shift();

	system("mkdir -p $destdir");
	if (file_glob("$srcdir/$RPM_ARCH/*") ne "" ) {
		system("mv $srcdir/$RPM_ARCH/* $destdir");
	}
	if (file_glob("$srcdir/$RPM_KERNEL_ARCH/*") ne "" ) {
		system("mv $srcdir/$RPM_KERNEL_ARCH/* $destdir");
	}
	# this covers manditory and optional 32 bit rpms on 64 bit OS
	if ($mand_target_cpu32 ne '') {
		if (file_glob("$srcdir/$mand_target_cpu32/*") ne "" ) {
			system("mv $srcdir/$mand_target_cpu32/* $destdir");
		}
	}
	if (file_glob("$srcdir/noarch/*") ne "" ) {
		system("mv $srcdir/noarch/* $destdir");
	}
}

sub remove_unneeded_kernel_ib_drivers($);

# install rpms which were PostReqs of previous srpms
sub ofed_install_needed_rpms($$$$$@)
{
	my $install_list = shift();	# total that will be installed when done
	my $osver = shift();	# kernel rev
	my $force_rpm = shift();
	my $prompt_rpm = shift();
	my $rpmsdir = shift();
	my @need_install = @_;

	if (need_install_rpm_list($osver, $force_rpm, $prompt_rpm, @need_install)) {
		if (ofed_rpm_install_list("$rpmsdir", $osver, 0, @need_install)) {
			remove_unneeded_kernel_ib_drivers($install_list);
		}
	}
}

# build a specific SRPM for 32 bit on 64 bit OS
# this is heavily based on build_rpm_32 in OFED install.pl
# main changes from cut and paste are marked with # QLOGIC commands
# this has an srpm orientation and is only called when we really want to
# build the srpm
sub build_srpm32($$$$$)
{
	my $srpm = shift();	# the srpm package name
	my $TOPDIR = shift();	# top directory for build
	my $BUILD_ROOT = shift();	# temp directory for build
	my $prefix = shift();	# prefix for install path
	my $resfileop = shift(); # append or replace build.res file
	my $srcdir=$ComponentInfo{'ib_stack'}{'SrcDir'};
	my $SRC_RPM = ofed_srpm_file($srcdir, "$srpm*.src.rpm");

	# convert a few variables into the names used in OFED's build_rpm_32
	my $parent = $srpm;
    my $sysconfdir = rpm_query_param('_sysconfdir');

    my $cmd;

    my $pref_env32;
    my $ldflags32;
    my $cflags32;
    my $cppflags32;
    my $cxxflags32;
    my $fflags32;
    my $ldlibs32;

    $ldflags32    .= " -m32 -g -O2 -L/usr/lib";
    $cflags32     .= " -m32 -g -O2";
    $cppflags32   .= " -m32 -g -O2";
    $cxxflags32   .= " -m32 -g -O2";
    $fflags32     .= " -m32 -g -O2";
    $ldlibs32     .= " -m32 -g -O2 -L/usr/lib";

    if ($prefix ne $default_prefix) {
        $ldflags32 .= " -L$prefix/lib";
        $cflags32 .= " -I$prefix/include";
        $cppflags32 .= " -I$prefix/include";
        $pref_env32 .= " LD_LIBRARY_PATH=$prefix/lib:\$LD_LIBRARY_PATH";
    }

    $pref_env32 .= " LDFLAGS='$ldflags32'";
    $pref_env32 .= " CFLAGS='$cflags32'";
    $pref_env32 .= " CPPFLAGS='$cppflags32'";
    $pref_env32 .= " CXXFLAGS='$cxxflags32'";
    $pref_env32 .= " FFLAGS='$fflags32'";
    $pref_env32 .= " LDLIBS='$ldlibs32'";

    $cmd = "$pref_env32 rpmbuild --rebuild --define '_topdir $TOPDIR'";
	# QLOGIC - use mand_target_cpu32, if we get here we definitely want to build
    $cmd .= " --target $mand_target_cpu32";
	# QLOGIC - also set build_root so we can cleanup and avoid conflicts
    $cmd .= " --buildroot '${BUILD_ROOT}'";
    $cmd .= " --define 'build_root ${BUILD_ROOT}'";
    $cmd .= " --define '_prefix $prefix'";
    $cmd .= " --define 'dist  %{nil}'";
    $cmd .= " --define '_exec_prefix $prefix'";
    $cmd .= " --define '_sysconfdir $sysconfdir'";
    $cmd .= " --define '_usr $prefix'";
    $cmd .= " --define '_lib lib'";
    $cmd .= " --define '__arch_install_post %{nil}'";

    if ($parent =~ m/dapl/) {
        my $def_doc_dir = `rpm --eval '%{_defaultdocdir}'`;
        chomp $def_doc_dir;
        $cmd .= " --define '_prefix $prefix'";
        $cmd .= " --define '_exec_prefix $prefix'";
        $cmd .= " --define '_sysconfdir $sysconfdir'";
		# QLOGIC - the srpm name given includes the version for dapl
        $cmd .= " --define '_defaultdocdir $def_doc_dir/$srpm'";
        #$cmd .= " --define '_defaultdocdir $def_doc_dir/$main_packages{$parent}{'name'}-$main_packages{$parent}{'version'}'";
        $cmd .= " --define '_usr $prefix'";
    }

	#if ($distro eq "SuSE") {
	if ( "$CUR_DISTRO_VENDOR" eq "SuSE" ) {
		$cmd .= " --define '_suse_os_install_post %{nil}'";
	}


	# QLOGIC - our pathing is done a little differently
    #$cmd .= " $main_packages{$parent}{'srpmpath'}";
	$cmd .= " $SRC_RPM";

	return run_build("$srcdir $SRC_RPM $mand_target_cpu32", "$srcdir", $cmd, "$resfileop");
}

# Build RPM from source RPM
# build a specific SRPM
# this is heavily based on build_rpm in OFED install.pl
# main changes from cut and paste are marked with # QLOGIC commands
# this has an srpm orientation and is only called when we really want to
# build the srpm
sub build_srpm($$$$$)
{
	my $srpm = shift();	# the srpm package name
	my $TOPDIR = shift();	# top directory for build
	my $BUILD_ROOT = shift();	# temp directory for build
	my $prefix = shift();	# prefix for install path
	my $resfileop = shift(); # append or replace build.res file
	my $configure_options = '';	# ofed keeps per srpm, but only initializes here
	my $srcdir=$ComponentInfo{'ib_stack'}{'SrcDir'};
	my $SRC_RPM = ofed_srpm_file($srcdir, "$srpm*.src.rpm");

	# convert a few variables into the names used in OFED's build_rpm
	my $parent = $srpm;
	my $distro = "$CUR_DISTRO_VENDOR";
    my $dist_rpm_rel  = $RPM_DIST_REL;
    my $target_cpu = $RPM_ARCH;
    my $optflags = rpm_query_param('optflags');
    my $mandir = rpm_query_param('_mandir');
    my $sysconfdir = rpm_query_param('_sysconfdir');
    my $arch = my_tolower($ARCH);

    my $cmd;

    my $ldflags;
    my $cflags;
    my $cppflags;
    my $cxxflags;
    my $fflags;
    my $ldlibs;
    my $openmpi_comp_env;

    my $pref_env;
    if ($prefix ne $default_prefix) {
        $pref_env .= " LD_LIBRARY_PATH=$prefix/lib64:$prefix/lib:\$LD_LIBRARY_PATH";
        if ($parent ne "mvapich2" and $parent ne "openmpi") {
            $ldflags .= "$optflags -L$prefix/lib64 -L$prefix/lib";
            $cflags .= "$optflags -I$prefix/include";
            $cppflags .= "$optflags -I$prefix/include";
        }
    }

	# QLOGIC - OFED tested rpm_exist.  We only get here if we
	# want to build the rpm, so we force true and proceed
	# (keeps indentation same as OFED install.pl for easier cut/paste)
    if (1) {
        if ($arch eq "ppc64") {
            if ($distro eq "SuSE" and $dist_rpm_rel gt 15.2) {
                # SLES 10 SP1
                if ($parent eq "ibutils") {
					# QLOGIC - keep local variable instead of global structure
                    $configure_options .= " LDFLAGS=-L/usr/lib/gcc/powerpc64-suse-linux/4.1.2/64";
                }
                if ($parent eq "openmpi") {
                    $openmpi_comp_env .= ' LDFLAGS="-m64 -O2 -L/usr/lib/gcc/powerpc64-suse-linux/4.1.2/64"';
                }
                if ($parent =~ /sdpnetstat|rds-tools|rnfs-utils/) {
                    $ldflags    = " -g -O2";
                    $cflags     = " -g -O2";
                    $cppflags   = " -g -O2";
                    $cxxflags   = " -g -O2";
                    $fflags     = " -g -O2";
                    $ldlibs     = " -g -O2";
                }
            }
            else {
                if ($parent eq "sdpnetstat" or $parent eq "rds-tools" or $parent eq "rnfs-utils") {
                    # Override compilation flags on RHEL 4.0 and 5.0 PPC64
                    $ldflags    = " -g -O2";
                    $cflags     = " -g -O2";
                    $cppflags   = " -g -O2";
                    $cxxflags   = " -g -O2";
                    $fflags     = " -g -O2";
                    $ldlibs     = " -g -O2";
                }
                elsif ($parent !~ /ibutils/) {
                    $ldflags    .= " $optflags -m64 -g -O2 -L/usr/lib64";
                    $cflags     .= " $optflags -m64 -g -O2";
                    $cppflags   .= " $optflags -m64 -g -O2";
                    $cxxflags   .= " $optflags -m64 -g -O2";
                    $fflags     .= " $optflags -m64 -g -O2";
                    $ldlibs     .= " $optflags -m64 -g -O2 -L/usr/lib64";
                }
            }
        }

        if ($ldflags) {
            $pref_env   .= " LDFLAGS='$ldflags'";
        }
        if ($cflags) {
            $pref_env   .= " CFLAGS='$cflags'";
        }
        if ($cppflags) {
            $pref_env   .= " CPPFLAGS='$cppflags'";
        }
        if ($cxxflags) {
            $pref_env   .= " CXXFLAGS='$cxxflags'";
        }
        if ($fflags) {
            $pref_env   .= " FFLAGS='$fflags'";
        }
        if ($ldlibs) {
            $pref_env   .= " LDLIBS='$ldlibs'";
        }

        $cmd = "$pref_env rpmbuild --rebuild --define '_topdir $TOPDIR'";
        $cmd .= " --define 'dist  %{nil}'";
        $cmd .= " --target $target_cpu";
		# QLOGIC - also set build_root so we can cleanup and avoid conflicts
    	$cmd .= " --buildroot '${BUILD_ROOT}'";
    	$cmd .= " --define 'build_root ${BUILD_ROOT}'";

        # Prefix should be defined per package
        if ($parent eq "ibutils") {
			# QLOGIC - keep local variable instead of global structure
            $configure_options .= " --with-osm=$prefix";
            $cmd .= " --define '_prefix $prefix'";
            $cmd .= " --define '_exec_prefix $prefix'";
            $cmd .= " --define '_sysconfdir $sysconfdir'";
            $cmd .= " --define '_usr $prefix'";
            $cmd .= " --define 'build_ibmgtsim 1'";
            $cmd .= " --define '__arch_install_post %{nil}'";
        }
		# QLOGIC - dropped MPIs, built via do_X_build scripts instead
        elsif ($parent eq "mpi-selector") {
            $cmd .= " --define '_prefix $prefix'";
            $cmd .= " --define '_exec_prefix $prefix'";
            $cmd .= " --define '_sysconfdir $sysconfdir'";
            $cmd .= " --define '_usr $prefix'";
            $cmd .= " --define 'shell_startup_dir /etc/profile.d'";
        }
        elsif ($parent =~ m/dapl/) {
			# QLOGIC - use rpm_query_param
            my $def_doc_dir = rpm_query_param('_defaultdocdir');
            #my $def_doc_dir = `rpm --eval '%{_defaultdocdir}'`;
            chomp $def_doc_dir;
            $cmd .= " --define '_prefix $prefix'";
            $cmd .= " --define '_exec_prefix $prefix'";
            $cmd .= " --define '_sysconfdir $sysconfdir'";
			# QLOGIC - the srpm name given includes the version for dapl
            $cmd .= " --define '_defaultdocdir $def_doc_dir/$srpm'";
            #$cmd .= " --define '_defaultdocdir $def_doc_dir/$main_packages{$parent}{'name'}-$main_packages{$parent}{'version'}'";
            $cmd .= " --define '_usr $prefix'";
        }
# TBD - odd that prefix, exec_prefix, sysconfdir and usr not defined
# QLOGIC - may want to add these 4 just to be safe, they are not in OFED
#            $cmd .= " --define '_prefix $prefix'";
#            $cmd .= " --define '_exec_prefix $prefix'";
#            $cmd .= " --define '_sysconfdir $sysconfdir'";
#            $cmd .= " --define '_usr $prefix'";
        else {
            $cmd .= " --define '_prefix $prefix'";
            $cmd .= " --define '_exec_prefix $prefix'";
            $cmd .= " --define '_sysconfdir $sysconfdir'";
            $cmd .= " --define '_usr $prefix'";
        }

		if ($parent eq "librdmacm") {
			# QLOGIC - keep configure_options as a local, ibacm always installed
			#if ( $packages_info{'ibacm'}{'selected'}) {
			if ( $ofed_rpm_info{'ibacm'}{'Available'}) {
				$configure_options .= " --with-ib_acm";
			}
		}

		# QLOGIC - keep configure_options as a local
        if ($configure_options or $OFED_user_configure_options) {
            $cmd .= " --define 'configure_options $configure_options $OFED_user_configure_options'";
        }

		# QLOGIC - use SRC_RPM (computed above) instead of srpmpath_for_distro
#       $cmd .= " $main_packages{$parent}{'srpmpath'}";
		$cmd .= " $SRC_RPM";

		return run_build("$srcdir $SRC_RPM $RPM_ARCH", "$srcdir", $cmd, "$resfileop");
	}
	# NOTREACHED
}

# build all OFED components specified in installing_list
# if already built, prompt user for option to build
sub build_ofed($$$$$$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift(); # what items are being installed/reinstalled
	my $K_VER = shift();	# osver
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild

	my $prompt_srpm = 0;	# prompt per SRPM
	my $prompt_rpm = 0;	# prompt per RPM
	my $force_srpm = $force;	# force SRPM rebuild
	my $force_kernel_srpm = ("$OFED_kernel_configure_options" ne "");
	my $force_user_srpm = ("$OFED_user_configure_options" ne "");
	my $force_rpm = $force;	# force dependent RPM reinstall
	my $rpmsdir = ofed_rpms_dir();

	my $prefix=$OFED_prefix;
	if ("$prefix" ne get_ofed_rpm_prefix($rpmsdir)) {
		$force_kernel_srpm = 1;
		$force_user_srpm = 1;
	}

	if (! $force && ! $Default_Prompt && ! ($force_user_srpm && $force_kernel_srpm)) {
		my $choice = GetChoice("Rebuild OFED SRPMs (a=all, p=prompt per SRPM, n=only as needed?)", "n", ("a", "p", "n"));
		if ("$choice" eq "a") {
			$force_srpm=1;
		} elsif ("$choice" eq "p") {
			$prompt_srpm=1;
		} elsif ("$choice" eq "n") {
			$prompt_srpm=0;
		}
	}
	# we base our decision on status of ib_stack.  Possible risk if
	# ib_stack is partially upgraded and was interrupted.
	if (! comp_is_uptodate('ib_stack') || $force_srpm  || $force_user_srpm || $force_kernel_srpm) {
		$force_rpm = 1;
	} elsif (! $Default_Prompt) {
		my $choice = GetChoice("Reinstall OFED dependent RPMs (a=all, p=prompt per RPM, n=only as needed?)", "n", ("a", "p", "n"));
		if ("$choice" eq "a") {
			$force_rpm=1;
		} elsif ("$choice" eq "p") {
			$prompt_rpm=1;
		} elsif ("$choice" eq "n") {
			$prompt_rpm=0;
		}
	}

	# -------------------------------------------------------------------------
	# do all rebuild prompting first so user doesn't have to wait 5 minutes
	# between prompts
	my $build_compat_rdma = need_build_srpm("compat-rdma", "$K_VER", "$K_VER",
		   					$installing_list,
							$force_srpm || $force_kernel_srpm || $OFED_debug || $OFED_xeonphi,
							$prompt_srpm);

	my $build_ib_bonding = need_build_srpm("ib-bonding", $K_VER, "$K_VER",
		   					$installing_list,
							$force_srpm||$force_kernel_srpm,$prompt_srpm);

	my $need_build = ($build_compat_rdma || $build_ib_bonding);
	my %build_user_srpms = ();

	foreach my $srpm ( @ofed_user_srpms ) {
		VerbosePrint("check if need to build $srpm\n");
		$build_user_srpms{"${srpm}_build_user"} = 0;
		$build_user_srpms{"${srpm}_build_user32"} = 0;

		# mpitests is built as part of mvapich, openmpi and mvapich2
		next if ( "$srpm" eq "mpitests" );

			$build_user_srpms{"${srpm}_build_user"} = 
					need_build_srpm($srpm, "user", "$K_VER", $installing_list,
							$force_srpm || $force_user_srpm,$prompt_srpm);
			$build_user_srpms{"${srpm}_build_user32"} = 
					need_build_srpm($srpm, "user32", "$K_VER", $installing_list,
							$force_srpm || $force_user_srpm,$prompt_srpm);
		$need_build |= ($build_user_srpms{"${srpm}_build_user"}
						|| $build_user_srpms{"${srpm}_build_user32"});
	}

	if (! $need_build) {
		return 0;	# success
	}

	# -------------------------------------------------------------------------
	# check OS dependencies for all srpms which we will build
	my $dep_error = 0;

	NormalPrint "Checking OS Dependencies needed for builds...\n";

	if ($build_compat_rdma)
	{
		VerbosePrint("check dependencies for compat-rdma\n");
		if (check_kbuild_dependencies($K_VER, "compat-rdma")) {
			DebugPrint "compat-rdma kbuild dependency failure\n";
			$dep_error = 1;
		}
		if (check_rpmbuild_dependencies("compat-rdma")) {
			DebugPrint "compat-rdma rpmbuild dependency failure\n";
			$dep_error = 1;
		}
	}
	if ($build_ib_bonding)
	{
		VerbosePrint("check dependencies for ib-bonding\n");
		if (check_kbuild_dependencies($K_VER, "ib-bonding")) {
			DebugPrint "ib-bonding kbuild dependency failure\n";
			$dep_error = 1;
		}
		if (check_rpmbuild_dependencies("ib-bonding")) {
			DebugPrint "ib-bonding rpmbuild dependency failure\n";
			$dep_error = 1;
		}
	}
	foreach my $srpm ( @ofed_user_srpms ) {
		# mpitests is built as part of mvapich, openmpi and mvapich2
		next if ( "$srpm" eq "mpitests" );

		my $build_user = $build_user_srpms{"${srpm}_build_user"};
		my $build_user32 = $build_user_srpms{"${srpm}_build_user32"};

		next if ( ! ($build_user | $build_user32));

		VerbosePrint("check dependencies for $srpm\n");

			if (check_rpmbuild_dependencies($srpm)) {
				DebugPrint "$srpm rpmbuild dependency failure\n";
				$dep_error = 1;
			}
			if ($build_user) {
				DebugPrint "Check $srpm user build prereqs\n";
				if (check_build_dependencies($srpm)) {
					$dep_error = 1;
				}
				if (rpm_check_build_os_prereqs("any", $srpm, 
							@{ $ofed_srpm_info{$srpm}{'BuildPrereq'}})) {
					DebugPrint "$srpm prereqs dependency failure\n";
					$dep_error = 1;
				}
			}
			if ($build_user32) {
				DebugPrint "Check $srpm user32 build prereqs\n";
				if (check_build32_dependencies($srpm)) {
					$dep_error = 1;
				}
				if (rpm_check_build_os_prereqs("any", $srpm, 
							@{ $ofed_srpm_info{$srpm}{'Build32Prereq'}})) {
					DebugPrint "$srpm user32 prereqs dependency failure\n";
					$dep_error = 1;
				}
			}
			if ("$srpm" eq "rnfs-utils" ) {
				my @reqs = ('krb5-devel any user');
			if ("$CUR_DISTRO_VENDOR" eq 'redhat' ||
				"$CUR_DISTRO_VENDOR" eq 'fedora') {
					@reqs = ( @reqs, 'krb5-libs any user',
						   		'openldap-devel any user');
					# RHEL6 and later have removed libevent and nfs-utils-lib
					if ("$CUR_VENDOR_VER" eq 'ES5' || "$CUR_VENDOR_VER" eq 'ES4') {
						@reqs = ( @reqs, 'libevent-devel any user',
						   		'nfs-utils-lib-devel any user');
					}
				} else {
					@reqs = ( @reqs, 'krb5 any user',
							'openldap2-devel any user',
							'cyrus-sasl-devel any user');
				}
				if ("$CUR_DISTRO_VENDOR" eq 'SuSE') {
					if ($K_VER =~ m/2\.6\.2[6-7]/ ) {
						@reqs = ( @reqs, 'libblkid-devel any user');
					} else {
						@reqs = ( @reqs, 'e2fsprogs-devel any user');
					}
					if ("$CUR_VENDOR_VER" eq 'ES11') {
						@reqs = ( @reqs, 'libevent-devel any user',
						   	'nfsidmap-devel any user',
						   	'libopenssl-devel any user');
					}
				}
				if (rpm_check_build_os_prereqs("any", "$srpm for $ComponentInfo{'ofed_nfsrdma'}{'Name'}", (@reqs))) {
					$dep_error = 1;
				}
			} elsif ("$srpm" eq "openmpi" ) {
				if ($ARCH eq "PPC64") {
					# TBD - on this platform openmpi tests user32 versions
					# in OFED for --32bit.
					# Not sure why 64 bit versions aren't tested
					#if (rpm_check_build_os_prereqs("any", $srpm, 
					#			('sysfsutils-devel any user32', 'libstdc++-devel any user32'))) {
					#	$dep_error = 1;
					#}
				}
			}
		}
	if ($dep_error) {
		NormalPrint "ERROR - unable to perform builds due to need for additional OS rpms\n";
		return 1;	# failure
	}

	# -------------------------------------------------------------------------
	# perform the builds
	my $srcdir=$ComponentInfo{'ib_stack'}{'SrcDir'};

	my $must_force_rpm = 0;	# set if we rebuild something so force updates
	my @need_install = ( );	# keep track of PostReqs not yet installed
	my @installed = ();	# rpms we installed to facilitate builds

	if ("$prefix" ne get_ofed_rpm_prefix($rpmsdir)) {
		system("rm -rf $rpmsdir");	# get rid of stuff with old prefix
		save_ofed_rpm_prefix($rpmsdir, $prefix);
	}

	# use a different directory for BUILD_ROOT to limit conflict with OFED
	if ("$build_temp" eq "" ) {
		$build_temp = "/var/tmp/IntelIB-OFED";
	}
	my $BUILD_ROOT="$build_temp/build";
	my $RPM_DIR="$build_temp/OFEDRPMS";
	my $mandir = rpm_query_param("_mandir");
	my $resfileop = "replace";	# replace for 1st build, append for rest

	system("rm -rf ${build_temp}");

	# use a different directory for BUILD_ROOT to limit conflict with OFED
	if (0 != system("mkdir -p $BUILD_ROOT $RPM_DIR/BUILD $RPM_DIR/RPMS $RPM_DIR/SOURCES $RPM_DIR/SPECS $RPM_DIR/SRPMS")) {
		NormalPrint "ERROR - mkdir -p $BUILD_ROOT $RPM_DIR/BUILD $RPM_DIR/RPMS $RPM_DIR/SOURCES $RPM_DIR/SPECS $RPM_DIR/SRPMS FAILED\n";
		return 1;	# failure
	}

	my $rpm_os_version=rpm_tr_os_version($K_VER);

	# OFED has all the ULPs in a single compat-rdma RPM.  We build that
	# RPM here from the compat-rdma SRPM with all ULPs included.
	# Later during install we remove ULPs not desired after installing
	# the compat-rdma RPM
	if ($build_compat_rdma)
	{
		my $OFA_KERNEL_SRC_RPM=ofed_srpm_file($srcdir,"compat-rdma*.src.rpm");
		my $K_SRC = "/lib/modules/$K_VER/build";
		my $configure_options_kernel;
		$configure_options_kernel = get_build_options($K_VER, %ofed_kernel_ib_options);
		if ( $OFED_debug ) {
			# TBD --with-memtrack
			#$configure_options_kernel .= " --with-memtrack";
		}

		if ( $OFED_xeonphi ) {
			$configure_options_kernel .= " --with-ibp-server-mod --with-ibscif-mod";
		}

		VerbosePrint("OS specific kernel configure options: '$configure_options_kernel'\n");

		if (0 != run_build("$srcdir $OFA_KERNEL_SRC_RPM $RPM_KERNEL_ARCH $K_VER", "$srcdir",
				 "rpmbuild --rebuild --define '_topdir ${RPM_DIR}'"
        		.		" --target $RPM_KERNEL_ARCH"
				.		" --define '_prefix ${prefix}'"
				.		" --buildroot '${BUILD_ROOT}'"
				.		" --define 'build_root ${BUILD_ROOT}'"
				.		" --define 'configure_options ${configure_options_kernel} $OFED_kernel_configure_options'"
				.		" --define 'KVERSION ${K_VER}'"
				.		" --define 'KSRC ${K_SRC}'"
				.		" --define 'build_kernel_ib 1'"
				.		" --define 'build_kernel_ib_devel 1'"
				.		" --define 'network_dir ${NETWORK_CONF_DIR}'"
            	.		" --define '__arch_install_post %{nil}'"
				.		" --define '_release $rpm_os_version'"
				.		" ${OFA_KERNEL_SRC_RPM}",
				"$resfileop"
				)) {
			return 1;	# failure
		}
		$must_force_rpm=1;
		$resfileop = "append";
		ofed_move_rpms("$RPM_DIR/$RPMS_SUBDIR", "$rpmsdir");
	}
	@need_install = ( @need_install, split /[[:space:]]+/, $ofed_srpm_info{'compat-rdma'}{'PostReq'});

	if ($build_ib_bonding)
	{
		my $IB_BONDING_SRC_RPM=ofed_srpm_file($srcdir,"ib-bonding*.src.rpm");

		# OFED_kernel_configure_options not applicable to ib-bonding
		if (0 != run_build("$srcdir $IB_BONDING_SRC_RPM $RPM_KERNEL_ARCH $K_VER", "$srcdir",
				 "rpmbuild --rebuild --define '_topdir ${RPM_DIR}'"
        		.		" --target $RPM_KERNEL_ARCH"
				.		" --define '_prefix ${prefix}'"
				.		" --buildroot '${BUILD_ROOT}'"
				.		" --define 'build_root ${BUILD_ROOT}'"
				.		" --define 'KVERSION ${K_VER}'"
				.		" --define '_release ${rpm_os_version}'"
            	.		" --define '__arch_install_post %{nil}'"
				.		" ${IB_BONDING_SRC_RPM}",
				"$resfileop"
				)) {
			return 1;	# failure
		}
		$resfileop = "append";
		ofed_move_rpms("$RPM_DIR/$RPMS_SUBDIR", "$rpmsdir");
		$must_force_rpm=1;
	}
	@need_install = ( @need_install, split /[[:space:]]+/, $ofed_srpm_info{'ib-bonding'}{'PostReq'});

	foreach my $srpm ( @ofed_user_srpms ) {
		VerbosePrint("process $srpm\n");

		# mpitests is built as part of mvapich, openmpi and mvapich2
		next if ( "$srpm" eq "mpitests" );

		my $build_user = $build_user_srpms{"${srpm}_build_user"};
		my $build_user32 = $build_user_srpms{"${srpm}_build_user32"};

			if ($build_user || $build_user32) {
				# load rpms which are were PostReqs from previous srpm builds
				ofed_install_needed_rpms($install_list, $K_VER, $force_rpm||$must_force_rpm, $prompt_rpm, $rpmsdir, @need_install);
				@installed = ( @installed, @need_install);
				@need_install = ();
				$must_force_rpm=0;

				# build it
				if ("$srpm" eq "mvapich2" ) {
					if (0 != run_build("mvapich2_gcc and mpitests_mvapich2_gcc", "$srcdir", "STACK_PREFIX='$prefix' BUILD_DIR='$build_temp' MPICH_PREFIX= CONFIG_OPTIONS='$OFED_user_configure_options' INSTALL_ROOT='$ROOT' ./do_mvapich2_build -d -i  gcc", $resfileop)) {
						return 1;	# failure
					}
					# build already installed mvapich2_gcc
					@installed = ( @installed, split /[[:space:]]+/, 'mvapich2_gcc');
					$resfileop = "append";
					$must_force_rpm=1;

				} elsif ("$srpm" eq "openmpi" ) {
					if (0 != run_build("openmpi_gcc and mpitests_openmpi_gcc", "$srcdir", "STACK_PREFIX='$prefix' BUILD_DIR='$build_temp' MPICH_PREFIX= CONFIG_OPTIONS='$OFED_user_configure_options' INSTALL_ROOT='$ROOT' ./do_openmpi_build -d -i  gcc", $resfileop)) {
						return 1;	# failure
					}
					# build already installed openmpi_gcc
					@installed = ( @installed, split /[[:space:]]+/, 'openmpi_gcc');
					$resfileop = "append";
					$must_force_rpm=1;

				} else {	# all non-MPI user RPMs
					if ($build_user) {
						if (0 != build_srpm($srpm, $RPM_DIR, $BUILD_ROOT, $prefix, $resfileop)) {
							return 1;	# failure
						}
						$resfileop = "append";
					}
					if ($build_user32) {
						if (0 != build_srpm32($srpm, $RPM_DIR, $BUILD_ROOT, $prefix, $resfileop)) {
							return 1;	# failure
						}
					}
					$resfileop = "append";
					@need_install = ( @need_install, split /[[:space:]]+/, $ofed_srpm_info{$srpm}{'PostReq'});
					$must_force_rpm=1;
				}
				ofed_move_rpms("$RPM_DIR/$RPMS_SUBDIR", "$rpmsdir");
			} else {
				@need_install = ( @need_install, split /[[:space:]]+/, $ofed_srpm_info{$srpm}{'PostReq'});
			}
		}

	# get rid of rpms we installed to enable builds but are not desired to stay
	# eg. uninstall rpms which were installed but are not part of install_list
	ofed_rpm_uninstall_not_needed_list($install_list, "", "", "verbose", @installed);

	if (! $debug) {
		system("rm -rf ${build_temp}");
	} else {
		LogPrint "Build remnants left in $BUILD_ROOT and $RPM_DIR\n";
	}

	return 0;	# success
}

# forward declarations
sub installed_ofed_ib_stack();
sub uninstall_old_stacks($);

# track if install_kernel_ib function was used so we only install
# compat-rdma once in a given "Perform" of install menu
my $install_kernel_ib_was_run = 0;

# return 0 on success, != 0 otherwise
sub uninstall_old_ofed_rpms($$$)
{
	my $mode = shift();	# "user32" (32 bit on 64 bit OS) or "user" or kernel rev
						# "any"- checks if any variation of package is installed
	my $verbosity = shift();
	my $message = shift();

	my $ret = 0;	# assume success
	my @packages = ();

	if ("$message" eq "" ) {
		$message = "previous OFED";
	}
	NormalPrint "\nUninstalling $message RPMs\n";

	# SLES11 includes an old version of OpenMPI that other packages may depend on, but 
	# which must be removed to prevent conflicts with the new version that we are installing. 
	#if ("$CUR_DISTRO_VENDOR" eq 'SuSE' && "$CUR_VENDOR_VER" eq 'ES11') {
	#	DebugPrint("Forcing Uninstall of SLES11 OpenMPI\n");
	#	if (rpm_uninstall_matches("SLES11 OpenMPI", "openmpi-1.2.8", "", "--nodeps")) {
	#		NormalPrint "Unable to uninstall existing openmpi installation.\n";
	#	}
	#}
	# SLES11 includes an old version of OpenMPI that other packages may depend on, but needs to be unselected in mpi-selector
	if ("$CUR_DISTRO_VENDOR" eq 'SuSE' && "$CUR_VENDOR_VER" eq 'ES11' && $mode eq 'any') {
		LogPrint "mpi-selector --unset --system >/dev/null 2>/dev/null\n";
		system("mpi-selector --unset --system >/dev/null 2>/dev/null");
		LogPrint "mpi-selector --unset --user >/dev/null 2>/dev/null\n";
		system("mpi-selector --unset --user >/dev/null 2>/dev/null");
	}

	# uninstall all present version OFED rpms, just to be safe
	foreach my $i ( reverse(@ofed_components) ) {
		@packages = (@packages, @{ $ofed_comp_info{$i}{'DebugRpms'}});
		@packages = (@packages, @{ $ofed_comp_info{$i}{'UserRpms'}});
		@packages = (@packages, @{ $ofed_comp_info{$i}{'KernelRpms'}});
	}
	# uninstall RPMs from older versions of OFED
	@packages = (@packages, @prev_release_rpms);
	@packages = (@packages, @redhat_rpms);
	@packages = (@packages, @suse_rpms);
	# other potential RPMs for ofed
	#my @other_ofed_rpms = `rpm -qa 2> /dev/null | grep ofed`;
	#@packages = (@packages, @other_ofed_rpms);

	# workaround LAM and other MPIs usng mpi-selector
	# we uninstall mpi-selector separately and ignore failures for its uninstall
	my @filtered_packages = ();
	my @rest_packages = ();
	foreach my $i ( @packages ) {
		if (scalar(grep /^$i$/, (@filtered_packages, @rest_packages)) > 0) {
			# skip, already in list
		} elsif ( "$i" eq "mpi-selector" ) {
			@rest_packages = (@rest_packages, "$i");
		} elsif ("$i" eq "openmpi") {
			if ("$CUR_DISTRO_VENDOR" eq 'SuSE' && "$CUR_VENDOR_VER" eq 'ES11') {
				# SLES11 openmpi is used by boost
				# keep openmpi for now
				#@filtered_packages = (@filtered_packages, "boost-devel", "libboost_mpi1_36_0", "$i");
				# try to remove it, but ignore errors
				@rest_packages = (@rest_packages, "$i");
			} else {
				@filtered_packages = (@filtered_packages, "$i");
			}
		} elsif ( ("$i" eq "ib-bonding" || "$i" eq "ib-bonding-debuginfo")
					&& ! $ofed_rpm_info{$i}{'Available'}) {
			# skip, might be included with distro
		} else {
			@filtered_packages = (@filtered_packages, "$i");
		}
	}

	$ret ||= rpm_uninstall_all_list($mode, $verbosity, @filtered_packages);

	# ignore errors uninstalling mpi-selector
	if (scalar(@rest_packages) != 0) {
		if (rpm_uninstall_all_list($mode, $verbosity, @rest_packages) && ! $ret) {
			NormalPrint "The previous errors can be ignored\n";
		}
	}

	ofed_cleanup_mpitests();

	if ( $ret ) {
		NormalPrint "Unable to uninstall $message RPMs\n";
	}
	return $ret;
}

# The QuickSilver version of SDP can leave sunrpc in a patched state
# in which case nfs will not load because it depends on QuickSilver SDP module
sub cleanup_iba_sdp()
{
	# only care about 2.6 kernels (.ko modules, not .o)
	if ( -e "$ROOT/lib/modules/$CUR_OS_VER/kernel/net/sunrpc/sunrpc.ko_orig" ) {
		my $res=system("cmp -s $ROOT/lib/modules/$CUR_OS_VER/kernel/net/sunrpc/sunrpc.ko_sdp $ROOT/lib/modules/$CUR_OS_VER/kernel/net/sunrpc/sunrpc.ko");
		if ( $res == 0) {
			NormalPrint "Undoing QuickSilver SDP NFS hooks\n";
			# Quicksilver sdp version is the active version, restore orig
			my $cmd="cp $ROOT/lib/modules/$CUR_OS_VER/kernel/net/sunrpc/sunrpc.ko_orig $ROOT/lib/modules/$CUR_OS_VER/kernel/net/sunrpc/sunrpc.ko";
			LogPrint "$cmd\n";
			if (0 != system("$cmd")) {
				NormalPrint "ERROR - Failed to $cmd\n";
			}
		}
	}
}

# remove any old stacks or old versions of the stack
# this is necessary before doing builds to ensure we don't use old dependent
# rpms
sub uninstall_prev_versions()
{
	cleanup_iba_sdp();
	if (! installed_ofed_ib_stack) {
		if (0 != uninstall_old_stacks(1)) {
			return 1;
		}
	} elsif (! comp_is_uptodate('ib_stack')) { # all ofed_comp same version
		if (0 != uninstall_old_ofed_rpms("any", "silent", "previous OFED")) {
			return 1;
		}
	}
	return 0;
}

sub media_version_ofed()
{
	# all OFED components at same version as ib_stack
	my $srcdir=$ComponentInfo{'ib_stack'}{'SrcDir'};
	return `cat "$srcdir/Version"`;
}

sub ofed_save_autostart()
{
	foreach my $comp ( @ofed_components ) {
  		if ($ComponentInfo{$comp}{'HasStart'}
			&& $ofed_comp_info{$comp}{'StartupScript'} ne "") { 
			$ofed_autostart_save{$comp} = comp_IsAutostart2($comp);
		} else {
			$ofed_autostart_save{$comp} = 0;
		}
	}
}

sub ofed_restore_autostart($)
{
	my $comp = shift();

	if ( $ofed_autostart_save{$comp} ) {
		comp_enable_autostart2($comp, 1);
	} else {
  		if ($ComponentInfo{$comp}{'HasStart'}
			&& $ofed_comp_info{$comp}{'StartupScript'} ne "") { 
			comp_disable_autostart2($comp, 1);
		}
	}
}

# makes sure needed OFED components are already built, builts/rebuilds as needed
# called for every ofed component's preinstall, noop for all but
# first OFED component in installing_list
# also available for use by srp to facilitate them getting
# built within ofed context
sub preinstall_ofed($$$)
{
	my $comp = shift();			# calling component
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	# make sure flag cleared so will install this if part of an installed comp
	$install_kernel_ib_was_run = 0;

	# ignore non-ofed components at start of installing_list
	my @installing = split /[[:space:]]+/, $installing_list;
	while (scalar(@installing) != 0
			&& ("$installing[0]" eq ""
			 	|| " @ofed_components " !~ / $installing[0] /)) {
		shift @installing;
	}
	# now, only do work if $comp is the 1st ofed component in installing_list
	if ("$comp" eq "$installing[0]") {
		ofed_save_autostart();
		init_ofed_rpm_info($CUR_OS_VER);

		# Before we do any builds make sure old stacks removed so we don't
		# build against the wrong version of dependent rpms
		if (0 != uninstall_prev_versions()) {
			return 1;
		}
		if (ROOT_is_set()) {
			# we will build in current image, so must uninstall
			# in / as well as $ROOT (above)
			my $save_ROOT=$ROOT;
			$ROOT='/';
			my $rc = uninstall_prev_versions();
			$ROOT=$save_ROOT;
			if (0 != $rc) {
				return 1;
			}
		}
			

		# remove 32 bit libraries from previous installs if not desired
		# only need to do this in install image ($ROOT)
		if ($OFED_no32bit && $mand_target_cpu32 ne "") {
			if (0 != uninstall_old_ofed_rpms("user32", "verbose", "32 bit library OFED")) {
				return 1;
			}
		}

		print_separator;
		my $version=media_version_ofed();
		chomp $version;
		printf("Preparing OFED $version $DBG_FREE for Install...\n");
		LogPrint "Preparing OFED $version $DBG_FREE for Install for $CUR_OS_VER\n";
		if (ROOT_is_set()) {
			# this directory is used during rpm installs, create it as needed
			if (0 != system("mkdir -p $ROOT/var/tmp")) {
				NormalPrint("Unable to create $ROOT/var/tmp\n");
				return 1;
			}
		}
	
		if (ROOT_is_set()) {
			# build in current image
			my $save_ROOT=$ROOT;
			$ROOT='/';
			my $rc = build_ofed("$install_list", "$installing_list", "$CUR_OS_VER",0,"",$OFED_force_rebuild);
			$ROOT=$save_ROOT;
			return $rc;
		} else {
			return build_ofed("$install_list", "$installing_list", "$CUR_OS_VER",0,"",$OFED_force_rebuild);
		}
	} else {
		return 0;
	}
}

# wrapper for installed_driver to handle the fact that OFED drivers used to
# be installed under updates/kernel and now are simply installed under updates
# So we check both places so that upgrade installs can properly detect drivers
# which are in the old location
sub installed_ofed_driver($$$)
{
	my $WhichDriver = shift();
	my $driver_subdir = shift();
	my $subdir = shift();

	return installed_driver($WhichDriver, "$driver_subdir/$subdir")
			|| installed_driver($WhichDriver, "$driver_subdir/kernel/$subdir");
}

# ==========================================================================
# OFED generic installation routines

# since most of OFED components are simply data driven by Rpm lists in
# ofed_comp_info, we can implement these support functions which do
# most of the real work for install and uninstall of components

# OFED has a single start script but controls which ULPs are loaded via
# entries in $OFED_CONFIG (openib.conf)
# change all StartupParams for given ofed component to $newvalue
sub ofed_comp_change_openib_conf_param($$)
{
	my $comp=shift();
	my $newvalue=shift();

	VerbosePrint("edit $ROOT/$OFED_CONFIG: $comp StartUp set to '$newvalue'\n");
	foreach my $p ( @{ $ofed_comp_info{$comp}{'StartupParams'} } ) {
		change_openib_conf_param($p, $newvalue);
	}
}

# generic functions to handle autostart needs for ofed components with
# more complex openib.conf based startup needs.  These assume ib_stack handles
# the actual startup script.  Hence these focus on the openib.conf parameters
# determine if the given capability is configured for Autostart at boot
sub IsAutostart_ofed_comp2($)
{
	my $comp = shift();	# component to check
	my $WhichStartup = $ofed_comp_info{$comp}{'StartupScript'};
	my $ret = IsAutostart($WhichStartup);	# just to be safe, test this too

	# to be true, all parameters must be yes
	foreach my $p ( @{ $ofed_comp_info{$comp}{'StartupParams'} } ) {
			$ret &= ( read_openib_conf_param($p, "") eq "yes");
	}
	return $ret;
}
sub autostart_desc_ofed_comp($)
{
	my $comp = shift();	# component to describe
	my $WhichStartup = $ofed_comp_info{$comp}{'StartupScript'};
	return "$ComponentInfo{$comp}{'Name'} ($WhichStartup)";
}
# enable autostart for the given capability
sub enable_autostart_ofed_comp2($)
{
	my $comp = shift();	# component to enable
	#my $WhichStartup = $ofed_comp_info{$comp}{'StartupScript'};

	#ib_stack handles this: enable_autostart($WhichStartup);
	ofed_comp_change_openib_conf_param($comp, "yes");
}
# disable autostart for the given capability
sub disable_autostart_ofed_comp2($)
{
	my $comp = shift();	# component to disable
	#my $WhichStartup = $ofed_comp_info{$comp}{'StartupScript'};

	# Note: as a side effect this ULP will also not be manually started
	# when openibd is manually run
	#ib_stack handles this: disable_autostart($WhichStartup);
	ofed_comp_change_openib_conf_param($comp, "no");
}

# OFED has all the ULPs in a single RPM.  This function removes the
# drivers from compat-rdma specific to the given ofed_component
# this is a hack, but its better than uninstall and reinstall compat-rdma
# every time a ULP is added/removed
sub remove_ofed_kernel_ib_drivers($$)
{
	my $comp = shift();	# component to remove
	my $verbosity = shift();
	# cheat on driver_subdir so ofed_components can have some stuff not
	# in @Components
	# we know driver_subdir is same for all ofed components in compat-rdma
	my $driver_subdir=$ComponentInfo{'ib_stack'}{'DriverSubdir'};

	my $i;
	my @list = split /[[:space:]]+/, $ofed_comp_info{$comp}{'Drivers'};
	for ($i=0; $i < scalar(@list); $i+=2)
	{
		my $driver=$list[$i];
		my $subdir=$list[$i+1];
		remove_driver("$driver", "$driver_subdir/$subdir", $verbosity);
		remove_driver_dirs("$driver_subdir/$subdir");
	}
}

sub print_install_banner_ofed_comp($)
{
	my $comp = shift();

	my $version=media_version_ofed();
	chomp $version;
	printf("Installing $ComponentInfo{$comp}{'Name'} $version $DBG_FREE...\n");
	# all OFED components at same version as ib_stack
	LogPrint "Installing $ComponentInfo{$comp}{'Name'} $version $DBG_FREE for $CUR_OS_VER\n";
}

# helper to determine if we need to reinstall due to parameter change
sub need_reinstall_ofed_comp($$$)
{
	my $comp = shift();
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	if (get_ofed_rpm_prefix(ofed_rpms_dir()) ne "$OFED_prefix" ) {
		return "all";
	} elsif (! comp_is_uptodate('ib_stack')) { # all ofed_comp same version
		# on upgrade force reinstall to recover from uninstall of old rpms
		return "all";
	} else {
		return "no";
	}
}

# helper which does most of the work for installing rpms and drivers
# for an OFED component
# installs compat-rdma drivers, KernelRpms and UserRpms
# caller must handle any non-RPM files
sub install_ofed_comp($$)
{
	my $comp = shift();
	my $install_list = shift();	# total that will be installed when done

	# special handling for compat-rdma
	if ($ComponentInfo{$comp}{'DriverSubdir'} ne "" ) {
		install_kernel_ib(ofed_rpms_dir(), $install_list);
	}
	# skip compat-rdma if in KernelRpms/UserRpms, already handled above
	ofed_rpm_install_list(ofed_rpms_dir(), $CUR_OS_VER, 1,
							( @{ $ofed_comp_info{$comp}{'KernelRpms'}},
							@{ $ofed_comp_info{$comp}{'UserRpms'}}) );
	# DebugRpms are installed as part of 'ofed_debug' component

}

sub print_uninstall_banner_ofed_comp($)
{
	my $comp = shift();

	NormalPrint("Uninstalling $ComponentInfo{$comp}{'Name'}...\n");
}

# uninstall all rpms associated with an OFED component
sub uninstall_ofed_comp_rpms($$$$)
{
	my $comp = shift();
	my $install_list = shift();
	my $uninstalling_list = shift();
	my $verbosity = shift();

	if ( "$comp" eq "ofed_ib_bonding" && ! $ofed_rpm_info{'ib-bonding'}{'Available'}) {
		# special case - do not touch distro ib-bonding
		return;
	}
	# debuginfo never in >1 component, so do explicit uninstall since
	# have an odd PartOf relationship which confuses uninstall_not_needed_list
	rpm_uninstall_list("any", $verbosity,
					 @{ $ofed_comp_info{$comp}{'DebugRpms'}});
	ofed_rpm_uninstall_not_needed_list($install_list, $uninstalling_list, $comp,
				 	$verbosity, @{ $ofed_comp_info{$comp}{'UserRpms'}});
	ofed_rpm_uninstall_not_needed_list($install_list, $uninstalling_list, $comp,
				 	$verbosity, @{ $ofed_comp_info{$comp}{'KernelRpms'}});
}

# helper which does most of the work for uninstalling rpms and drivers
# for an OFED component
# caller must handle any non-RPM files
sub uninstall_ofed_comp($$$$)
{
	my $comp = shift();
	my $install_list = shift();
	my $uninstalling_list = shift();
	my $verbosity = shift();

	uninstall_ofed_comp_rpms($comp, $install_list, $uninstalling_list, $verbosity);
	remove_ofed_kernel_ib_drivers($comp, $verbosity);
}

# remove compat-rdma drivers for components which will not be installed
sub remove_unneeded_kernel_ib_drivers($)
{
	my $install_list = shift();	# total that will be installed when done
	foreach my $c ( @ofed_components )
	{
		if ($install_list !~ / $c /) {
			remove_ofed_kernel_ib_drivers($c, "verbose");
		}
	}
}

# OFED has all the ULPs in a single RPM.  This function installs that
# RPM and removes the undesired ULP drivers
sub install_kernel_ib($$)
{
	my $rpmdir = shift();
	my $install_list = shift();	# total that will be installed when done
	my $old_conf = 0;	# do we have an existing conf file

	my $driver_subdir=$ComponentInfo{'ib_stack'}{'DriverSubdir'};	# same for all ofed components

	if ( $install_kernel_ib_was_run) {
		return;
	}

	if ( -e "$ROOT/$OFED_CONFIG" ) {
		if (0 == system("cp $ROOT/$OFED_CONFIG $ROOT/$OFED_CONFIG-save")) {
			$old_conf=1;
		}
	}
	rpm_install("$rpmdir", $CUR_OS_VER, "compat-rdma");
	remove_unneeded_kernel_ib_drivers($install_list);

	# adjust openib.conf autostart settings
	foreach my $c ( @ofed_components )
	{
		if ($install_list !~ / $c /) {
			# disable autostart of uninstalled components
			# no need to disable openibd, since being in this function implies
			# ib_stack is at least installed
			ofed_comp_change_openib_conf_param($c, "no");
		} else {
			# retain previous setting for components being installed
			# set to no if initial install
			# it seems that compat-rdma rpm will do this for us,
			# repeat just to be safe
			foreach my $p ( @{ $ofed_comp_info{$c}{'StartupParams'} } ) {
				my $old_value = "";
				if ( $old_conf ) {
					$old_value = read_openib_conf_param($p, "$ROOT/$OFED_CONFIG-save");
				}
				if ( "$old_value" eq "" ) {
					$old_value = "no";
				}
				change_openib_conf_param($p, $old_value);
			}
		}
	}
	# openib.conf values not directly associated with driver startup are left
	# untouched ofed rpm install will keep existing value

	$install_kernel_ib_was_run = 1;
}

# ==========================================================================
# OFED ib_stack installation

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_ib_stack()
{
	# ib_stack is tricky, there are multiple parameters.  We just test
	# the things we control here, if user has edited openib.conf they
	# could end up with startup still disabled by having disabled all
	# the individual HCA drivers
	return IsAutostart_ofed_comp2('ib_stack') || IsAutostart("iba");
}
sub autostart_desc_ib_stack()
{
	return autostart_desc_ofed_comp('ib_stack');
}
# enable autostart for the given capability
sub enable_autostart2_ib_stack()
{
	enable_autostart("openibd");
	ofed_comp_change_openib_conf_param('ib_stack', "yes");
}
# disable autostart for the given capability
sub disable_autostart2_ib_stack()
{
	disable_autostart("openibd");
	ofed_comp_change_openib_conf_param('ib_stack', "no");
}

sub start_ib_stack()
{
	my $driver_subdir=$ComponentInfo{'ib_stack'}{'DriverSubdir'};
	start_driver($ComponentInfo{'ib_stack'}{'Name'}, "ib_core", "$driver_subdir/drivers/infiniband/core", "openibd");
}

sub stop_ib_stack()
{
	stop_driver($ComponentInfo{'ib_stack'}{'Name'}, "ib_core", "openibd");
}

sub available_ib_stack()
{
	my $srcdir=$ComponentInfo{'ib_stack'}{'SrcDir'};
# TBD better checks for available?
# check file_glob("$srcdir/SRPMS/compat-rdma*.src.rpm") ne ""
#			|| rpm_exists($rpmsdir, $CUR_OS_VER, "compat-rdma")
	return ( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS" );
}

sub installed_ofed_ib_stack()
{
	my $driver_subdir=$ComponentInfo{'ib_stack'}{'DriverSubdir'};
	return (rpm_is_installed("libibverbs", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& installed_ofed_driver("ib_core", "$driver_subdir", "drivers/infiniband/core")
			 );
}

sub installed_ib_stack()
{
	return (installed_ofed_ib_stack || installed_iba);
}

# only called if installed_ib_stack is true
sub installed_version_ib_stack()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return installed_version_iba;
	}
}

# only called if available_ib_stack is true
sub media_version_ib_stack()
{
	return media_version_ofed();
}

# return 0 on success, 1 on failure
sub run_uninstall($$$)
{
	my $stack = shift();
	my $cmd = shift();
	my $cmdargs = shift();

	if ( "$cmd" ne "" && -e "$cmd" ) {
		NormalPrint "\nUninstalling $stack: chroot /$ROOT $cmd $cmdargs\n";
		if (0 != system("yes | chroot /$ROOT $cmd $cmdargs")) {
			NormalPrint "Unable to uninstall $stack\n";
			return 1;
		}
	}
	return 0;
}

# manual remove of quicksilver in case iba_config is lost
sub uninstall_quicksilver()
{
	if (installed_mpisrc) {
		uninstall_mpisrc("", " mpisrc ");
	}
	if (installed_mpidev) {
		uninstall_mpidev("", " mpidev ");
	}
	if (installed_mpi) {
		uninstall_mpi("", " mpi ");
	}
	if (installed_udapl) {
		uninstall_udapl("", " udapl ");
	}
	if (installed_rds) {
		uninstall_rds("", " rds ");
	}
	if (installed_sdp) {
		uninstall_sdp("", " sdp ");
	}
	if (installed_ipoib) {
		uninstall_ipoib("", " ipoib ");
	}
	if (installed_inic) {
		uninstall_inic("", " inic ");
	}
	if (installed_ifibre) {
		uninstall_ifibre("", " ifibre ");
	}
	if (installed_ibdev) {
		uninstall_ibdev("", " ibdev ");
	}
	if (installed_kdapl) {
		uninstall_kdapl("", " iba kdapl ");
	}
	if (installed_ibboot) {
		uninstall_ibboot("", " iba ibboot ");
	}
	if (installed_iba) {
		uninstall_iba("", " iba ");
	}
}

# uninstall 3rd party and older IB stacks
# only called when ib_stack is not installed, hence it can also safely
# uninstall files/rpms which may overlap with the ib_stack
# return 0 on success, != 0 on failure
sub	uninstall_old_stacks($)
{
	my $prompt = shift();
	my $ret = 0;

	if ( $prompt) {
		NormalPrint "About to Uninstall previous IB Software Installations...\n";
		HitKeyCont;
	}

	# FF for OFED requires oftools
	# hence we can conclude if FF for OFED is installed by testing
	# for iba_porttool (which is unique to oftools for OFED)
	# this way if FF for OFED is already installed, we
	# will not run iba_config -u
	# also check our name so we don't recursively call ourselves
	# However if FF for QS or QS is installed, we want to run uninstall
	if (-e "$ROOT/sbin/iba_config"
		&& ! -e "$ROOT$BASE_DIR/version_ofed"
		&& ! -e "$ROOT/sbin/iba_porttool"
		&& ! -e "$ROOT/opt/iba/ib_tools/iba_porttool"
		&& my_basename($0) ne "iba_config"
		) {
		$ret |= run_uninstall("QLogic/QuickSilver/SilverStorm IB Stack", "$ROOT/sbin/iba_config", "-u -r '$ROOT'");
	}

	# uninstall Mellanox OFED
	$ret |= run_uninstall("Mellanox OFED IB Stack", "/sbin/mlnx_en_uninstall.sh", "" );
	# uninstall modern OFED
	my $ofed_uninstall=`chroot /$ROOT which ofed_uninstall.sh 2>/dev/null`;
	$ret |= run_uninstall("OFED IB Stack", "$ofed_uninstall", "");
	my $prefix = ofed_get_prefix();
	$ret |= run_uninstall("OFED IB Stack", "$prefix/sbin/ofed_uninstall.sh", "" );
	$ret |= run_uninstall("OFED IB Stack", "$prefix/uninstall_gen2.sh", "" );
	$ret |= run_uninstall("OFED IB Stack", "$prefix/uninstall.sh", "" );
	ofed_cleanup_mpitests();

	# uninstall TopSpin/Cisco
	if (rpm_uninstall_matches("TopSpin/Cisco IB Stack", "topspin-ib", "")) {
		NormalPrint "Unable to uninstall TopSpin/Cisco IB Stack\n";
		$ret = 1;
	}

	# uninstall Voltaire
	if (rpm_uninstall_matches("Voltaire IB Stack", "Voltaire", "4.0.0_5")) {
		NormalPrint "Unable to uninstall Voltaire IB Stack\n";
		$ret = 1;
	}

	# uninstall Mellanox
	if ("$ENV{MTHOME}" ne "") {
		$ret |= run_uninstall("Mellanox IB Stack", "$ENV{MTHOME}/uninstall.sh", "");
	}
	$ret |= run_uninstall("Mellanox IB Stack", "/usr/mellanox/uninstall.sh", "");
	$ret |= run_uninstall("Mellanox EN driver", "/sbin/mlnx_en_uninstall.sh", "" );
	# uninstall Mellanox mtnic
	if ( -d "$ROOT/lib/modules/$CUR_OS_VER/kernel/drivers/net/mtnic" ) {
		NormalPrint "\nUninstalling mtnic driver: chroot /$ROOT /sbin/rmmod mtnic >/dev/null 2>&1; chroot /$ROOT rm -rf /lib/modules/*/kernel/drivers/net/mtnic\n";
		system("chroot /$ROOT /sbin/rmmod mtnic >/dev/null 2>&1; chroot /$ROOT rm -rf /lib/modules/*/kernel/drivers/net/mtnic");
	}

	# workaround a %preun problem in RHEL 5 which included OFED 1.1
	rpm_uninstall_matches("OFED 1.1 iscsi","open-iscsi-2.0-754","",
   				"--nodeps --notriggers --noscripts");
	rpm_uninstall_matches("OFED 1.1","openib-1.1","",
   				"--nodeps --notriggers --noscripts");

	# workaround a %preun problem in RHEL 5.1 which included OFED 1.2
	rpm_uninstall_matches("OFED 1.2","openib-1.2","",
   				"--nodeps --notriggers --noscripts");

	# workaround a %preun problem in RHEL 5.3 which included OFED 1.3
	rpm_uninstall_matches("OFED 1.3","iscsi-target-utils-0.1-20080828","",
   				"--nodeps --notriggers --noscripts");
	rpm_uninstall_matches("OFED 1.3","tgt-0.1-20080828","",
   				"--nodeps --notriggers --noscripts");

	# workaround a %preun problem in SLES11 which included OFED 1.4
	rpm_uninstall_matches("OFED 1.4","opensm-3.2.3_20081117_b70e2d2-1.10","",
   				"--nodeps --notriggers --noscripts");
	rpm_uninstall_matches("OFED 1.4","ofed-1.4.0-11.12","",
   				"--nodeps --notriggers --noscripts");

	$ret |= uninstall_old_ofed_rpms("any", "silent", "previous OFED");

	my $old_ofed = file_glob("$ROOT/usr/local/ofed*");
	if ("$old_ofed" ne "") {
		NormalPrint "\nUninstalling previous OFED code: rm -rf $ROOT/usr/local/ofed*\n";
		system("rm -rf $ROOT/usr/local/ofed* >/dev/null 2>/dev/null");
	}

	uninstall_quicksilver();	# just in case iba_config was lost

	# some other possible stray files which could be left around
	system("rm -rf $ROOT/usr/include/infiniband/complib");
	system("rm -rf $ROOT/usr/include/infiniband/vendor");
	system("rm -rf $ROOT/usr/include/infiniband/opensm");
	system("rm -rf $ROOT/usr/include/infiniband/iba");
	system("rm -rf $ROOT/usr/libosmcomp*");
	system("rm -rf $ROOT/usr/libosmvendor*");
	system("rm -rf $ROOT/usr/libopensm*");
	system("rm -rf $ROOT/usr/bin/opensm");
	system("rm -rf $ROOT/usr/bin/osmtest");
	system("rm -rf $ROOT/usr/local/include/infiniband/complib");
	system("rm -rf $ROOT/usr/local/include/infiniband/vendor");
	system("rm -rf $ROOT/usr/local/include/infiniband/opensm");
	system("rm -rf $ROOT/usr/local/include/infiniband/iba");
	system("rm -rf $ROOT/usr/local/libosmcomp*");
	system("rm -rf $ROOT/usr/local/libosmvendor*");
	system("rm -rf $ROOT/usr/local/libopensm*");
	system("rm -rf $ROOT/usr/local/bin/opensm");
	system("rm -rf $ROOT/usr/local/bin/osmtest");

	return $ret;
}

# return 0 on success, !=0 on failure
sub build_ib_stack($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild

	init_ofed_rpm_info($osver);

	# Before we do any builds make sure old stacks removed so we don't
	# build against the wrong version of dependent rpms
	if (0 != uninstall_prev_versions()) {
		return 1;
	}

	if (ROOT_is_set()) {
		# build in current image
		my $save_ROOT=$ROOT;
		$ROOT='/';
		my $rc =  build_ofed("@Components", "@Components", $osver, $debug,$build_temp,$force);
		$ROOT=$save_ROOT;
		return $rc;
	} else {
		return build_ofed("@Components", "@Components", $osver, $debug,$build_temp,$force);
	}
}

sub need_reinstall_ib_stack($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ib_stack', $install_list, $installing_list));
}

sub check_os_prereqs_ib_stack
{
 	return rpm_check_os_prereqs("ib_stack", "any", (
				'pciutils',
				# required by compat-rdma
				'lsof',
				# required by ibutils
		   		"tcl 8.4", "tk", 'libstdc++ any user'
   				));
}

sub preinstall_ib_stack($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ib_stack", $install_list, $installing_list);
}

sub install_ib_stack($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'ib_stack'}{'SrcDir'};

	print_install_banner_ofed_comp('ib_stack');

	#override the udev permissions.
	install_udev_permissions("$srcdir/config");

	#edit_modconf("$srcdir/config");
	edit_limitsconf("$srcdir/config");

	# Check $BASE_DIR directory ...exist 
	check_config_dirs();
	check_dir("/opt/iba");

	copy_systool_file("$srcdir/comp.pl", "/opt/iba/.comp_ofed.pl");

	install_ofed_comp('ib_stack', $install_list);

	# in some recovery situations OFED doesn't properly restore openib.conf
	# this makes sure the SMA NodeDesc is properly set so uname -n is used
	change_openib_conf_param('NODE_DESC_HOSTNAME', '@');
	prompt_openib_conf_param('RENICE_IB_MAD', 'OFED SMI/GSI renice', "y");
	# QIB driver has replaced IPATH, make sure IPATH disabled
	change_openib_conf_param('IPATH_LOAD', 'no');
	if (!build_option_is_allowed($CUR_OS_VER, "--with-qib-mod", %ofed_kernel_ib_options)) {
		change_openib_conf_param('QIB_LOAD', 'no');
	} else {
		change_openib_conf_param('QIB_LOAD', 'yes');
	}
	if (!build_option_is_allowed($CUR_OS_VER, "--with-kcopy-mod", %ofed_kernel_ib_options)) {
		change_openib_conf_param('KCOPY_LOAD', 'no');
	} else {
		change_openib_conf_param('KCOPY_LOAD', 'yes');
	}

	copy_data_file("$srcdir/Version", "$BASE_DIR/version_ofed");

	# prevent distro's open IB from loading
	#add_blacklist("ib_mthca");
	#add_blacklist("ib_ipath");
	disable_distro_ofed();

	need_reboot();
	$ComponentWasInstalled{'ib_stack'}=1;
	#enable_openib_stack();

	# we need to generate new initramfs-`uname -r`.img for RHEL6.6 and 7 only
	# if dracut has rdma/ib_qib module as it doen't allow openibd to  load new modules
	# in system
	if (("$CUR_VENDOR_VER" eq 'ES7') || ("$CUR_VENDOR_VER" eq 'ES6') || ("$CUR_VENDOR_VER" eq 'ES12')
	   ) {
		my $ret = 0;
		if ("$CUR_VENDOR_VER" eq 'ES6') {
			$ret = system("lsinitrd | grep ib_qib\.ko || lsinitrd | grep mlx4_core\.ko > /dev/null");
		} elsif ("$CUR_VENDOR_VER" eq 'ES7'){
			$ret = system("lsinitrd | grep rdma | egrep -v .rdma || lsinitrd | grep mlx4_core\.ko > /dev/null");
		} else {
			$ret = system("dracut --list-modules | grep qib | egrep -v .qib || dracut --list-modules | grep mlx4 > /dev/null");
		}

		if ($ret == 0) {
			my $initramfs_path="/boot";
			my $kernel_version=`uname -r`;
			chomp($kernel_version);
			my $initramfs_fname="";
			if ("$CUR_VENDOR_VER" eq 'ES12') {
				$initramfs_fname="initrd-$kernel_version";
			} else {
				$initramfs_fname="initramfs-$kernel_version.img";
			}
			my $initramfs_backup_fname="$initramfs_fname.backup";
			my $initramfs_new_fname="$initramfs_fname.new";

			if ( !(-e "$initramfs_path/$initramfs_backup_fname") ) {
				NormalPrint("rdma module present, generating new $initramfs_fname\n");

				#backup initrd first and then generate new one
				$ret = system("cp -f $initramfs_path/$initramfs_fname $initramfs_path/$initramfs_backup_fname");
				if ($ret != 0) {
					NormalPrint("Error backing up $initramfs_path/$initramfs_fname\nAborting...\n");
					exit 1;
				}
				NormalPrint("$initramfs_backup_fname backup is generated\n");

				#Now generate new initramfs.img
				if ("$CUR_VENDOR_VER" eq 'ES6') {
					$ret = system("dracut --omit-drivers \".*/infiniband/.*\" --omit-drivers \"mlx4_core\" $initramfs_path/$initramfs_new_fname > nohup.out 2>&1");
				} elsif ("$CUR_VENDOR_VER" eq 'ES7') {
					$ret = system("dracut -o \"rdma\" --omit-drivers \"mlx4_core\" $initramfs_path/$initramfs_new_fname > nohup.out 2>&1");
				} else {
					$ret = system("dracut -o \"qib\" --omit-drivers \"mlx4_core\" $initramfs_path/$initramfs_new_fname > nohup.out 2>&1");
				}

				if ($ret != 0) {
					NormalPrint("Error generating $initramfs_fname\nRestoring original\n");
					system("cp -f $initramfs_path/$initramfs_backup_fname $initramfs_path/$initramfs_fname");
					NormalPrint("restored stock $initramfs_fname\nAborting installation\n");
					exit 1;
				}
				NormalPrint("Warnings from dracut:\n");
				system("cat nohup.out;rm -f nohup.out");
				system("rm -f $initramfs_path/$initramfs_fname");
				system("mv $initramfs_path/$initramfs_new_fname $initramfs_path/$initramfs_fname");
				NormalPrint("New $initramfs_fname generated\n");
			}
		}
	}

}

sub postinstall_ib_stack($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('ib_stack');
}

sub uninstall_ib_stack($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	my $driver_subdir=$ComponentInfo{'ib_stack'}{'DriverSubdir'};
	print_uninstall_banner_ofed_comp('ib_stack');
	stop_ib_stack;

	# allow open IB to load
	#remove_blacklist("ib_mthca");
	#remove_blacklist("ib_ipath");

	# ofed rpm -e will keep an rpmsave copy of openib.conf for us
	uninstall_ofed_comp('ib_stack', $install_list, $uninstalling_list, 'verbose');
	remove_driver_dirs($driver_subdir);
	#remove_modules_conf;
	remove_limits_conf;

	remove_udev_permissions;

	system("rm -rf $ROOT$BASE_DIR/version_ofed");
	system("rm -rf $ROOT/opt/iba/.comp_ofed.pl");
	system "rmdir $ROOT/opt/iba 2>/dev/null";	# remove only if empty
	system "rmdir $ROOT$BASE_DIR 2>/dev/null";	# remove only if empty
	system "rmdir $ROOT$IBA_CONFIG_DIR 2>/dev/null";	# remove only if empty
	if (0 != uninstall_old_stacks(0)) {
		Abort "Unable to uninstall old IB stacks\n";
	}
	need_reboot();
	$ComponentWasInstalled{'ib_stack'}=0;
	#enable_openib_stack();
	if (installed_iba || installed_kdapl || installed_ibboot) {
		print_separator;
		uninstall_kdapl("", " iba kdapl ");
		print_separator;
		uninstall_ibboot("", " iba ibboot ");
		print_separator;
		uninstall_iba("", " iba ");
	}

	#restore original initramfs on uninstall
	if (("$CUR_VENDOR_VER" eq 'ES7') || ("$CUR_VENDOR_VER" eq 'ES6') || ("$CUR_VENDOR_VER" eq 'ES12')
	   ) {
		my $initramfs_path="/boot";
 		my $kernel_version=`uname -r`;
		chomp($kernel_version);
		my $initramfs_fname="";
		if ("$CUR_VENDOR_VER" eq 'ES12') {
			$initramfs_fname="initrd-$kernel_version";
		} else {
			$initramfs_fname="initramfs-$kernel_version.img";
		}
		my $initramfs_backup_fname="$initramfs_fname.backup";

		if (-e "$initramfs_path/$initramfs_backup_fname") {

			NormalPrint("Restoring stock $initramfs_fname\n");
			my $ret = system("cp -f $initramfs_path/$initramfs_backup_fname $initramfs_path/$initramfs_fname");
			if ($ret != 0) {
				NormalPrint("Error restoring stock $initramfs_fname\nStock $initramfs_fname lies at $initramfs_path/$initramfs_backup_fname\n");
			} else {
				system("rm -f $initramfs_path/$initramfs_backup_fname");
				NormalPrint("Stock $initramfs_fname restored\n");
			}
		}
	}
}
# ==========================================================================
# OFED ofed_mlx4 installation

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_ofed_mlx4()
{
	return IsAutostart_ofed_comp2('ofed_mlx4');
}
sub autostart_desc_ofed_mlx4()
{
	return autostart_desc_ofed_comp('ofed_mlx4');
}
# enable autostart for the given capability
sub enable_autostart2_ofed_mlx4()
{
	enable_autostart_ofed_comp2('ofed_mlx4');
}
# disable autostart for the given capability
sub disable_autostart2_ofed_mlx4()
{
	disable_autostart_ofed_comp2('ofed_mlx4');
}

# these are not presently called, which is good since ofed is hard to do this
#sub start_ofed_mlx4()
#{
#	my $driver_subdir=$ComponentInfo{'ofed_mlx4'}{'DriverSubdir'};
#	start_driver($ComponentInfo{'ofed_mlx4'}{'Name'}, "ib_core", $driver_subdir, "openibd");
#}

#sub stop_ofed_mlx4()
#{
#	stop_driver($ComponentInfo{'ofed_mlx4'}{'Name'}, "ib_core", "openibd");
#}

sub available_ofed_mlx4()
{
	my $srcdir=$ComponentInfo{'ofed_mlx4'}{'SrcDir'};
	return ( (-d "$srcdir/SRPMS" || -d "$srcdir/RPMS" )
			&& build_option_is_allowed($CUR_OS_VER, "--with-mlx4-mod", %ofed_kernel_ib_options));
}

sub installed_ofed_mlx4()
{
	my $driver_subdir=$ComponentInfo{'ofed_mlx4'}{'DriverSubdir'};
	return (rpm_is_installed("libmlx4", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& (installed_ofed_driver("mlx4_ib", "$driver_subdir", "drivers/infiniband/hw/mlx4")
				&& installed_ofed_driver("mlx4_core", "$driver_subdir", "drivers/net/mlx4"))
			 );
}

# only called if installed_ofed_mlx4 is true
sub installed_version_ofed_mlx4()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_ofed_mlx4 is true
sub media_version_ofed_mlx4()
{
	return media_version_ofed();
}

sub build_ofed_mlx4($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_mlx4($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_mlx4', $install_list, $installing_list));
}

sub preinstall_ofed_mlx4($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_mlx4", $install_list, $installing_list);
}

sub install_ofed_mlx4($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_mlx4');
	install_ofed_comp('ofed_mlx4', $install_list);

	need_reboot();
	$ComponentWasInstalled{'ofed_mlx4'}=1;
}

sub postinstall_ofed_mlx4($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('ofed_mlx4');
}

sub uninstall_ofed_mlx4($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_mlx4');
	# TBD stop_ofed_mlx4;
	uninstall_ofed_comp('ofed_mlx4', $install_list, $uninstalling_list, 'verbose');
	need_reboot();
	$ComponentWasInstalled{'ofed_mlx4'}=0;
}


# ==========================================================================
# OFED ib_stack development installation

sub available_ib_stack_dev()
{
	my $srcdir=$ComponentInfo{'ib_stack_dev'}{'SrcDir'};
	return ( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS" );
}

sub installed_ib_stack_dev()
{
	return ((rpm_is_installed("libibverbs-devel", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed")
			|| installed_ibdev);
}

# only called if installed_ib_stack_dev is true
sub installed_version_ib_stack_dev()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return installed_version_ibdev;
	}
}

# only called if available_ib_stack_dev is true
sub media_version_ib_stack_dev()
{
	return media_version_ofed();
}

sub build_ib_stack_dev($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ib_stack_dev($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ib_stack_dev', $install_list, $installing_list));
}

sub preinstall_ib_stack_dev($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ib_stack_dev", $install_list, $installing_list);
}

sub install_ib_stack_dev($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ib_stack_dev');
	install_ofed_comp('ib_stack_dev', $install_list);

	$ComponentWasInstalled{'ib_stack_dev'}=1;
}

sub postinstall_ib_stack_dev($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	#ofed_restore_autostart('ib_stack_dev');
}

sub uninstall_ib_stack_dev($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ib_stack_dev');
	uninstall_ofed_comp('ib_stack_dev', $install_list, $uninstalling_list, 'verbose');
	$ComponentWasInstalled{'ib_stack_dev'}=0;
	if (installed_ibdev) {
		print_separator;
		uninstall_ibdev("", " ibdev ");
	}
}

# ==========================================================================
# OFED ofed_ipoib installation

my $FirstIPoIBInterface=0; # first device is ib0

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_ofed_ipoib()
{
	return IsAutostart_ofed_comp2('ofed_ipoib') || IsAutostart("ipoib");
}
sub autostart_desc_ofed_ipoib()
{
	return autostart_desc_ofed_comp('ofed_ipoib');
}
# enable autostart for the given capability
sub enable_autostart2_ofed_ipoib()
{
	enable_autostart_ofed_comp2('ofed_ipoib');
}
# disable autostart for the given capability
sub disable_autostart2_ofed_ipoib()
{
	disable_autostart_ofed_comp2('ofed_ipoib');
	if (Exist_ifcfg("ib")) {
		print "$ComponentInfo{'ofed_ipoib'}{'Name'} will autostart if ifcfg files exists\n";
		print "To fully disable autostart, it's recommended to also remove related ifcfg files\n";
		Remove_ifcfg("ib_ipoib","$ComponentInfo{'ofed_ipoib'}{'Name'}","ib");
	}
}

# these are not presently called, which is good since ofed is hard to do this
#sub start_ofed_ipoib()
#{
#	my $driver_subdir=$ComponentInfo{'ofed_ipoib'}{'DriverSubdir'};
#	start_driver($ComponentInfo{'ofed_ipoib'}{'Name'}, "ib_core", $driver_subdir, "openibd");
#}

#sub stop_ofed_ipoib()
#{
#	stop_driver($ComponentInfo{'ofed_ipoib'}{'Name'}, "ib_core", "openibd");
#}

sub available_ofed_ipoib()
{
	my $srcdir=$ComponentInfo{'ofed_ipoib'}{'SrcDir'};
	return ( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS" );
}

sub installed_ofed_ipoib()
{
	my $driver_subdir=$ComponentInfo{'ofed_ipoib'}{'DriverSubdir'};
	return ((-e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& installed_ofed_driver("ib_ipoib", "$driver_subdir", "drivers/infiniband/ulp/ipoib")
			 ) || installed_ipoib);
}

# only called if installed_ofed_ipoib is true
sub installed_version_ofed_ipoib()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return installed_version_ipoib;	# QuickSilver version
	}
}

# only called if available_ofed_ipoib is true
sub media_version_ofed_ipoib()
{
	return media_version_ofed();
}

sub build_ofed_ipoib($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_ipoib($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_ipoib', $install_list, $installing_list));
}

sub preinstall_ofed_ipoib($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_ipoib", $install_list, $installing_list);
}

sub install_ofed_ipoib($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_ipoib');
	install_ofed_comp('ofed_ipoib', $install_list);

	prompt_openib_conf_param('SET_IPOIB_CM', 'IPoIB Connected Mode', "y");
	# bonding is more involved, require user to edit to enable that
	Config_ifcfg(1,"$ComponentInfo{'ofed_ipoib'}{'Name'}","ib", "$FirstIPoIBInterface",1);
	check_network_config;
	#Config_IPoIB_cfg;
	#add_insserv_conf("openibd", "network");
	need_reboot();
	$ComponentWasInstalled{'ofed_ipoib'}=1;
}

sub postinstall_ofed_ipoib($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('ofed_ipoib');
}

sub uninstall_ofed_ipoib($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_ipoib');
	# TBD stop_ofed_ipoib;
	uninstall_ofed_comp('ofed_ipoib', $install_list, $uninstalling_list, 'verbose');
	#del_insserv_conf("openibd", "network");
	Remove_ifcfg("ib_ipoib","$ComponentInfo{'ofed_ipoib'}{'Name'}","ib");
	need_reboot();
	$ComponentWasInstalled{'ofed_ipoib'}=0;
	if (installed_ipoib) {
		print_separator;
		uninstall_ipoib("", " ipoib ");
	}
}

# ==========================================================================
# OFED ofed_ib_bonding installation

# ib_bonding does not have any autostart configuration

sub available_ofed_ib_bonding()
{
	my $srcdir=$ComponentInfo{'ofed_ib_bonding'}{'SrcDir'};
	return ( (-d "$srcdir/SRPMS" || -d "$srcdir/RPMS")
			&& available_srpm("ib-bonding", $CUR_OS_VER, $CUR_OS_VER));
}

sub installed_ofed_ib_bonding()
{
	# TBD - should we detect OFED vs distro ib-bonding?
	return (-e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("ib-bonding", $CUR_OS_VER));
}

# only called if installed_ofed_ib_bonding is true
sub installed_version_ofed_ib_bonding()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_ofed_ib_bonding is true
sub media_version_ofed_ib_bonding()
{
	return media_version_ofed();
}

sub build_ofed_ib_bonding($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_ib_bonding($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_ib_bonding', $install_list, $installing_list));
}

sub preinstall_ofed_ib_bonding($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_ib_bonding", $install_list, $installing_list);
}

sub install_ofed_ib_bonding($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_ib_bonding');
	install_ofed_comp('ofed_ib_bonding', $install_list);

	need_reboot();
	$ComponentWasInstalled{'ofed_ib_bonding'}=1;
}

sub postinstall_ofed_ib_bonding($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	#ofed_restore_autostart('ofed_ib_bonding');
}

sub uninstall_ofed_ib_bonding($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_ib_bonding');
	# TBD stop_ofed_ib_bonding;
	uninstall_ofed_comp('ofed_ib_bonding', $install_list, $uninstalling_list, 'verbose');
	need_reboot();
	$ComponentWasInstalled{'ofed_ib_bonding'}=0;
}

# ==========================================================================
# OFED ofed_sdp installation

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_ofed_sdp()
{
	return IsAutostart_ofed_comp2('ofed_sdp') || IsAutostart("ics_sdp");
}
sub autostart_desc_ofed_sdp()
{
	return autostart_desc_ofed_comp('ofed_sdp');
}
# enable autostart for the given capability
sub enable_autostart2_ofed_sdp()
{
	enable_autostart_ofed_comp2('ofed_sdp');
}
# disable autostart for the given capability
sub disable_autostart2_ofed_sdp()
{
	disable_autostart_ofed_comp2('ofed_sdp');
}

# these are not presently called, which is good since ofed is hard to do this
#sub start_ofed_sdp()
#{
#	my $driver_subdir=$ComponentInfo{'ofed_sdp'}{'DriverSubdir'};
#	start_driver($ComponentInfo{'ofed_sdp'}{'Name'}, "ib_core", $driver_subdir, "openibd");
#}

#sub stop_ofed_sdp()
#{
#	stop_driver($ComponentInfo{'ofed_sdp'}{'Name'}, "ib_core", "openibd");
#}

sub available_ofed_sdp()
{
	my $srcdir=$ComponentInfo{'ofed_sdp'}{'SrcDir'};
	return ( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS" );
}

sub installed_ofed_sdp()
{
	my $driver_subdir=$ComponentInfo{'ofed_sdp'}{'DriverSubdir'};
	return ((rpm_is_installed("libsdp", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& installed_ofed_driver("ib_sdp", "$driver_subdir", "drivers/infiniband/ulp/sdp")
			 )
			|| installed_sdp);
}

# only called if installed_ofed_sdp is true
sub installed_version_ofed_sdp()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return installed_version_sdp;
	}
}

# only called if available_ofed_sdp is true
sub media_version_ofed_sdp()
{
	return media_version_ofed();
}

sub build_ofed_sdp($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_sdp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_sdp', $install_list, $installing_list));
}

sub preinstall_ofed_sdp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_sdp", $install_list, $installing_list);
}

sub install_ofed_sdp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_sdp');
	install_ofed_comp('ofed_sdp', $install_list);

	need_reboot();
	$ComponentWasInstalled{'ofed_sdp'}=1;
}

sub postinstall_ofed_sdp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('ofed_sdp');
}

sub uninstall_ofed_sdp($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_sdp');
	# TBD stop_ofed_sdp;
	uninstall_ofed_comp('ofed_sdp', $install_list, $uninstalling_list, 'verbose');
	need_reboot();
	$ComponentWasInstalled{'ofed_sdp'}=0;
	if (installed_sdp) {
		print_separator;
		uninstall_sdp("", " sdp ");
	}
}

# ==========================================================================
# OFED ofed_rds installation

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_ofed_rds()
{
	return IsAutostart_ofed_comp2('ofed_rds') || IsAutostart("rds");
}
sub autostart_desc_ofed_rds()
{
	return autostart_desc_ofed_comp('ofed_rds');
}
# enable autostart for the given capability
sub enable_autostart2_ofed_rds()
{
	enable_autostart_ofed_comp2('ofed_rds');
}
# disable autostart for the given capability
sub disable_autostart2_ofed_rds()
{
	disable_autostart_ofed_comp2('ofed_rds');
}

# these are not presently called, which is good since ofed is hard to do this
#sub start_ofed_rds()
#{
#	my $driver_subdir=$ComponentInfo{'ofed_rds'}{'DriverSubdir'};
#	start_driver($ComponentInfo{'ofed_rds'}{'Name'}, "ib_core", $driver_subdir, "openibd");
#}
#
#sub stop_ofed_rds()
#{
#	stop_driver($ComponentInfo{'ofed_rds'}{'Name'}, "ib_core", "openibd");
#}

sub available_ofed_rds()
{
	my $srcdir=$ComponentInfo{'ofed_rds'}{'SrcDir'};
	return ( (-d "$srcdir/SRPMS" || -d "$srcdir/RPMS")
			&& build_option_is_allowed($CUR_OS_VER, "--with-rds-mod", %ofed_kernel_ib_options));
}

sub installed_ofed_rds()
{
	my $driver_subdir=$ComponentInfo{'ofed_rds'}{'DriverSubdir'};
	return ((rpm_is_installed("rds-tools", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& installed_ofed_driver("rds", "$driver_subdir", "net/rds")
			 )
			|| installed_rds);
}

# only called if installed_ofed_rds is true
sub installed_version_ofed_rds()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return installed_version_rds;
	}
}

# only called if available_ofed_rds is true
sub media_version_ofed_rds()
{
	return media_version_ofed();
}

sub build_ofed_rds($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_rds($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_rds', $install_list, $installing_list));
}

sub preinstall_ofed_rds($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_rds", $install_list, $installing_list);
}

sub install_ofed_rds($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_rds');
	install_ofed_comp('ofed_rds', $install_list);

	need_reboot();
	$ComponentWasInstalled{'ofed_rds'}=1;
}

sub postinstall_ofed_rds($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('ofed_rds');
}

sub uninstall_ofed_rds($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_rds');
	# TBD stop_ofed_rds;
	uninstall_ofed_comp('ofed_rds', $install_list, $uninstalling_list, 'verbose');
	need_reboot();
	$ComponentWasInstalled{'ofed_rds'}=0;
	if (installed_rds) {
		print_separator;
		uninstall_rds("", " rds ");
	}
}

# ==========================================================================
# OFED ofed_udapl installation

sub available_ofed_udapl()
{
	my $srcdir=$ComponentInfo{'ofed_udapl'}{'SrcDir'};
	return ( (-d "$srcdir/SRPMS" || -d "$srcdir/RPMS" )
			&& available_srpm("compat-dapl", "user", $CUR_OS_VER)
			&& available_srpm("dapl", "user", $CUR_OS_VER));
}

sub installed_ofed_udapl()
{
	return ((rpm_is_installed("dapl", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed" )
			|| installed_udapl);
}

# only called if installed_ofed_udapl is true
sub installed_version_ofed_udapl()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return installed_version_udapl;
	}
}

# only called if available_ofed_udapl is true
sub media_version_ofed_udapl()
{
	return media_version_ofed();
}

sub build_ofed_udapl($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_udapl($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_udapl', $install_list, $installing_list));
}

sub preinstall_ofed_udapl($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_udapl", $install_list, $installing_list);
}

sub install_ofed_udapl($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_udapl');
	install_ofed_comp('ofed_udapl', $install_list);

	$ComponentWasInstalled{'ofed_udapl'}=1;
}

sub postinstall_ofed_udapl($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	#ofed_restore_autostart('ofed_udapl');
}

sub uninstall_ofed_udapl($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_udapl');
	# TBD stop_ofed_udapl;
	uninstall_ofed_comp('ofed_udapl', $install_list, $uninstalling_list, 'verbose');
	$ComponentWasInstalled{'ofed_udapl'}=0;
	if (installed_udapl) {
		print_separator;
		uninstall_udapl("", " udapl ");
	}
}

# ==========================================================================
# OFED mpi-selector installation

sub available_mpi_selector()
{
	my $srcdir=$ComponentInfo{'mpi_selector'}{'SrcDir'};
	return ( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS" );
}

sub installed_mpi_selector()
{
	return (rpm_is_installed("mpi-selector", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed");
}

# only called if installed_mpi_selector is true
sub installed_version_mpi_selector()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_mpi_selector is true
sub media_version_mpi_selector()
{
	return media_version_ofed();
}

sub build_mpi_selector($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_mpi_selector($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('mpi_selector', $install_list, $installing_list));
}

sub check_os_prereqs_mpi_selector
{
 	return rpm_check_os_prereqs("mpi_selector", "any", ( "tcsh"))
}

sub preinstall_mpi_selector($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("mpi_selector", $install_list, $installing_list);
}

sub install_mpi_selector($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('mpi_selector');
	install_ofed_comp('mpi_selector', $install_list);

	$ComponentWasInstalled{'mpi_selector'}=1;
}

sub postinstall_mpi_selector($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	#ofed_restore_autostart('mpi_selector');
}

sub uninstall_mpi_selector($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	uninstall_ofed_comp('mpiRest', $install_list, $uninstalling_list, 'verbose');
	print_uninstall_banner_ofed_comp('mpi_selector');
	uninstall_ofed_comp('mpi_selector', $install_list, $uninstalling_list, 'verbose');
	ofed_cleanup_mpitests();
	$ComponentWasInstalled{'mpi_selector'}=0;
}

# ==========================================================================
# OFED MVAPICH2 for gcc installation

sub available_mvapich2()
{
	my $srcdir=$ComponentInfo{'mvapich2'}{'SrcDir'};
	return ( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS" );
}

sub installed_mvapich2()
{
	return ((rpm_is_installed("mvapich2_gcc", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed")
			|| installed_mpi);
}

# only called if installed_mvapich2 is true
sub installed_version_mvapich2()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return installed_version_mpi;
	}
}

# only called if available_mvapich2 is true
sub media_version_mvapich2()
{
	return media_version_ofed();
}

sub build_mvapich2($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_mvapich2($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('mvapich2', $install_list, $installing_list));
}

sub check_os_prereqs_mvapich2
{
 	return rpm_check_os_prereqs("mvapich2", "user", ( "sysfsutils", "libstdc++"));
}

sub preinstall_mvapich2($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("mvapich2", $install_list, $installing_list);
}

sub install_mvapich2($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('mvapich2');

	# make sure any old potentially custom built versions of mpi are uninstalled
	rpm_uninstall_list2("any", "--nodeps", 'silent', @{ $ofed_comp_info{'mvapich2'}{'UserRpms'}});
	my $rpmfile = rpm_resolve(ofed_rpms_dir(), "any", "mvapich2_gcc");
	if ( "$rpmfile" ne "" && -e "$rpmfile" ) {
		my $mpich_prefix= "$OFED_prefix/mpi/gcc/mvapich2-"
	   							. rpm_query_attr($rpmfile, "VERSION");
		if ( -d "$mpich_prefix" && GetYesNo ("Remove $mpich_prefix directory?", "y")) {
			LogPrint "rm -rf $mpich_prefix\n";
			system("rm -rf $mpich_prefix");
		}
	}

	install_ofed_comp('mvapich2', $install_list);

	$ComponentWasInstalled{'mvapich2'}=1;
}

sub postinstall_mvapich2($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	#ofed_restore_autostart('mvapich2');
}

sub uninstall_mvapich2($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('mvapich2');
	uninstall_ofed_comp('mvapich2', $install_list, $uninstalling_list, 'verbose');
	ofed_cleanup_mpitests();
	$ComponentWasInstalled{'mvapich2'}=0;
}
# ==========================================================================
# OFED OpenMpi for gcc installation

sub available_openmpi()
{
	my $srcdir=$ComponentInfo{'openmpi'}{'SrcDir'};
	return ( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS" );
}

sub installed_openmpi()
{
	return ((rpm_is_installed("openmpi_gcc", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed")
			|| installed_mpi);
}

# only called if installed_openmpi is true
sub installed_version_openmpi()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return installed_version_mpi;
	}
}

# only called if available_openmpi is true
sub media_version_openmpi()
{
	return media_version_ofed();
}

sub build_openmpi($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_openmpi($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('openmpi', $install_list, $installing_list));
}

sub check_os_prereqs_openmpi
{
 	return rpm_check_os_prereqs("openmpi", "user", ( "libstdc++"));
}

sub preinstall_openmpi($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("openmpi", $install_list, $installing_list);
}

sub install_openmpi($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('openmpi');

	# make sure any old potentially custom built versions of mpi are uninstalled
	rpm_uninstall_list2("any", "--nodeps", 'silent', @{ $ofed_comp_info{'openmpi'}{'UserRpms'}});
	my $rpmfile = rpm_resolve(ofed_rpms_dir(), "any", "openmpi_gcc");
	if ( "$rpmfile" ne "" && -e "$rpmfile" ) {
		my $mpich_prefix= "$OFED_prefix/mpi/gcc/openmpi-"
	   							. rpm_query_attr($rpmfile, "VERSION");
		if ( -d "$mpich_prefix" && GetYesNo ("Remove $mpich_prefix directory?", "y")) {
			LogPrint "rm -rf $mpich_prefix\n";
			system("rm -rf $mpich_prefix");
		}
	}

	install_ofed_comp('openmpi', $install_list);

	$ComponentWasInstalled{'openmpi'}=1;
}

sub postinstall_openmpi($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	#ofed_restore_autostart('openmpi');
}

sub uninstall_openmpi($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('openmpi');
	uninstall_ofed_comp('openmpi', $install_list, $uninstalling_list, 'verbose');
	ofed_cleanup_mpitests();
	$ComponentWasInstalled{'openmpi'}=0;
}

# ==========================================================================
# OFED ofed_mpisrc installation

sub available_ofed_mpisrc()
{
	my $srcdir=$ComponentInfo{'ofed_mpisrc'}{'SrcDir'};
# TBD better checks for available?
# check file_glob("$srcdir/SRPMS/mvapich2-*.src.rpm") ne ""
# check file_glob("$srcdir/SRPMS/openmpi-*.src.rpm") ne ""
	return ( (-d "$srcdir/SRPMS" || -d "$srcdir/RPMS" ) );
}

sub installed_ofed_mpisrc()
{
	return ((-e "$ROOT$BASE_DIR/version_ofed"
			&& file_glob("$ROOT/opt/iba/src/MPI/mvapich2*.src.rpm") ne ""
			&& file_glob("$ROOT/opt/iba/src/MPI/openmpi*.src.rpm") ne ""
			&& file_glob("$ROOT/opt/iba/src/MPI/mpitests*.src.rpm") ne "")
			|| installed_mpisrc);
}

# only called if installed_ofed_mpisrc is true
sub installed_version_ofed_mpisrc()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return installed_version_mpisrc;
	}
}

# only called if available_ofed_mpisrc is true
sub media_version_ofed_mpisrc()
{
	return media_version_ofed();
}

sub build_ofed_mpisrc($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_mpisrc($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_mpisrc', $install_list, $installing_list));
}

sub check_os_prereqs_ofed_mpisrc
{
 	return rpm_check_os_prereqs("ofed_mpisrc", "any", 
					 ( @{ $ofed_srpm_info{'openmpi'}{'BuildPrereq'}},
					   @{ $ofed_srpm_info{'mvapich2'}{'BuildPrereq'}} ));
}

sub preinstall_ofed_mpisrc($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_mpisrc", $install_list, $installing_list);
}

sub install_ofed_mpisrc($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'ofed_mpisrc'}{'SrcDir'};

	print_install_banner_ofed_comp('ofed_mpisrc');
	install_ofed_comp('ofed_mpisrc', $install_list);
	check_dir("/opt/iba/src");
	check_dir("/opt/iba/src/MPI");
	# remove old versions (.src.rpm and built .rpm files too)
	system "rm -rf $ROOT/opt/iba/src/MPI/mvapich2[-_]*.rpm 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/openmpi[-_]*.rpm 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/mpitests[-_]*.rpm 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/make.*.res 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/make.*.err 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/make.*.warn 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/.mpiinfo 2>/dev/null";

	# install new versions
	foreach my $srpm ( "mvapich2", "openmpi", "mpitests" ) {
		my $srpmfile = file_glob("$srcdir/$SRPMS_SUBDIR/${srpm}-*.src.rpm");
		if ( "$srpmfile" ne "" ) {
			my $file = my_basename($srpmfile);
			copy_data_file($srpmfile, "/opt/iba/src/MPI/$file");
		}
	}
	copy_systool_file("$srcdir/do_build", "/opt/iba/src/MPI/do_build");
	copy_systool_file("$srcdir/do_mvapich2_build", "/opt/iba/src/MPI/do_mvapich2_build");
	copy_systool_file("$srcdir/do_openmpi_build", "/opt/iba/src/MPI/do_openmpi_build");

	$ComponentWasInstalled{'ofed_mpisrc'}=1;
}

sub postinstall_ofed_mpisrc($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	#ofed_restore_autostart('ofed_mpisrc');
}

sub uninstall_ofed_mpisrc($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_mpisrc');

	# remove old versions (.src.rpm and built .rpm files too)
	system "rm -rf $ROOT/opt/iba/src/MPI/mvapich2[-_]*.rpm 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/openmpi[-_]*.rpm 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/mpitests[-_]*.rpm 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/make.*.res 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/make.*.err 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/make.*.warn 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/.mpiinfo 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/do_build 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/do_mvapich2_build 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/do_openmpi_build 2>/dev/null";
	system "rm -rf $ROOT/opt/iba/src/MPI/.mpiinfo 2>/dev/null";

	uninstall_ofed_comp('ofed_mpisrc', $install_list, $uninstalling_list, 'verbose');
	system "rmdir $ROOT/opt/iba/src/MPI 2>/dev/null"; # remove only if empty
	system "rmdir $ROOT/opt/iba/src 2>/dev/null"; # remove only if empty
	$ComponentWasInstalled{'ofed_mpisrc'}=0;
	if (installed_mpisrc ) {
		print_separator;
		uninstall_mpisrc("", " mpisrc ");
	}
}

# ==========================================================================
# OFED ofed_srp installation

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_ofed_srp()
{
	return IsAutostart_ofed_comp2('ofed_srp');
}
sub autostart_desc_ofed_srp()
{
	return autostart_desc_ofed_comp('ofed_srp');
}
# enable autostart for the given capability
sub enable_autostart2_ofed_srp()
{
	enable_autostart_ofed_comp2('ofed_srp');
}
# disable autostart for the given capability
sub disable_autostart2_ofed_srp()
{
	disable_autostart_ofed_comp2('ofed_srp');
}

# these are not presently called, which is good since ofed is hard to do this
#sub start_ofed_srp()
#{
#	my $driver_subdir=$ComponentInfo{'ofed_srp'}{'DriverSubdir'};
#	start_driver($ComponentInfo{'ofed_srp'}{'Name'}, "ib_core", $driver_subdir, "openibd");
#}

#sub stop_ofed_srp()
#{
#	stop_driver($ComponentInfo{'ofed_srp'}{'Name'}, "ib_core", "openibd");
#}

sub available_ofed_srp()
{
	my $srcdir=$ComponentInfo{'ofed_srp'}{'SrcDir'};
	return ( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS" );
}

sub installed_ofed_srp()
{
	my $driver_subdir=$ComponentInfo{'ofed_srp'}{'DriverSubdir'};
	return (rpm_is_installed("srptools", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& installed_ofed_driver("ib_srp", "$driver_subdir", "drivers/infiniband/ulp/srp")
			 );
}

# only called if installed_ofed_srp is true
sub installed_version_ofed_srp()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_ofed_srp is true
sub media_version_ofed_srp()
{
	return media_version_ofed();
}

sub build_ofed_srp($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_srp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_srp', $install_list, $installing_list));
}

sub preinstall_ofed_srp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_srp", $install_list, $installing_list);
}

sub install_ofed_srp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_srp');
	install_ofed_comp('ofed_srp', $install_list);

	prompt_openib_conf_param('SRPHA_ENABLE', 'OFED SRP High Availability deamon', "n");
	need_reboot();
	$ComponentWasInstalled{'ofed_srp'}=1;
}

sub postinstall_ofed_srp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('ofed_srp');
}

sub uninstall_ofed_srp($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_srp');
	# TBD stop_ofed_srp;
	uninstall_ofed_comp('ofed_srp', $install_list, $uninstalling_list, 'verbose');
	need_reboot();
	$ComponentWasInstalled{'ofed_srp'}=0;
}

# ==========================================================================
# OFED ofed_srpt installation

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_ofed_srpt()
{
	return IsAutostart_ofed_comp2('ofed_srpt');
}
sub autostart_desc_ofed_srpt()
{
	return autostart_desc_ofed_comp('ofed_srpt');
}
# enable autostart for the given capability
sub enable_autostart2_ofed_srpt()
{
	enable_autostart_ofed_comp2('ofed_srpt');
}
# disable autostart for the given capability
sub disable_autostart2_ofed_srpt()
{
	disable_autostart_ofed_comp2('ofed_srpt');
}

# these are not presently called, which is good since ofed is hard to do this
#sub start_ofed_srpt()
#{
#	my $driver_subdir=$ComponentInfo{'ofed_srpt'}{'DriverSubdir'};
#	start_driver($ComponentInfo{'ofed_srpt'}{'Name'}, "ib_core", $driver_subdir, "openibd");
#}

#sub stop_ofed_srpt()
#{
#	stop_driver($ComponentInfo{'ofed_srpt'}{'Name'}, "ib_core", "openibd");
#}

sub available_ofed_srpt()
{
	my $srcdir=$ComponentInfo{'ofed_srpt'}{'SrcDir'};
	return ( (-d "$srcdir/SRPMS" || -d "$srcdir/RPMS" )
			 && build_option_is_allowed($CUR_OS_VER, "--with-srp-target-mod", %ofed_kernel_ib_options));
}

sub installed_ofed_srpt()
{
	my $driver_subdir=$ComponentInfo{'ofed_srpt'}{'DriverSubdir'};
	return (-e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& installed_ofed_driver("ib_srpt", "$driver_subdir", "drivers/infiniband/ulp/srpt")
			 );
}

# only called if installed_ofed_srpt is true
sub installed_version_ofed_srpt()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_ofed_srpt is true
sub media_version_ofed_srpt()
{
	return media_version_ofed();
}

sub build_ofed_srpt($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_srpt($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_srpt', $install_list, $installing_list));
}

sub preinstall_ofed_srpt($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_srpt", $install_list, $installing_list);
}

sub install_ofed_srpt($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_srpt');
	install_ofed_comp('ofed_srpt', $install_list);

	need_reboot();
	$ComponentWasInstalled{'ofed_srpt'}=1;
}

sub postinstall_ofed_srpt($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('ofed_srpt');
}

sub uninstall_ofed_srpt($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_srpt');
	# TBD stop_ofed_srpt;
	uninstall_ofed_comp('ofed_srpt', $install_list, $uninstalling_list, 'verbose');
	need_reboot();
	$ComponentWasInstalled{'ofed_srpt'}=0;
}

# ==========================================================================
# OFED ofed_iser installation

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_ofed_iser()
{
	return IsAutostart_ofed_comp2('ofed_iser');
}
sub autostart_desc_ofed_iser()
{
	return autostart_desc_ofed_comp('ofed_iser');
}
# enable autostart for the given capability
sub enable_autostart2_ofed_iser()
{
	enable_autostart_ofed_comp2('ofed_iser');
}
# disable autostart for the given capability
sub disable_autostart2_ofed_iser()
{
	disable_autostart_ofed_comp2('ofed_iser');
}

# these are not presently called, which is good since ofed is hard to do this
#sub start_ofed_iser()
#{
#	my $driver_subdir=$ComponentInfo{'ofed_iser'}{'DriverSubdir'};
#	start_driver($ComponentInfo{'ofed_iser'}{'Name'}, "ib_core", $driver_subdir, "openibd");
#}

#sub stop_ofed_iser()
#{
#	stop_driver($ComponentInfo{'ofed_iser'}{'Name'}, "ib_core", "openibd");
#}

sub available_ofed_iser()
{
	my $srcdir=$ComponentInfo{'ofed_iser'}{'SrcDir'};
	return ( (-d "$srcdir/SRPMS" || -d "$srcdir/RPMS" )
			&& build_option_is_allowed($CUR_OS_VER, "--with-iser-mod", %ofed_kernel_ib_options));
}

sub installed_ofed_iser()
{
	my $driver_subdir=$ComponentInfo{'ofed_iser'}{'DriverSubdir'};
	return (
			-e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& installed_ofed_driver("ib_iser", "$driver_subdir", "drivers/infiniband/ulp/iser")
			 );
}

# only called if installed_ofed_iser is true
sub installed_version_ofed_iser()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_ofed_iser is true
sub media_version_ofed_iser()
{
	return media_version_ofed();
}

sub build_ofed_iser($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_iser($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_iser', $install_list, $installing_list));
}

sub preinstall_ofed_iser($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_iser", $install_list, $installing_list);
}

sub install_ofed_iser($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_iser');
	install_ofed_comp('ofed_iser', $install_list);

	need_reboot();
	$ComponentWasInstalled{'ofed_iser'}=1;
}

sub postinstall_ofed_iser($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('ofed_iser');
}

sub uninstall_ofed_iser($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_iser');
	# TBD stop_ofed_iser;
	uninstall_ofed_comp('ofed_iser', $install_list, $uninstalling_list, 'verbose');
	need_reboot();
	$ComponentWasInstalled{'ofed_iser'}=0;
}

# ==========================================================================
# OFED ofed_nfsrdma installation

# involves /etc/init.d/nfs and /etc/init.d/nfslock
# The HasStart is disabled, so these won't be called.
# TBD - If this is enabled, what return value to use and how should it
# interact with the two daemons
# should we treat nfs as a subcomponent much like we used to handle iba_mon?
# autostart functions are per subcomponent
sub IsAutostart2_ofed_nfsrdma()
{
	return IsAutostart("nfslock") || IsAutoStart("nfs");
}
sub autostart_desc_ofed_nfsrdma()
{
	return "$ComponentInfo{'ofed_nfsrdma'}{'Name'}";
}
sub enable_autostart2_ofed_nfsrdma()
{
	enable_autostart("nfslock");
	enable_autostart("nfs");
}
sub disable_autostart2_ofed_nfsrdma()
{
	disable_autostart("nfs");
	disable_autostart("nfslock");
}

sub start_ofed_nfsrdma()
{
	my $driver_subdir=$ComponentInfo{'ofed_nfsrdma'}{'DriverSubdir'};
	start_driver($ComponentInfo{'ofed_nfsrdma'}{'Name'}, "lockd", "$driver_subdir/fs/lockd", "nfslock");
	start_driver($ComponentInfo{'ofed_nfsrdma'}{'Name'}, "nfs", "$driver_subdir/fs/nfs", "nfs");
}

sub stop_ofed_nfsrdma()
{
	stop_driver($ComponentInfo{'ofed_nfsrdma'}{'Name'}, "nfs", "nfs");
	stop_driver($ComponentInfo{'ofed_nfsrdma'}{'Name'}, "lockd", "nfslock");
}

sub available_ofed_nfsrdma()
{
	my $srcdir=$ComponentInfo{'ofed_nfsrdma'}{'SrcDir'};
	return ( (-d "$srcdir/SRPMS" || -d "$srcdir/RPMS")
			&& build_option_is_allowed($CUR_OS_VER, "--with-nfsrdma-mod", %ofed_kernel_ib_options));
}

sub installed_ofed_nfsrdma()
{
	my $driver_subdir=$ComponentInfo{'ofed_nfsrdma'}{'DriverSubdir'};
	return (#rpm_is_installed("rnfs-utils", "user") &&
			-e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& installed_ofed_driver("xprtrdma", "$driver_subdir", "net/sunrpc/xprtrdma")
			 );
}

# only called if installed_ofed_nfsrdma is true
sub installed_version_ofed_nfsrdma()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_ofed_nfsrdma is true
sub media_version_ofed_nfsrdma()
{
	return media_version_ofed();
}

sub build_ofed_nfsrdma($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_nfsrdma($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_nfsrdma', $install_list, $installing_list));
}

sub preinstall_ofed_nfsrdma($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_nfsrdma", $install_list, $installing_list);
}

sub install_ofed_nfsrdma($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_nfsrdma');
	install_ofed_comp('ofed_nfsrdma', $install_list);

	need_reboot();
	$ComponentWasInstalled{'ofed_nfsrdma'}=1;
}

sub postinstall_ofed_nfsrdma($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	# no need to restore_autostart, ofed reinstall does not affect nfs nor nfslock autostart
}

sub uninstall_ofed_nfsrdma($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_nfsrdma');
	# TBD stop_ofed_nfsrdma;
	uninstall_ofed_comp('ofed_nfsrdma', $install_list, $uninstalling_list, 'verbose');
	need_reboot();
	$ComponentWasInstalled{'ofed_nfsrdma'}=0;
}

# ==========================================================================
# OFED ofed_iwarp installation

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_ofed_iwarp()
{
	return IsAutostart_ofed_comp2('ofed_iwarp');
}
sub autostart_desc_ofed_iwarp()
{
	return autostart_desc_ofed_comp('ofed_iwarp');
}
# enable autostart for the given capability
sub enable_autostart2_ofed_iwarp()
{
	enable_autostart_ofed_comp2('ofed_iwarp');
}
# disable autostart for the given capability
sub disable_autostart2_ofed_iwarp()
{
	disable_autostart_ofed_comp2('ofed_iwarp');
}

# these are not presently called, which is good since ofed is hard to do this
#sub start_ofed_iwarp()
#{
#	my $driver_subdir=$ComponentInfo{'ofed_iwarp'}{'DriverSubdir'};
#	start_driver($ComponentInfo{'ofed_iwarp'}{'Name'}, "ib_core", $driver_subdir, "openibd");
#}

#sub stop_ofed_iwarp()
#{
#	stop_driver($ComponentInfo{'ofed_iwarp'}{'Name'}, "ib_core", "openibd");
#}

sub available_ofed_iwarp()
{
	my $srcdir=$ComponentInfo{'ofed_iwarp'}{'SrcDir'};
	return ( (-d "$srcdir/SRPMS" || -d "$srcdir/RPMS" )
			&& (build_option_is_allowed($CUR_OS_VER, "--with-cxgb3-mod", %ofed_kernel_ib_options)
			|| build_option_is_allowed($CUR_OS_VER, "--with-cxgb4-mod", %ofed_kernel_ib_options)
			|| build_option_is_allowed($CUR_OS_VER, "--with-nes-mod", %ofed_kernel_ib_options)));
}

sub installed_ofed_iwarp()
{
	my $driver_subdir=$ComponentInfo{'ofed_iwarp'}{'DriverSubdir'};
	return ((rpm_is_installed("libcxgb3", "user")
				|| rpm_is_installed("libcxgb4", "user")
				|| rpm_is_installed("libnes", "user"))
			&& -e "$ROOT$BASE_DIR/version_ofed"
			&& rpm_is_installed("compat-rdma", $CUR_OS_VER)
			&& (installed_ofed_driver("iw_cxgb3", "$driver_subdir", "drivers/infiniband/hw/cxgb3")
				|| installed_ofed_driver("iw_cxgb4", "$driver_subdir", "drivers/infiniband/hw/cxgb4")
				|| installed_ofed_driver("iw_nes", "$driver_subdir", "drivers/infiniband/hw/nes"))
			 );
}

# only called if installed_ofed_iwarp is true
sub installed_version_ofed_iwarp()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_ofed_iwarp is true
sub media_version_ofed_iwarp()
{
	return media_version_ofed();
}

sub build_ofed_iwarp($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_iwarp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('ofed_iwarp', $install_list, $installing_list));
}

sub preinstall_ofed_iwarp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_iwarp", $install_list, $installing_list);
}

sub install_ofed_iwarp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('ofed_iwarp');
	install_ofed_comp('ofed_iwarp', $install_list);

	need_reboot();
	$ComponentWasInstalled{'ofed_iwarp'}=1;
}

sub postinstall_ofed_iwarp($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('ofed_iwarp');
}

sub uninstall_ofed_iwarp($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_iwarp');
	# TBD stop_ofed_iwarp;
	uninstall_ofed_comp('ofed_iwarp', $install_list, $uninstalling_list, 'verbose');
	need_reboot();
	$ComponentWasInstalled{'ofed_iwarp'}=0;
}

# ==========================================================================
# OFED opensm installation

# determine if the given capability is configured for Autostart at boot
sub IsAutostart2_opensm()
{
	return IsAutostart_ofed_comp2('opensm');
}
sub autostart_desc_opensm()
{
	return autostart_desc_ofed_comp('opensm');
}
# enable autostart for the given capability
sub enable_autostart2_opensm()
{
	enable_autostart($ofed_comp_info{'opensm'}{'StartupScript'});
}
# disable autostart for the given capability
sub disable_autostart2_opensm()
{
	disable_autostart($ofed_comp_info{'opensm'}{'StartupScript'});
}

sub start_opensm()
{
	my $prefix = ofed_get_prefix();
	start_utility($ComponentInfo{'opensm'}{'Name'}, "$prefix/sbin", "opensm", "opensmd");
}

sub stop_opensm()
{
	stop_utility($ComponentInfo{'opensm'}{'Name'}, "opensm", "opensmd");
}

sub available_opensm()
{
	my $srcdir=$ComponentInfo{'opensm'}{'SrcDir'};
	return ( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS" );
}

sub installed_opensm()
{
	return (rpm_is_installed("opensm", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed");
}

# only called if installed_opensm is true
sub installed_version_opensm()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_opensm is true
sub media_version_opensm()
{
	return media_version_ofed();
}

sub build_opensm($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_opensm($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return (need_reinstall_ofed_comp('opensm', $install_list, $installing_list));
}

sub preinstall_opensm($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("opensm", $install_list, $installing_list);
}

sub install_opensm($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	print_install_banner_ofed_comp('opensm');
	install_ofed_comp('opensm', $install_list);

	$ComponentWasInstalled{'opensm'}=1;
}

sub postinstall_opensm($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	ofed_restore_autostart('opensm');
}

sub uninstall_opensm($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('opensm');
	stop_opensm;

	uninstall_ofed_comp('opensm', $install_list, $uninstalling_list, 'verbose');
	$ComponentWasInstalled{'opensm'}=0;
}

# ==========================================================================
# OFED ofed_debug installation

# this is an odd component.  It consists of the debuginfo files which
# are built and identified in DebugRpms in other components.  Installing this
# component installs the debuginfo files for the installed components.
# uninstalling this component gets rid of all debuginfo files.
# uninstalling other components will get rid of individual debuginfo files
# for those components

sub available_ofed_debug()
{
	my $srcdir=$ComponentInfo{'ofed_debug'}{'SrcDir'};
	return (( -d "$srcdir/SRPMS" || -d "$srcdir/RPMS")
			&&	$ofed_rpm_info{'libibverbs-debuginfo'}{'Available'});
}

sub installed_ofed_debug()
{
	return (rpm_is_installed("libibverbs-debuginfo", "user")
			&& -e "$ROOT$BASE_DIR/version_ofed");
}

# only called if installed_ofed_debug is true
sub installed_version_ofed_debug()
{
	if ( -e "$ROOT$BASE_DIR/version_ofed" ) {
		return `cat $ROOT$BASE_DIR/version_ofed`;
	} else {
		return "";
	}
}

# only called if available_ofed_debug is true
sub media_version_ofed_debug()
{
	return media_version_ofed();
}

sub build_ofed_debug($$$$)
{
	my $osver = shift();
	my $debug = shift();	# enable extra debug of build itself
	my $build_temp = shift();	# temp area for use by build
	my $force = shift();	# force a rebuild
	return 0;	# success
}

sub need_reinstall_ofed_debug($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	my $reins = need_reinstall_ofed_comp('ofed_debug', $install_list, $installing_list);
	if ("$reins" eq "no" ) {
		# if ofed components with DebugRpms have been added we need to reinstall
		# this component.  Note uninstall for individual components will
		# get rid of associated debuginfo files
		foreach my $comp ( @ofed_components ) {
			if ( " $installing_list " =~ / $comp /
				 && 0 != scalar(@{ $ofed_comp_info{$comp}{'DebugRpms'}})) {
				return "this";
			}
		}
		
	}
	return $reins;
}

sub preinstall_ofed_debug($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	return preinstall_ofed("ofed_debug", $install_list, $installing_list);
}

sub install_ofed_debug($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled

	my @list;

	print_install_banner_ofed_comp('ofed_debug');
	install_ofed_comp('ofed_debug', $install_list);

	# install DebugRpms for each installed component
	foreach my $comp ( @ofed_components ) {
		if ( " $install_list " =~ / $comp / ) {
			ofed_rpm_install_list(ofed_rpms_dir(), $CUR_OS_VER, 1,
							( @{ $ofed_comp_info{$comp}{'DebugRpms'}}));
		}
	}

	$ComponentWasInstalled{'ofed_debug'}=1;
}

sub postinstall_ofed_debug($$)
{
	my $install_list = shift();	# total that will be installed when done
	my $installing_list = shift();	# what items are being installed/reinstalled
	#ofed_restore_autostart('ofed_debug');
}

sub uninstall_ofed_debug($$)
{
	my $install_list = shift();	# total that will be left installed when done
	my $uninstalling_list = shift();	# what items are being uninstalled

	print_uninstall_banner_ofed_comp('ofed_debug');

	uninstall_ofed_comp('ofed_debug', $install_list, $uninstalling_list, 'verbose');
	# uninstall debug rpms for all components
	# debuginfo never in >1 component, so do explicit uninstall since
	# have an odd PartOf relationship which confuses uninstall_not_needed_list
	foreach my $comp ( reverse(@ofed_components) ) {
		if ( "$comp" eq "ofed_ib_bonding" && ! $ofed_rpm_info{'ib-bonding'}{'Available'}) {
			# skip, might be included with distro
		} else {
			rpm_uninstall_list("any", 'verbose',
					 @{ $ofed_comp_info{$comp}{'DebugRpms'}});
		}
	}
	$ComponentWasInstalled{'ofed_debug'}=0;
}
#!/usr/bin/perl
## INTEL CONFIDENTIAL
## Copyright (c) 2008-2012  Intel Corporation All Rights Reserved.
## The source code contained or described herein and all documents related
## to the source code ("Material") are owned by Intel Corporation or its
## suppliers or licensors. Title to the Material remains with Intel Corporation
## or its suppliers and licensors. The Material contains trade secrets and
## proprietary and confidential information of Intel or its suppliers and
## licensors. The Material is protected by worldwide copyright and trade
## secret laws and treaty provisions. No part of the Material may be used,
## copied, reproduced, modified, published, uploaded, posted, transmitted,
## distributed, or disclosed in any way without Intel's prior express
## written permission.
##
## No license under any patent, copyright, trade secret or other intellectual
## property right is granted to or conferred upon you by disclosure or delivery
## of the Materials, either expressly, by implication, inducement, estoppel or
## otherwise. Any license under such intellectual property rights must be
## express and approved by Intel in writing.

# [ICS VERSION STRING: @(#) ./INSTALL 3_18_3_4 [01/25/18 09:30]

use strict;
#use Term::ANSIColor;
#use Term::ANSIColor qw(:constants);
#use File::Basename;
#use Math::BigInt;

# ===========================================================================
# Main menus, option handling and version handling for FF for OFED install
#

$MainInstall="ofed";
$IB_STACK="OPENIB";
@supported_kernels = ( $CUR_OS_VER );	# TBD how do we verify OS
my $Build_OsVer=$CUR_OS_VER;
my $Build_Debug=0;	# should we provide more info for debug
my $Build_Temp="";	# temp area to use for build
my $Default_Build = 0;	# -B option used to select build
my $Build_Force = 0;# rebuild option used to force full rebuild

$Skip_UsrLocalSymLinks=1;	# no /usr/local symlinks for OFED installs
$FirstIPoIBInterface=0; # first device is ib0

	# Names of supported install components
	# must be listed in depdency order such that prereqs appear 1st
# TBD ofed_vnic
@Components = ( "ib_stack", "ofed_mlx4", "mpi_selector",
	   	"ib_stack_dev",
		"ofed_ipoib", "ofed_ib_bonding", "ofed_sdp",
	   	"mvapich2", "openmpi",
	   	"ofed_mpisrc", "ofed_udapl", "ofed_rds",
		"ofed_srp", "ofed_srpt", "ofed_iser", "ofed_iwarp",
		"opensm", "ofed_nfsrdma", "ofed_debug", );
# ofed_nfsrdma dropped in OFED 1.5.3rc2
# ofed_debug must be last

@SubComponents = ( );

	# an additional "special" component which is always installed when
	# we install/upgrade anything and which is only uninstalled when everything
	# else has been uninstalled.  Typically this will be the iba_config
	# file and related files absolutely required by it (such as wrapper_version)
$WrapperComponent = "iba_config_ofed";

# This provides more detailed information about each Component in @Components
# since hashes are not retained in the order specified, we still need
# @Components and @SubComponents to control install and menu order
# Fields are as follows:
#	Name => full name of component/subcomponent for prompts
# 	DefaultInstall => default installation (State_DoNotInstall or State_Install)
#					  used only when available and ! installed
#	SrcDir => directory name within install media for component
#	DriverSubdir => directory within /lib/modules/$CUR_OS_VERSION/ to
#					install driver to.  Set to "" if no drivers in component
#					set to "." if no subdir
# 	PreReq => other components which are prereqs of a given
#				component/subcomponent
#				Need space before and after each component name to
#				facilitate compares so that compares do not mistake names
#				such as mpidev for mpi
#	CoReq =>  other components which are coreqs of a given component
#				Note that CoReqs can also be listed as prereqs to provide
#				install verification as each component is installed,
#				however prereqs should only refer to items earlier in the list
#				Need space before and after each component name to
#				facilitate compares so that compares do not mistake names
#				such as mpidev for mpi
#	Hidden => component should not be shown in menus/prompts
#			  used for hidden PreReq.  Hidden components can't HasStart
#			  nor HasFirmware
#	Disabled =>  components/subcomponents which are disabled from installation
#	HasStart =>  components/subcomponents which have autostart capability
#	DefaultStart =>  should autostart default to Enable (1) or Disable (0)
#				Not needed/ignored unless HasStart=1
# 	StartPreReq => other components/subcomponents which must be autostarted
#				before autostarting this component/subcomponent
#				Not needed/ignored unless HasStart=1
#				Need space before and after each component name to
#				facilitate compares so that compares do not mistake names
#				such as mpidev for mpi
#	StartComponents => components/subcomponents with start for this component
#				if a component has a start script 
#				list the component as a subcomponent of itself
#	HasFirmware =>  components which need HCA firmware update after installed
#
# Note both Components and SubComponents are included in the list below.
# Components require all fields be supplied
# SubComponents only require the following fields:
#	Name, PreReq (should reference only components), HasStart, StartPreReq,
#	DefaultStart
%ComponentInfo = (
		# our special WrapperComponent, limited use
	"iba_config_ofed" =>	{ Name => "iba_config_ofed",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => "", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"ib_stack" =>	{ Name => "OFED IB Stack",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => "", CoReq => "",
 						# TBD - HasFirmware - FW update
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => "",
					  StartComponents => [ "ib_stack" ],
					},
	"ofed_mlx4" =>	{ Name => "OFED mlx4 Driver",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ", CoReq => "",
 						# TBD - HasFirmware - FW update
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ "ofed_mlx4" ],
					},
	"mpi_selector" =>	{ Name => "MPI selector",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 1, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"ib_stack_dev" => { Name => "OFED IB Development",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"ofed_vnic" =>	{ Name => "OFED Virtual NIC",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ "ofed_vnic" ],
					},
	"ofed_ipoib" =>	{ Name => "OFED IP over IB",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ "ofed_ipoib" ],
					},
	"ofed_ib_bonding" =>	{ Name => "OFED IB Bonding",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " ib_stack ofed_ipoib ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"ofed_sdp" =>	{ Name => "OFED SDP",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ofed_ipoib ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " ib_stack ofed_ipoib ",
					  StartComponents => [ "ofed_sdp" ],
					},
	"ofed_rds" =>	{ Name => "OFED RDS",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ofed_ipoib ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ "ofed_rds" ],
					},
	"ofed_udapl" =>	{ Name => "OFED uDAPL",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " ib_stack ofed_ipoib ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"mvapich2" =>	{ Name => "MVAPICH2 (gcc)",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " ib_stack mpi_selector ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"openmpi" =>	{ Name => "OpenMPI (gcc)",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " ib_stack mpi_selector ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"ofed_mpisrc" =>{ Name => "MPI Source",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " ib_stack ib_stack_dev mpi_selector ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"ofed_srp" =>	{ Name => "OFED SRP",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ "ofed_srp" ],
					},
	"ofed_srpt" =>	{ Name => "OFED SRP Target",
					  DefaultInstall => $State_DoNotAutoInstall,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ "ofed_srpt" ],
					},
	"ofed_iser" =>	{ Name => "OFED iSER",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ "ofed_iser" ],
					},
	"ofed_iwarp" =>	{ Name => "OFED iWARP",
					  DefaultInstall => $State_DoNotAutoInstall,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ "ofed_iwarp" ],
					},
	"opensm" =>		{ Name => "OFED Open SM",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ "opensm" ],
					},
	"ofed_nfsrdma" =>{ Name => "OFED NFS RDMA",
					  DefaultInstall => $State_DoNotAutoInstall,
					  SrcDir => ".", DriverSubdir => "updates",
					  PreReq => " ib_stack ofed_ipoib ", CoReq => "",
					  # for now, skip startup option for nfs and nfslock
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => " ib_stack ",
					  StartComponents => [ ],
					},
	"ofed_debug" =>	{ Name => "OFED Debug Info",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " ib_stack ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	# QuickSilver components, here so we can upgrade and uninstall as needed
	"iba" =>		{ Name => "QuickSilver IB Network Stack",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "iba",
					  PreReq => "", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 1, HasFirmware => 1, DefaultStart => 1,
					  StartPreReq => "",
					  StartComponents => [ "iba" ],
					},
	#			# iba_mon is a subcomponent
	#			# it is a tool with startup and config, but is part of iba
	#"iba_mon" =>	{ Name => "QuickSilver IB Port Monitor",
	#				  PreReq => " iba ", CoReq => "",
	#				  HasStart => 1, DefaultStart => 0,
	#				  StartPreReq => " iba ",
	#				  StartComponents => [ "iba_mon" ],
	#				},
	"ibdev" =>		{ Name => "QuickSilver IB Development",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "",
					  PreReq => " iba ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"ibboot" =>		{ Name => "QuickSilver IB Boot",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "",
					  PreReq => " iba ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 0, HasFirmware => 1, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"ifibre" =>		{ Name => "QuickSilver Virtual HBA (SRP)",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "iba",
					  PreReq => " iba ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " iba ",
					  StartComponents => [ "ifibre" ],
					},
	"inic" =>		{ Name => "QuickSilver Virtual NIC",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "iba",
					  PreReq => " iba ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " iba ",
					  StartComponents => [ "inic" ],
					},
	"ipoib" =>		{ Name => "QuickSilver IP over IB",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "iba",
					  PreReq => " iba ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " iba ",
					  StartComponents => [ "ipoib" ],
					},
	"mpi" =>		{ Name => "QuickSilver MPI Runtime",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "",
					  PreReq => " iba ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"mpidev" =>		{ Name => "QuickSilver MPI Development",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "",
					  PreReq => " iba mpi ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"mpisrc" =>		{ Name => "QuickSilver MPI Source",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "",
					  PreReq => " iba ibdev mpi ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"udapl" =>		{ Name => "QuickSilver uDAPL",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "iba",
					  PreReq => " iba ipoib ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " iba ",
					  StartComponents => [ "udapl" ],
					},
	"kdapl" =>		{ Name => "QuickSilver kDAPL",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "iba",
					  PreReq => " iba ipoib udapl ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " iba ",
					  StartComponents => [ "kdapl" ],
					},
	"sdp" =>		{ Name => "QuickSilver SDP",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "iba",
					  PreReq => " iba ipoib ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " iba ipoib ",
					  StartComponents => [ "sdp" ],
					},
	"rds" =>		{ Name => "QuickSilver RDS",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => "NO SUCH DIRECTORY", DriverSubdir => "iba",
					  PreReq => " iba ipoib ", CoReq => "",
					  Hidden => 0, Disabled => 1,
					  HasStart => 1, HasFirmware => 0, DefaultStart => 1,
					  StartPreReq => " iba ",
					  StartComponents => [ "rds" ],
					},
	);
	# translate from startup script name to component/subcomponent name
%StartupComponent = (
				"openibd" => "ib_stack",
				"iba_mon" => "iba_mon",
				"qlgc_vnic" => "ofed_vnic",
				"opensmd" => "opensm",
				# QuickSilver startup components so can disable on upgrade
				"iba" => "iba",
				"ics_srp" => "ifibre",
				"ics_inic" => "inic",
				"ipoib" => "ipoib",
				"udapl" => "udapl",
				"kdapl" => "kdapl",
				"ics_sdp" => "sdp",
				"rds" => "rds"
			);
	# has component been loaded since last configured autostart
%ComponentWasInstalled = (
				"ib_stack" => 0,
				"ofed_mlx4" => 0,
				"mpi_selector" => 0,
				"ib_stack_dev" => 0,
				"ofed_vnic" => 0,
				"ofed_ipoib" => 0,
				"ofed_ib_bonding" => 0,
				"ofed_sdp" => 0,
				"ofed_rds" => 0,
				"ofed_udapl" => 0,
				"mvapich2" => 0,
				"openmpi" => 0,
				"ofed_mpisrc" => 0,
				"ofed_srp" => 0,
				"ofed_srpt" => 0,
				"ofed_iser" => 0,
				"ofed_iwarp" => 0,
				"opensm" => 0,
				"ofed_nfsrdma" => 0,
				"ofed_debug" => 0,
			);

# ==========================================================================
# iba_config_ofed installation
# This is a special WrapperComponent which only needs:
#	available, install and uninstall
# it cannot have startup scripts, dependencies, prereqs, etc

sub available_iba_config_ofed
{
	my $srcdir=$ComponentInfo{'iba_config_ofed'}{'SrcDir'};
	return ( -e "$srcdir/INSTALL" );
}

sub install_iba_config_ofed
{
	my $install_list = $_[0];	# total that will be installed when done
	my $installing_list = $_[1];	# what items are being installed/reinstalled

	my $srcdir=$ComponentInfo{'iba_config_ofed'}{'SrcDir'};
	NormalPrint("Installing $ComponentInfo{'iba_config_ofed'}{'Name'}...\n");

	check_config_dirs();
	copy_systool_file("$srcdir/INSTALL", "/sbin/iba_config_ofed");
	# no need for a version file, ofed will have its own

	# if QLogic OFED is not installed, create iba_config too
	if ( ! -e "$BASE_DIR/version_wrapper" ) {
		copy_systool_file("$srcdir/INSTALL", "/sbin/iba_config");
	}

	$ComponentWasInstalled{'iba_config_ofed'}=1;
}

sub uninstall_iba_config_ofed
{
	my $install_list = $_[0];	# total that will be left installed when done
	my $uninstalling_list = $_[1];	# what items are being uninstalled

	NormalPrint("Uninstalling $ComponentInfo{'iba_config_ofed'}{'Name'}...\n");
	system("rm -rf $ROOT/sbin/iba_config_ofed");
	# if QLogic OFED is not installed, remove iba_config too
	if ( ! -e "$BASE_DIR/version_wrapper" ) {
		system("rm -rf $ROOT/sbin/iba_config");
	}
	$ComponentWasInstalled{'iba_config_ofed'}=0;
}

my $allow_install;
if ( my_basename($0) ne "INSTALL" )
{
	if ( my_basename($0) eq "ics_ib" )
	{
		printf("Warning: ics_ib is depricated, use iba_config\n");
		HitKeyCont;
	}
	$allow_install=0;
} else {
	$allow_install=1;
}

#
# Check if all basic requirements are ok
#
sub verify_os_ver 
{
	determine_os_version;
	#my $supported_kernel;
	#
	#if (!$allow_install)
	#{
	#	my $catkernels = `cat $ROOT$BASE_DIR/supported_kernels`;
	#	@supported_kernels = split( / +/, $catkernels);
	#} else {
	#	system("echo -n @supported_kernels > ./config/supported_kernels");
	#}
	#
	#foreach my $supported_kernel_path ( @supported_kernels ) 
	#{    
	#	$supported_kernel = my_basename($supported_kernel_path);
	#
	#	$module_dirs[++$#module_dirs] = "/lib/modules/$supported_kernel";
	#}
	# make sure current OS version included so remove_driver works
	$module_dirs[++$#module_dirs] = "/lib/modules/$CUR_OS_VER";
}

sub Usage
{
	if ( $allow_install ) {
		#printf STDERR "Usage: $0 [-r root] [-v|-vv] -R osver -B osver [-d][-t tempdir] [--user_configure_options 'options'] [--kernel_configure_options 'options'] [--prefix dir] [--no32bit|--32bit] [--without-depcheck] [--rebuild] [--force] [--answer keyword=value] [--debug]\n";
		#printf STDERR "               or\n";
		#printf STDERR "Usage: $0 [-r root] [-v|-vv] [-a|-n|-U|-u|-s|-i comp|-e comp] [-E comp] [-D comp] [-l] [--user_configure_options 'options'] [--kernel_configure_options 'options'] [--prefix dir] [--no32bit|--32bit] [--without-depcheck] [--rebuild] [--force] [--answer keyword=value] [--debug]\n";
		printf STDERR "Usage: $0 [-r root] [-v|-vv] [-a|-n|-U|-u|-s|-i comp|-e comp|-E comp|-D comp] [--user_configure_options 'options'] [--kernel_configure_options 'options'] [--prefix dir] [--no32bit|--32bit] [--without-depcheck] [--rebuild] [--force] [--answer=value] [--with-xeon-phi=<path>]\n";
	} else {
		printf STDERR "Usage: $0 [-r root] [-v|-vv] [-u|-s|-e comp] [-E comp] [-D comp] [--answer=value]\n";
		printf STDERR "          [--user_queries|--no_user_queries]\n";
	}
	printf STDERR "               or\n";
	printf STDERR "Usage: $0 -C\n";
	printf STDERR "               or\n";
	printf STDERR "Usage: $0 -V\n";
	if ( $allow_install ) {
		printf STDERR "       -a - install all ULPs and drivers with default options\n";
		printf STDERR "       -n - install all ULPs and drivers with default options\n";
		printf STDERR "            but with no change to autostart options\n";
		printf STDERR "       -U - upgrade/re-install all presently installed ULPs and drivers with\n";
		printf STDERR "            default options and no change to autostart options\n";
		printf STDERR "       -i comp - install the given component with default options\n";
		printf STDERR "            can appear more than once on command line\n";
		#printf STDERR "       -l - skip creating/removing symlinks to /usr/local from /opt/iba\n";
		printf STDERR "       --user_configure_options 'options' - specify additional OFED build\n";
		printf STDERR "             options for user space srpms.  Causes rebuild of all user srpms\n";
		printf STDERR "       --kernel_configure_options 'options' - specify additional OFED build\n";
		printf STDERR "             options for driver srpms.  Causes rebuild of all driver srpms\n";
		printf STDERR "       --prefix dir - specify alternate directory prefix for install\n";
		printf STDERR "             default is /usr.  Causes rebuild of needed srpms\n";
		printf STDERR "       --no32bit - disable install of 32 bit libraries on 64 bit OSs\n";
		printf STDERR "       --32bit - enable install of 32 bit libraries on 64 bit OSs\n";
		printf STDERR "             default is no32bit\n";
	 	printf STDERR "       --without-depcheck - disable check of OS dependencies\n";
		printf STDERR "       --rebuild - force OFED rebuild\n";
		printf STDERR "       --force - force install even if distos don't match\n";
		printf STDERR "                 Use of this option can result in undefined behaviors\n";
		printf STDERR "       --with-xeon-phi=<path> - enable install of xeon phi packages\n";
		# --debug, -B, -t and -d options are purposely not documented
		#printf STDERR "       --debug - build a debug version of modules\n";
		#printf STDERR "       -B osver - run build for all components targetting kernel osver\n";
		#printf STDERR "       -t - temp area for use by builds, only valid with -B\n";
		#printf STDERR "       -d - enable build debugging assists, only valid with -B\n";
		#printf STDERR "       -R osver - force install for kernel osver rather than running kernel.\n";
	}
	printf STDERR "       -u - uninstall all ULPs and drivers with default options\n";
	printf STDERR "       -s - enable autostart for all installed drivers\n";
	printf STDERR "       -r - specify alternate root directory, default is /\n";
	printf STDERR "       -e comp - uninstall the given component with default options\n";
	printf STDERR "            can appear more than once on command line\n";
	printf STDERR "       -E comp - enable autostart of given component\n";
	printf STDERR "            can appear with -D or more than once on command line\n";
	printf STDERR "       -D comp - disable autostart of given component\n";
	printf STDERR "            can appear with -E or more than once on command line\n";
	printf STDERR "       -v - verbose logging\n";
	printf STDERR "       -vv - very verbose debug logging\n";
	printf STDERR "       -C - output list of supported components\n";
	printf STDERR "       -V - output Version\n";

	printf STDERR "       --user_queries - permit non-root users to query the fabric. (default)\n";
	printf STDERR "       --no_user_queries - non root users cannot query the fabric.\n";
	showAnswerHelp();

	printf STDERR "       default options retain existing configuration files\n";
	printf STDERR "       supported component names:\n";
	printf STDERR "            ";
	foreach my $comp ( @Components )
	{
		printf STDERR " $comp";
	}
	printf STDERR "\n";
	if (scalar(@SubComponents) > 0) {
		printf STDERR "       additional component names allowed for -E and -D options:\n";
		printf STDERR "            ";
		foreach my $comp ( @SubComponents )
		{
			printf STDERR " $comp";
		}
		printf STDERR "\n";
	}
	exit (2);
}

# translate an ibaccess component name into the corresponding list of ofed comps
# if the given name is invalid or has no corresponding OFED component
# returns an empty list
sub translate_comp
{
	my($arg)=$_[0];
	if ( "$arg" eq "iba" )			{ return ( "ib_stack", "ofed_mlx4", "oftools" );
	} elsif ("$arg" eq "ibdev")		{ return ( "ib_stack_dev" );
	} elsif ("$arg" eq "ifibre")	{ return ( "ofed_srp" );
	#} elsif ("$arg" eq "inic")		{ return ( "ofed_vnic" );
			# marker for ib-bonding so we can postprocess later
	} elsif ("$arg" eq "ipoib")		{ return ( "ofed_ipoib", "ib_bonding_marker" );
	} elsif ("$arg" eq "mpi")		{ return ( "mvapich2", "openmpi" );
	} elsif ("$arg" eq "mpidev") { return ( "mvapich2", "openmpi" );
	} elsif ("$arg" eq "mpisrc")	{ return ( "ofed_mpisrc" );
	} elsif ("$arg" eq "udapl")		{ return ( "ofed_udapl" );
	} elsif ("$arg" eq "sdp")		{ return ( "ofed_sdp" );
	} elsif ("$arg" eq "rds")		{ return ( "ofed_rds" );
		# no ibaccess argument equivalent for:  ofed_srpt, ofed_iser,
		#	openmpi, ofed_iwarp, opensm, ofed_nfsrdma, ofed_debug
		#
	} else {
		return ();	# invalid name
	}
}

sub process_args
{
	my $arg;
	my $last_arg;
	my $setroot = 0;
	my $install_opt = 0;
	my $setcomp = 0;
	my $setenabled = 0;
	my $setdisabled = 0;
	my $setosver = 0;
	my $setbuildtemp = 0;
	my $comp = 0;
	my $osver = 0;
	my $setuseroptions = 0;
	my $setcurosver = 0;
	my $setkerneloptions = 0;
	my $setprefix = 0;
	my $setanswer = 0;
	my $got_32bit_option = 0;
	my $patch_ofed=0;

	if (scalar @ARGV >= 1) {
		foreach $arg (@ARGV) {
			if ( $setroot ) {
				$ROOT="$arg";
				if (substr($ROOT,0,1) ne "/") {
					printf STDERR "Invalid -r root (must be absolute path): '$ROOT'\n";
					Usage;
				}
				if (! -d $ROOT) {
					printf STDERR "Invalid -r root (directory not found): '$ROOT'\n";
					Usage;
				}
				$setroot=0;
			} elsif ( $setanswer ) {
				my @pair = split /=/,$arg;
				if ( scalar(@pair) != 2 ) {
					printf STDERR "Invalid --answer keyword=value: '$arg'\n";
					Usage;
				}
				set_answer($pair[0], $pair[1]);
				$setanswer=0;
			} elsif ( $setcomp ) {
				foreach $comp ( @Components )
				{
					if ( "$arg" eq "$comp" )
					{
						$Default_Components{$arg} = 1;
						$setcomp=0;
					}
				}
				if ( $setcomp )
				{
					my @comps = translate_comp($arg);
					# if empty list returned, we will not clear setcomp and
					# will get error below
					foreach $comp ( @comps )
					{
						$Default_Components{$comp} = 1;
						$setcomp=0;
					}
				}
				if ( $setcomp )
				{
					printf STDERR "Invalid component: $arg\n";
					Usage;
				}
			} elsif ( $setenabled ) {
				foreach $comp ( @Components, @SubComponents )
				{
					if ( "$arg" eq "$comp" )
					{
						$Default_EnabledComponents{$arg} = 1;
						$setenabled=0;
					}
				}
				if ( $setenabled )
				{
					my @comps = translate_comp($arg);
					# if empty list returned, we will not clear setcomp and
					# will get error below
					foreach $comp ( @comps )
					{
						$Default_EnabledComponents{$comp} = 1;
						$setenabled=0;
					}
				}
				if ( $setenabled )
				{
					printf STDERR "Invalid component: $arg\n";
					Usage;
				}
			} elsif ( $setdisabled ) {
				foreach $comp ( @Components, @SubComponents )
				{
					if ( "$arg" eq "$comp" )
					{
						$Default_DisabledComponents{$arg} = 1;
						$setdisabled=0;
					}
				}
				if ( $setdisabled )
				{
					my @comps = translate_comp($arg);
					# if empty list returned, we will not clear setcomp and
					# will get error below
					foreach $comp ( @comps )
					{
						$Default_DisabledComponents{$comp} = 1;
						$setdisabled=0;
					}
				}
				if ( $setdisabled )
				{
					printf STDERR "Invalid component: $arg\n";
					Usage;
				}
			} elsif ( $setosver ) {
				$Build_OsVer="$arg";
				$setosver=0;
			} elsif ( $setbuildtemp ) {
				$Build_Temp="$arg";
				$setbuildtemp=0;
			} elsif ( $setuseroptions ) {
				$OFED_user_configure_options="$arg";
				$setuseroptions=0;
			} elsif ( $setkerneloptions ) {
				$OFED_kernel_configure_options="$arg";
				$setkerneloptions=0;
			} elsif ( $setprefix ) {
				$OFED_prefix="$arg";
				$setprefix=0;
			} elsif ( $setcurosver ) {
				$CUR_OS_VER="$arg";
				@supported_kernels = ( $CUR_OS_VER );
				$setcurosver=0;
			} elsif ( "$arg" eq "-r" ) {
				$setroot=1;
			} elsif ( "$arg" eq "-v" ) {
				$LogLevel=1;
			} elsif ( "$arg" eq "-vv" ) {
				$LogLevel=2;
			#} elsif ( "$arg" eq "-l" ) {
			#	$Skip_UsrLocalSymLinks=1;
			} elsif ( "$arg" eq "-i" ) {
				$Default_CompInstall=1;
				$Default_Prompt=1;
				$setcomp=1;
				if ($install_opt || $Default_CompUninstall || $Default_Build) {
					# can't mix -i with other install controls
					printf STDERR "Invalid combination of options: $arg not permitted with previous options\n";
					Usage;
				}
			} elsif ( "$arg" eq "-e" ) {
				$Default_CompUninstall=1;
				$Default_Prompt=1;
				$setcomp=1;
				if ($install_opt || $Default_CompInstall || $Default_Build) {
					# can't mix -e with other install controls
					printf STDERR "Invalid combination of options: $arg not permitted with previous options\n";
					Usage;
				}
			} elsif ( "$arg" eq "-E" ) {
				$Default_Autostart=1;
				$Default_EnableAutostart=1;
				$Default_Prompt=1;
				$setenabled=1;
				if ($Default_Build) {
					# can't mix -E with other install controls
					printf STDERR "Invalid combination of options: $arg not permitted with previous options\n";
					Usage;
				}
			} elsif ( "$arg" eq "-D" ) {
				$Default_Autostart=1;
				$Default_DisableAutostart=1;
				$Default_Prompt=1;
				$setdisabled=1;
				if ($Default_Build) {
					# can't mix -D with other install controls
					printf STDERR "Invalid combination of options: $arg not permitted with previous options\n";
					Usage;
				}
			} elsif ( "$arg" eq "--user_configure_options" ) {
				$setuseroptions=1;
			} elsif ( "$arg" eq "--kernel_configure_options" ) {
				$setkerneloptions=1;
			} elsif ( "$arg" eq "--prefix" ) {
				$setprefix=1;
			} elsif ( "$arg" eq "--answer" ) {
 				$setanswer=1;
			} elsif ( "$arg" eq "--no32bit" ) {
				$OFED_no32bit=1;
				$got_32bit_option = 1;
			} elsif ( "$arg" eq "--32bit" ) {
				$OFED_no32bit=0;
				$got_32bit_option = 1;
#			} elsif ( "$arg" eq "--with-xeon-phi" ) {
#				$OFED_xeonphi=1;
            } elsif ( index($arg,"--with-xeon-phi") != -1 ) {
                $OFED_xeonphi=1;
                my @pair = split /=/,$arg;
#                if (scalar(@pair) != 2) {
#                    printf(STDERR "Invalid --with-xeon-phi usage: --with-xeon-phi=<path> '$arg'\n");
#                    Usage;
#                }
                $OFED_xeonphi_path=$pair[1];
			} elsif ( "$arg" eq "--without-depcheck" ) {
				$rpm_check_dependencies=0;
			} elsif ( "$arg" eq "--force" ) {
				$Force_Install=1;
			} elsif ( "$arg" eq "-C" ) {
				ShowComponents;
				exit(0);
			} elsif ( "$arg" eq "-V" ) {
				printf "$VERSION\n";
				exit(0);
			} elsif ( "$arg" eq "-R" ) {
				$setcurosver=1;
			} elsif ( "$arg" eq "-B" ) {
				# undocumented option to do a build for specific OS
				$Default_Build=1;
				$Default_Prompt=1;
				$setosver=1;
				if ($install_opt || $Default_CompInstall || $Default_CompUninstall || $Default_Autostart) {
					# can't mix -B with install
					printf STDERR "Invalid combination of options: $arg not permitted with previous options\n";
					Usage;
				}
			} elsif ( "$arg" eq "-d" ) {
				# undocumented option to aid debug of build
				$Build_Debug=1;
				if ($install_opt || $Default_CompInstall || $Default_CompUninstall || $Default_Autostart) {
					# can't mix -d with install
					printf STDERR "Invalid combination of options: $arg not permitted with previous options\n";
					Usage;
				}
			} elsif ( "$arg" eq "-t" ) {
				# undocumented option to aid debug of build
				$setbuildtemp=1;
				if ($install_opt || $Default_CompInstall || $Default_CompUninstall || $Default_Autostart) {
					# can't mix -t with install
					printf STDERR "Invalid combination of options: $arg not permitted with previous options\n";
					Usage;
				}
			} elsif ( "$arg" eq "--rebuild" ) {
				# force rebuild
				$Build_Force=1;
				$OFED_force_rebuild=1;
			} elsif ( "$arg" eq "--debug" ) {
				$OFED_debug=1;
			} elsif ( "$arg" eq "--user_queries" ) {
				$Default_UserQueries=1;
			} elsif ( "$arg" eq "--no_user_queries" ) {
				$Default_UserQueries=-1;
			} elsif ( "$arg" eq "--patch_ofed" ) {
				$patch_ofed=1;
			} else {
				# Install options
				if ( "$arg" eq "-a" ) {
					$Default_Install=1;
				} elsif ( "$arg" eq "-u" ) {
					$Default_Uninstall=1;
				} elsif ( "$arg" eq "-s" ) {
					$Default_Autostart=1;
				} elsif ( "$arg" eq "-n" ) {
					$Default_Install=1;
					$Default_SameAutostart=1;
				} elsif ( "$arg" eq "-U" ) {
					$Default_Upgrade=1;
					$Default_SameAutostart=1;
				} else {
					printf STDERR "Invalid option: $arg\n";
					Usage;
				}
				if ($install_opt || $Default_CompInstall
					 || $Default_CompUninstall) {
					# only one of the above install selections
					printf STDERR "Invalid combination of options: $arg not permitted with previous options\n";
					Usage;
				}
				$install_opt=1;
				$Default_Prompt=1;
			}
			$last_arg=$arg;
		}
	}
	if ( $setroot || $setcomp || $setenabled || $setdisabled  || $setosver || $setbuildtemp || $setuseroptions || $setkerneloptions || $setprefix || $setanswer) {
		printf STDERR "Missing argument for option: $last_arg\n";
		Usage;
	}
	if ( ($Default_Install || $Default_CompInstall || $Default_Upgrade
			|| $got_32bit_option || $Force_Install)
		 && ! $allow_install) {
		printf STDERR "Installation options not permitted in this mode\n";
		Usage;
	}
	if ( ($Default_Build || $OFED_force_rebuild || $OFED_debug
		 || ($OFED_user_configure_options ne '')
			 || ($OFED_kernel_configure_options ne '')
			 || ($OFED_prefix ne '/usr'))
		&& ! $allow_install) {
		printf STDERR "Build options not permitted in this mode\n";
		Usage;
	}
	if ( $patch_ofed) {
		NormalPrint("Patching OFED...\n");
		LogPrint("Executing: cd $ComponentInfo{'ib_stack'}{'SrcDir'}; ./patch_ofed3\n");
		system("cd $ComponentInfo{'ib_stack'}{'SrcDir'}; ./patch_ofed3");
		HitKeyCont;
	}
}

my @INSTALL_CHOICES= ();
sub show_menu
{
	my $inp;
	my $max_inp;

	@INSTALL_CHOICES= ();
	if ( $Default_Install ) {
		NormalPrint ("Installing All IB Software\n");
		@INSTALL_CHOICES = ( @INSTALL_CHOICES, 1);
	}
	if ( $Default_CompInstall ) {
		NormalPrint ("Installing Selected IB Software\n");
		@INSTALL_CHOICES = ( @INSTALL_CHOICES, 1);
	}
	if ( $Default_Upgrade ) {
		NormalPrint ("Upgrading/Re-Installing IB Software\n");
		@INSTALL_CHOICES = ( @INSTALL_CHOICES, 1);
	}
	if ( $Default_Uninstall ) {
		NormalPrint ("Uninstalling All IB Software\n");
		@INSTALL_CHOICES = ( @INSTALL_CHOICES, 4);
	}
	if ($Default_CompUninstall ) {
		NormalPrint ("Uninstalling Selected IB Software\n");
		@INSTALL_CHOICES = ( @INSTALL_CHOICES, 4);
	}
	if ($Default_Autostart) {
		NormalPrint ("Configuring autostart for Selected installed IB Drivers\n");
		@INSTALL_CHOICES = ( @INSTALL_CHOICES,  3);
	}
	if (scalar(@INSTALL_CHOICES) > 0) {
		return;
	}
START:	
	system "clear";
	printf ("$BRAND IB $VERSION Software\n\n");
	if ($allow_install) {
		printf ("   1) Install/Uninstall Software\n");
	} else {
		printf ("   1) Show Installed Software\n");
	}
	printf ("   2) Reconfigure $ComponentInfo{'ofed_ipoib'}{'Name'}\n");
	printf ("   3) Reconfigure Driver Autostart \n");
	$max_inp=3;
	if (!$allow_install)
	{
		printf ("   4) Uninstall Software\n");
		$max_inp=4;
	}
	printf ("\n   X) Exit\n");


	$inp = getch();      

	if ($inp =~ /[qQ]/ || $inp =~ /[Xx]/ ) {
		@INSTALL_CHOICES = ( 99999 );	# indicates exit, none selected
		return;
	}
	if (ord($inp) == $KEY_ENTER) {           
		goto START;
	}

	if ($inp =~ /[0123456789abcdefABCDEF]/)
	{
		$inp = hex($inp);
	}

	if ($inp < 1 || $inp > $max_inp) 
	{
#		printf ("Invalid choice...Try again\n");
		goto START;
	}
	@INSTALL_CHOICES = ( $inp );
}

process_args;
check_root_user;
if ( ! $Default_Build ) {
	open_log("");
} else {
	open_log("./build.log");
}

if ( ! $Default_Build ) {
	verify_os_ver;
	verify_modtools;
	#if ($allow_install) {
	#	verify_distrib_files;
	#}
} else {
	determine_os_version;
}
# post process ib_bonding_marker selection via command line args so
# can check Available for ib-bonding
if ( $Default_Components{'ib_bonding_marker'} ) {
	if ( comp_is_available('ofed_ib_bonding') ) {
		$Default_Components{'ofed_ib_bonding'} = 1;
	}
}
if ( $Default_EnabledComponents{'ib_bonding_marker'} ) {
	if ( comp_is_available('ofed_ib_bonding') ) {
		$Default_EnabledComponents{'ofed_ib_bonding'} = 1;
	}
}
if ( $Default_DisabledComponents{'ib_bonding_marker'} ) {
	if ( comp_is_available('ofed_ib_bonding') ) {
		$Default_DisabledComponents{'ofed_ib_bonding'} = 1;
	}
}

set_libdir;
init_ofed_rpm_info($CUR_OS_VER);

RESTART:
if ($Default_Build) {
	$exit_code = build_all_components($Build_OsVer, $Build_Debug, $Build_Temp, $Build_Force);
	goto DONE;
} else {
	show_menu;
}

foreach my $INSTALL_CHOICE ( @INSTALL_CHOICES )
{
	if ($allow_install && $INSTALL_CHOICE == 1) 
	{
		select_debug_release(".");
		show_install_menu(1);
		if (! $Default_Prompt) {
			goto RESTART;
		} else {
			if ($exit_code == 0) {
				print "Done Installing IB Software.\n"
			}
		}
	} 
	elsif ($INSTALL_CHOICE == 1) {
		show_installed(1);
		goto RESTART;
	}
	elsif ($INSTALL_CHOICE == 4)
	{
		show_uninstall_menu(1);
		if (! $Default_Prompt ) {
			goto RESTART;
		} else {
			if ($exit_code == 0) {
				print "Done Uninstalling IB Software.\n"
			}
		}
	}
	elsif ($INSTALL_CHOICE == 2) 
	{     
		Config_ifcfg(1,"$ComponentInfo{'ofed_ipoib'}{'Name'}","ib", "$FirstIPoIBInterface",1);
		check_network_config;
		#Config_IPoIB_cfg;
		goto RESTART;
	}
	elsif ($INSTALL_CHOICE == 3) 
	{
		reconfig_autostart;
		if (! $Default_Prompt ) {
			goto RESTART;
		} else {
			print "Done IB Driver Autostart Configuration.\n"
		}
	}
}
DONE:
close_log;
exit $exit_code;
