#!/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: unknown]

#

#++
# "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.3.165% 00.000B000";
$VERSION =~ s/THIS_IS_THE_ICS_VERSION_NUMBER:@\(#\)//;
$VERSION =~ s/%.*//;
my $INT_VERSION = "THIS_IS_THE_ICS_INTERNAL_VERSION_NUMBER:@(#)3.3.165% 00.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: unknown]

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: unknown]

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: unknown]

#

#++
# "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: unknown]

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: unknown]

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: unknown]

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: unknown]

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: unknown]

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: unknown]

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: unknown]

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.
#
# This file is used by the Intel Installer scripts. If you are not using the
# Intel installer, this file can be ignored.
use strict;
use File::Basename;

my @TRUESCALE_USER_RPM_LIST = ( "Documentation/infinipath-doc",
				"InfiniPath/infinipath-libs",
				"InfiniPath-Devel/infinipath-devel",
				"InfiniPath/infinipath",
				"TMI/tmi" );

my @XEON_PHI_USER_RPM_LIST = ( "Documentation/infinipath-doc",
				"InfiniPath/infinipath",
				"TMI/tmi" );

my @XEON_PHI_USER_RPM_LIST_OLD = ( "Documentation/infinipath-doc",
				"InfiniPath-MIC/intel-mic-psm",
				"InfiniPath-MIC/intel-mic-psm-devel",
				"InfiniPath/infinipath",
				"TMI/tmi" );

my @TRUESCALE_ALL_RPM_LIST = (@TRUESCALE_USER_RPM_LIST );

my @TRUESCALE_OLD_RPM_LIST = ( "mpi-libs", "mpi-frontend", "mpi-benchmark",
				 "mpi-devel", "mpi-doc", "qlogic-mpi-register" );

AddAnswerHelp("SinglePort", "Enable Intel HCA Single Port Mode");

# immediately stops or starts given component, only
# called if HasStart
sub start_truescale
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_truescale
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_truescale
{
    my @QueryFor = ("InfiniPath/infinipath-libs");
    my $srcdir = $ComponentInfo{'truescale'}{'SrcDir'};
    return rpm_exists_list ($srcdir, "user", @QueryFor);
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_truescale
{
    return ( -f "$ROOT/usr/lib64/libinfinipath.so.4.0" );
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_truescale
{
    my $ver = rpm_query_attr_pkg ("infinipath-libs", "VERSION");
    my $rel = rpm_query_attr_pkg ("infinipath-libs", "RELEASE");
    my $major = 0;
    my $minor = 0;
    my $maint = 0;
    (my $build) = split (/\./, $rel);
    ($major, $minor, $maint) = split (/\./, $ver);
    $maint = 0 if ($maint eq "");
    return "$major.$minor.$maint.0.$build";
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_truescale
{
    my $srcdir = $ComponentInfo{'truescale'}{'SrcDir'};
    my $rpm = rpm_resolve ($srcdir, "user", "InfiniPath/infinipath-libs");
    my $ver = rpm_query_attr ($rpm, "VERSION");
    my $rel = rpm_query_attr ($rpm, "RELEASE");
    my $major = 0;
    my $minor = 0;
    my $maint = 0;
    (my $build) = split (/\./, $rel);
    ($major, $minor, $maint) = split (/\./, $ver);
    $maint = 0 if ($maint eq "");
    return "$major.$minor.$maint.0.$build";
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_truescale
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

sub check_os_prereqs_truescale
{
    my $rc = 0;
    my $dmidecode_pkg = "dmidecode";
    if (lc ($CUR_DISTRO_VENDOR) eq "suse" || lc ($CUR_DISTRO_VENDOR) eq "sles") {
	if ("$CUR_VENDOR_VER" eq 'ES12') {
		$dmidecode_pkg = "dmidecode";
	} else {
		$dmidecode_pkg = "pmtools";
	}
    }
    $rc = rpm_check_os_prereqs("truescale", "user", ($dmidecode_pkg));
    return $rc || rpm_check_os_prereqs("truescale", "user32", ("glibc"));
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_truescale
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_truescale
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

my $truescale_modprobe_comment = "# If this comment is present, the singleport option will be removed on uninstall";

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_truescale
{
    my $install_list = $_[0];
    my $installing_list = $_[1];
    my $srcdir = $ComponentInfo{'truescale'}{'SrcDir'};
    my $version = media_version_truescale ();
    my $ver;
    my $rel;
    my $remove = 1;
    my $rc;
    my $libs_suffix = "";
    my $opts;
    my $enabled = 0;
    my $enable = 0;

    if (lc ($CUR_DISTRO_VENDOR) eq "suse" || lc ($CUR_DISTRO_VENDOR) eq "sles") {
		$libs_suffix = "-32bit";
    }
    
    printf ("Installing $ComponentInfo{'truescale'}{'Name'} $version...\n");
    LogPrint ("Installing $ComponentInfo{'truescale'}{'Name'} $version for $CUR_OS_VER\n");

    if (rpm_is_installed ("lam", "user")) {
		  $ver = rpm_query_attr_pkg ("lam", "VERSION");
		  $rel = rpm_query_attr_pkg ("lam", "RELEASE");
		  
		  printf ("It appears that the RPM lam-$ver-$rel is installed on your system.\n");
		  printf ("LAM/MPI is an MPI implementation that runs on Ethernet and as such\n");
		  printf ("is not configured to run over InfiniBand fabrics.\n");
		  printf ("This package may conflict with the install of the Intel mpi-docs RPM.\n");
		  $remove = GetYesNo ("Would you like to remove lam-$ver-$rel?", "y");
		  if ($remove) {
				my @lam_rpms = ();
				for my $name ("lam-libs", "lam", "lam-devel") {
					if (rpm_is_installed ($name, "any")) {
						 push (@lam_rpms, $name);
					}
				}
				LogPrint ("Removing lam RPMs: @lam_rpms\n");
				$rc = rpm_uninstall_list ("any", "verbose", @lam_rpms);
		  }
    }

    # Deal with infinipath-psm RPM that may come from stock OFED or
    # the distro.
    if (rpm_is_installed("infinipath-psm", "user")) {
	  if (rpm_is_installed("infinipath-psm-devel", "user")) {
			rpm_uninstall("infinipath-psm-devel", "any", "--nodeps", "yes");
	  }
	  if (rpm_is_installed("infinipath-psm-debuginfo", "user")) {
			rpm_uninstall("infinipath-psm-debuginfo", "any", "--nodeps", "yes");
	  }
	  rpm_uninstall("infinipath-psm", "any", "--nodeps", "yes");
    }
    
	# Uninstall old QLogic MPI rpms
    rpm_uninstall_list ("any", "silent", @TRUESCALE_OLD_RPM_LIST);
    rpm_uninstall_list ("user32", "silent", ("mpi-libs".$libs_suffix));


    # Uninstall 32bit *-libs rpms.
    rpm_uninstall_list ("user32", "verbose", ("infinipath-libs".$libs_suffix));

	# cleanup empty qlogic MPI tree
	system("rmdir $ROOT/usr/mpi/qlogic 2>/dev/null"); # remove only if empty


    if($OFED_xeonphi) {
		  # Looking for mpps rpms in path specified by parameter
		  if ($OFED_xeonphi_path ne "" and -e $OFED_xeonphi_path and -d $OFED_xeonphi_path) {
				 # Install packages from specified directory
				 printf ("Searching for mpss-psm-* packages in: $OFED_xeonphi_path dir\n");
				 LogPrint ("Searching for mpss-psm-* packages in: $OFED_xeonphi_path dir");
				 my @found_rpms = `find $OFED_xeonphi_path -name \"mpss-psm-[!dev]*.rpm\" 2>/dev/null`;
				 my @found_rpms_dev = `find $OFED_xeonphi_path -name \"mpss-psm-dev*.rpm\" 2>/dev/null`;
				 # Check if mpss rpms were found in specified directory and reinstall it
				 if (scalar @found_rpms > 0) {
						my $pkgname = `dirname $found_rpms[0]`;
						chomp($pkgname);
						$pkgname .= "/mpss-psm";

						printf ("Found package in $pkgname\n");
						LogPrint ("Found package in $pkgname\n");

						# Uninstalling infinipath-libs and infinipath-devel if present
						if (rpm_is_installed("infinipath-libs", "user")) {
							rpm_uninstall("infinipath-libs", "any", "--nodeps", "yes");
						} 
						if (rpm_is_installed("infinipath-devel", "user")) {
							rpm_uninstall("infinipath-devel", "any", "--nodeps", "yes");
						}

						rpm_install("/", "user", $pkgname);
				}
				# Check if mpss-dev  rpms  were found in specified directory and reinstall it
				if (scalar @found_rpms_dev > 0) {
					  my $pkgname = `dirname $found_rpms_dev[0]`;
					  chomp($pkgname);
					  $pkgname .= "/mpss-psm-dev";

					  printf ("Found package in $pkgname\n");
					  LogPrint ("Found package in $pkgname\n");  
					  rpm_install("/", "user", $pkgname);
				}
				# Information about no matches found for packages in specified directory
				if (scalar @found_rpms == 0 && scalar @found_rpms_dev == 0) {
					  printf ("Packages mpss-psm-* cannot be found in: $OFED_xeonphi_path dir!\n");
					  LogPrint ("Packages mpss-psm-* cannot be found in: $OFED_xeonphi_path dir!\n");
				}				
		 # Path for mpps directory not specified in parameter - looking for files in default directories
		 } else {
				  # Try to find the packages in /root/, /tmp, /opt, /home
				  my @search_dirs = ("/root", "/tmp", "/opt", "/home");
				  my @found_rpms; 
				  my @found_rpms_dev;
				  printf ("Searching for mpss-psm-* packages in: /root/, /tmp, /opt, /home dirs\n");
				  LogPrint ("Searching for mpss-psm-* packages in: /root/, /tmp, /opt, /home dirs\n");

				  foreach my $dir (@search_dirs) {
						@found_rpms = `find $dir -name \"mpss-psm-[!dev]*.rpm\" 2>/dev/null`;
						@found_rpms_dev = `find $dir -name \"mpss-psm-dev*.rpm\" 2>/dev/null`;
						# Check if mpss rpms were found in specified directory and reinstall it	
						if (scalar @found_rpms > 0) {
							  my $pkgname = `dirname $found_rpms[0]`;
							  chomp($pkgname);
							  $pkgname .= "/mpss-psm";

							  printf ("Found package in $pkgname\n");
							  LogPrint ("Found package in $pkgname\n");

							  # Uninstalling infinipath-libs and infinipath-devel if present
							  if (rpm_is_installed("infinipath-libs", "user")) {
								  rpm_uninstall("infinipath-libs", "any", "--nodeps", "yes");
							  }
							  if (rpm_is_installed("infinipath-devel", "user")) {
									rpm_uninstall("infinipath-devel", "any", "--nodeps", "yes");
							  }

							  rpm_install("/", "user", $pkgname);
					  }
					  # Check if mpss-dev rpms were found in specified directory and reinstall it
					  if (scalar @found_rpms_dev > 0) {
							  my $pkgname = `dirname $found_rpms_dev[0]`;
							  chomp($pkgname);
							  $pkgname .= "/mpss-psm-dev";

							  printf ("found package in $pkgname\n");
							  LogPrint ("Found package in $pkgname\n");

							  rpm_install("/", "user", $pkgname);
					  }
					  # Leaving loop after first mpss directory found
					  last if (scalar @found_rpms > 0 || scalar @found_rpms_dev > 0);
				}

			 if (!rpm_is_installed("mpss-psm", "user") or !rpm_is_installed("mpss-psm-dev", "user")) {
					 # Uninstalling conflicting mpss-psm* packages if present
					 if (rpm_is_installed("mpss-psm", "user")) {
						 rpm_uninstall("mpss-psm", "any", "--nodeps", "yes");
					 }
					 if (rpm_is_installed("mpss-psm-dev", "user")) {
						  rpm_uninstall("mpss-psm-dev", "any", "--nodeps", "yes");
					 }
					 rpm_install_list($srcdir, "user", @XEON_PHI_USER_RPM_LIST_OLD);
			 }
 
			 rpm_install_list ($srcdir, "user", @XEON_PHI_USER_RPM_LIST);
			 # Information about no matches found for packages in default directories
			 if (scalar @found_rpms == 0 && scalar @found_rpms_dev == 0) {
					printf ("Packages mpss-psm-* cannot be found in /root/, /tmp, /opt, /home dirs!\n");
					LogPrint ("Packages mpss-psm-* cannot be found in:  /root/, /tmp, /opt, /home dirs!\n");
			 }
		}
    } else {
		  #uninstalling conflicting mpss-psm* packages if present
		  if (rpm_is_installed("mpss-psm", "user")) {
				rpm_uninstall("mpss-psm", "any", "--nodeps", "yes");
		  }
		  if (rpm_is_installed("mpss-psm-dev", "user")) {
				rpm_uninstall("mpss-psm-dev", "any", "--nodeps", "yes");
		  }
		  rpm_install_list ($srcdir, "user", @TRUESCALE_USER_RPM_LIST);
     }

    # Install the 32bit infinipath-libs rpms
    if (!$OFED_no32bit) {
		rpm_install ($srcdir, "user32", "InfiniPath/infinipath-libs".$libs_suffix);
    }

    # Get current ib_qib options line (if it exists)
    $opts = qib_modprobe_get();
	 if ($opts =~ m/singleport=([x0-9A-Fa-f]+)/) {	
		 my $status = hex($1);
		 if ($status >= 1) {
			  $enabled = 1;
		 }
    }

    # Ask the user whether to enable single port
    $enable = GetYesNoWithMemory("SinglePort", 0, "Single Port Mode reallocates all Intel HCA resources to " .
		       "HCA Port 1.\n" .
		       "Enable Intel HCA Single Port Mode?", "y");

    # Enable/disable single port depending on user's preferences
    if ($enable && !$enabled) {
	if ($opts eq "") {
	    qib_modprobe_write("$truescale_modprobe_comment\noptions ib_qib singleport=1\n");
	} else {
	    # clean the option up
	    $opts =~ s/singleport=[x0-9a-fA-F]*[ \t]*//;
	    # re-add it
	    $opts =~ s/$/ singleport=1/;
	    qib_modprobe_write("$truescale_modprobe_comment\n$opts");
	}
    } elsif (!$enable && $enabled) {
	$opts =~ s/singleport=[x0-9a-fA-F]*[ \t]*//;
	if ($opts =~ /^options[ \t][ \t]*ib_qib[ \t]*$/) {
	    # if it was the only option, just remove the line
	    qib_modprobe_write("");
	} else {
	    qib_modprobe_write("$truescale_modprobe_comment\n$opts");
	}
    }
    
    check_dir ("/opt/iba");
    copy_systool_file ("$srcdir/comp.pl", "/opt/iba/.comp_truescale.pl");

    $ComponentWasInstalled{'truescale'} = 1;
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_truescale
{
    my $install_list = $_[0];
    my $installing_list = $_[1];
    my @packages;
    my $libs_suffix = "";
    my $prefix = rpm_query_attr_pkg ("mpi-libs", "INSTALLPREFIX");
    chomp $prefix;
    
    if (lc ($CUR_DISTRO_VENDOR) eq "suse" || lc ($CUR_DISTRO_VENDOR) eq "sles") {
	$libs_suffix = "-32bit";
    }
    NormalPrint ("Uninstalling $ComponentInfo{'truescale'}{'Name'}...\n");

    if ($OFED_xeonphi) {
		foreach my $x ( @XEON_PHI_USER_RPM_LIST, @XEON_PHI_USER_RPM_LIST, @TRUESCALE_OLD_RPM_LIST ) {
		  @packages = (@packages, basename ($x));
		  push (@packages, "mpss-psm");
		  push (@packages, "mpss-psm-dev");
      }
    } else {
      foreach my $x ( @TRUESCALE_USER_RPM_LIST, @TRUESCALE_OLD_RPM_LIST ) {
        @packages = (@packages, basename ($x));
      }
    }

    rpm_uninstall_list ("any", "verbose", @packages);
    # Uninstall 32bit *-libs rpms.
    rpm_uninstall_list ("user32", "verbose", ("infinipath-libs".$libs_suffix,
					      "mpi-libs".$libs_suffix));
    if (0 == system("grep '$truescale_modprobe_comment' >/dev/null 2>/dev/null " . qib_get_modprobe_file())) {
	# remove comment and the singleport option
	my $opts = qib_modprobe_get();
	$opts =~ s/singleport=[^\ ]+[\ \t]?//;
	if ($opts =~ /^options[ \t][ \t]*ib_qib[ \t]*$/) {
	    # if it was the only option, just remove the line
	    qib_modprobe_write("");
	} else {
	    qib_modprobe_write("$opts");
	}
    }
    
    if ( -d $prefix ) {
	my @files = glob ("$prefix/*");
	my $num = scalar (@files);
	if ( $num == 0 ) {
	    system ("rm -rf $prefix");
	}
    }
    
    system ("rm -rf $ROOT/opt/iba/.comp_truescale.pl");
    system ("rmdir $ROOT/opt/iba 2>/dev/null");
    $ComponentWasInstalled{'truescale'} = 0;
}

sub qib_get_modprobe_file()
{
    my $file;
    my ($major_distro_ver) = $CUR_VENDOR_VER =~ /^[[:alpha:]]*(\d+)\.?\d*/;
    my ($minor_distro_ver) = $CUR_VENDOR_VER =~ /^[[:alpha:]]*\d+\.(\d+)/;
    $minor_distro_ver ||= 0;

    if (lc ($CUR_DISTRO_VENDOR) eq "redhat" || lc ($CUR_DISTRO_VENDOR) eq "rhel") {
	if ($major_distro_ver ge 6) {
	    $file = "/etc/modprobe.d/ib_qib.conf";
	} else {
	    $file = "/etc/modprobe.conf";
	}
    } elsif (lc ($CUR_DISTRO_VENDOR) eq "suse" || lc ($CUR_DISTRO_VENDOR) eq "sles") {
	if ($major_distro_ver ge 11) {
	    $file = "/etc/modprobe.d/ib_qib.conf";
	} else {
	    $file = "/etc/modprobe.conf.local";
	}
    }
    return $file;
}

sub qib_modprobe_get()
{
    my $file = qib_get_modprobe_file();
    my $options = "";
    
    open(FILE, $file);
    while (my $line = <FILE>) {
	if ($line =~ /^options[ \t][ \t]*ib_qib[ \t]/) {
	    $options = $line;
	}
    }
    close (FILE);
    return $options;
}

sub qib_modprobe_write($)
{
    my $file = qib_get_modprobe_file();
    my $options = $_[0];
    my $found = 0;

    if ($file =~ /ib_qib.conf$/ && length($options) == 0) {
	# no options to be written to the QIB specific file, remove it
	system("rm -f $file");
	return;
    }

    open(FILE, $file);
    my @content = <FILE>;
    close(FILE);

    open(FILE, ">$file");
    foreach my $line ( @content ) {
	if ($line =~ /^options[ \t][ \t]*ib_qib[ \t]/) {
	    print FILE $options;
	    $found = 1;
	} elsif ($line =~ /^$truescale_modprobe_comment/) {
               # skip this line, we will put it back in when we add options line
	} else {
	    print FILE $line;
	}
    }
    if ($found != 1) {
	print FILE $options;
    }
    close(FILE);
}

#############################################################################
##
##    Intel SHMEM

my @INTEL_SHMEM_RPM_LIST = ( "SHMEM/intel-shmem", "SHMEM/intel-onesided",
	   				"SHMEM-Devel/intel-shmem-devel", "SHMEM-Devel/intel-onesided-devel",
				   	"SHMEM-Benchmarks/intel-shmem-benchmarks" );
my @QLOGIC_SHMEM_RPM_LIST = ( "SHMEM/qlogic-shmem", "SHMEM/qlogic-onesided",
	   				"SHMEM-Devel/qlogic-shmem-devel", "SHMEM-Devel/qlogic-onesided-devel",
				   	"SHMEM-Benchmarks/qlogic-shmem-benchmarks" );

# immediately stops or starts given component, only
# called if HasStart
sub start_intel_shmem
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_intel_shmem
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_intel_shmem
{
    my $srcdir = $ComponentInfo{'intel_shmem'}{'SrcDir'};
    return rpm_exists ("$srcdir/SHMEM", "user", "intel-shmem");
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_intel_shmem
{
    return ((-e "$ROOT/opt/iba/.comp_qlogic_shmem.pl"
                        || rpm_is_installed ("qlogic-shmem", "user"))
        || (-e "$ROOT/opt/iba/.comp_intel_shmem.pl"
                        || rpm_is_installed ("intel-shmem", "user")));
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_intel_shmem
{
        my $shmem_version;
        if (rpm_is_installed ("qlogic-shmem", "user")) {
                $shmem_version = rpm_query_version_release_pkg("qlogic-shmem");
        } elsif (rpm_is_installed ("intel-shmem", "user")) {
                $shmem_version = rpm_query_version_release_pkg("intel-shmem");
        }
        return $shmem_version;
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_intel_shmem
{
    my $srcdir = $ComponentInfo{'intel_shmem'}{'SrcDir'};
    my $rpm = rpm_resolve ("$srcdir/SHMEM", "user", "intel-shmem");
    return rpm_query_version_release ($rpm);
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_intel_shmem
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_intel_shmem
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use to verify OS
# has proper dependent rpms installed.
sub check_os_prereqs_intel_shmem
{
	return rpm_check_os_prereqs("intel_shmem", "user", ( "libstdc++"));
}                              

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_intel_shmem
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_intel_shmem
{
    my $install_list = $_[0];
    my $installing_list = $_[1];
    my $srcdir = $ComponentInfo{'intel_shmem'}{'SrcDir'};
    my $version = media_version_intel_shmem();
    
    printf ("Installing $ComponentInfo{'intel_shmem'}{'Name'} $version...\n");
    LogPrint ("Installing $ComponentInfo{'intel_shmem'}{'Name'} $version for $CUR_OS_VER\n");
    
    rpm_install_list ("$srcdir", "user", @INTEL_SHMEM_RPM_LIST );

    check_dir ("/opt/iba");
    #Remove older file
    system( "rm -rf $ROOT/opt/iba/.comp_qlogic_shmem.pl");
    copy_systool_file ("$srcdir/comp.pl", "/opt/iba/.comp_intel_shmem.pl");
    
    $ComponentWasInstalled{'intel_shmem'} = 1;
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_intel_shmem
{
    my $install_list = $_[0];
    my $installing_list = $_[1];
    my @packages;

    NormalPrint ("Uninstalling $ComponentInfo{'intel_shmem'}{'Name'}...\n");

    foreach my $x ( @QLOGIC_SHMEM_RPM_LIST ) {
		@packages = (@packages, basename ($x));
    }
    foreach my $x ( @INTEL_SHMEM_RPM_LIST ) {
		@packages = (@packages, basename ($x));
    }
    
    rpm_uninstall_list ("any", "verbose", @packages);

    system( "rm -rf $ROOT/opt/iba/.comp_qlogic_shmem.pl");
    system ("rm -rf $ROOT/opt/iba/.comp_intel_shmem.pl");
    system ("rmdir $ROOT/opt/iba 2>/dev/null"); # remove only if empty
    $ComponentWasInstalled{'intel_shmem'} = 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.
#
# This file is used by the Intel Installer scripts. If you are not using the
# Intel installer, this file can be ignored.
use strict;
use File::Basename;

#############################################################################
##
##    MPI installation generic functions

# these functions can be used by the MPI specific install functions

# installs PSM based MPI component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_generic_mpi
{
    my $install_list = $_[0];
    my $installing_list = $_[1];
    my $mpiname = $_[2];
    my $compiler = $_[3];
    my $mpifullname = "$mpiname"."_$compiler"."_qlc";
    my $srcdir = $ComponentInfo{$mpifullname}{'SrcDir'};
    my $version = eval "media_version_$mpifullname()";
    
    printf ("Installing $ComponentInfo{$mpifullname}{'Name'} $version...\n");
    LogPrint ("Installing $ComponentInfo{$mpifullname}{'Name'} $version for $CUR_OS_VER\n");
    # make sure any old potentially custom built versions of mpi are uninstalled
    my @list = ( "$mpifullname", "mpitests_$mpifullname" );
    rpm_uninstall_list2("any", "--nodeps", 'silent', @list);
    
    my $rpmfile = rpm_resolve("$srcdir/OtherMPIs", "any", "$mpifullname");
    if ( "$rpmfile" ne "" && -e "$rpmfile" ) {
	my $mpich_prefix= "/usr/mpi/$compiler/$mpiname-"
	    . rpm_query_attr($rpmfile, "VERSION") . "-qlc";
	if ( -d "$mpich_prefix" ) {
	    if (GetYesNo ("Remove $mpich_prefix directory?", "y")) {
		LogPrint "rm -rf $mpich_prefix\n";
		system("rm -rf $mpich_prefix");
	    }
	}
    }
    # enable this code if mpitests is missing for some compilers or MPIs
    #my $mpitests_rpmfile = rpm_resolve("$srcdir/OtherMPIs", "any", "mpitests_$mpifullname");
    #if ( "$mpitests_rpmfile" ne "" && -e "$mpitests_rpmfile" ) {
        rpm_install_list ("$srcdir/OtherMPIs", "user", @list);
    #} else {
    #    rpm_install("$srcdir/OtherMPIs", "user", "$mpifullname");
    #}
    check_dir ("/opt/iba");
    copy_systool_file ("$srcdir/comp.pl", "/opt/iba/.comp_$mpifullname.pl");
    
    $ComponentWasInstalled{$mpifullname} = 1;
}

sub installed_generic_mpi
{
    my $mpiname = $_[0];
    my $compiler = $_[1];
    my $mpifullname = "$mpiname"."_$compiler"."_qlc";

    return ( -e "$ROOT/opt/iba/.comp_$mpifullname.pl"
		   	|| rpm_is_installed ($mpifullname, "user") );
}

sub uninstall_generic_mpi
{
    my $install_list = $_[0];
    my $installing_list = $_[1];
    my $mpiname = $_[2];
    my $compiler = $_[3];
    my $mpifullname = "$mpiname"."_$compiler"."_qlc";
    my $rc;
    my $top;
    
    NormalPrint ("Uninstalling $ComponentInfo{$mpifullname}{'Name'}...\n");
    if (lc($CUR_DISTRO_VENDOR) eq "redhat" &&
	($CUR_VENDOR_VER eq "ES6" || $CUR_VENDOR_VER eq "ES6.1" || $CUR_VENDOR_VER eq "ES7")) {
	$top = rpm_query_attr_pkg("$mpifullname", "INSTPREFIXES");
    } else {
	$top = rpm_query_attr_pkg("$mpifullname", "INSTALLPREFIX");
    }
    if ($top eq "" || $top =~ /is not installed/) {
	$top = undef;
    } else {
	$top = `dirname $top`;
	chomp $top;
    }
    
    # uninstall tests in case built by do_build
    $rc = rpm_uninstall ("mpitests_$mpifullname", "user", "", "verbose");
    $rc = rpm_uninstall ($mpifullname, "user", "", "verbose");

    if ( -d $top ) {
	my @files = glob("$top/*");
	my $num = scalar (@files);
	if ( $num == 0 ) {
	    system ("rm -rf $top");
	}
    }
    
    system ("rm -rf $ROOT/opt/iba/.comp_$mpifullname.pl");
    system ("rmdir $ROOT/opt/iba 2>/dev/null"); # remove only if empty
    $ComponentWasInstalled{$mpifullname} = 0;
}

#############################################################################
##
##    OpenMPI GCC

# immediately stops or starts given component, only
# called if HasStart
sub start_openmpi_gcc_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_openmpi_gcc_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_openmpi_gcc_qlc
{
    my $srcdir = $ComponentInfo{'openmpi_gcc_qlc'}{'SrcDir'};
    return rpm_exists ("$srcdir/OtherMPIs", "user", "openmpi_gcc_qlc");
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_openmpi_gcc_qlc
{
    return  installed_generic_mpi("openmpi", "gcc");
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_openmpi_gcc_qlc
{
    return rpm_query_version_release_pkg ("openmpi_gcc_qlc");
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_openmpi_gcc_qlc
{
    my $srcdir = $ComponentInfo{'openmpi_gcc_qlc'}{'SrcDir'};
    my $rpm = rpm_resolve ("$srcdir/OtherMPIs", "user", "openmpi_gcc_qlc");
    return rpm_query_version_release ($rpm);
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_openmpi_gcc_qlc
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_openmpi_gcc_qlc
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use to verify OS
# has proper dependent rpms installed.
sub check_os_prereqs_openmpi_gcc_qlc
{
	return rpm_check_os_prereqs("openmpi_gcc_qlc", "user", ( "libstdc++"));
}                              

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_openmpi_gcc_qlc
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_openmpi_gcc_qlc
{
    install_generic_mpi("$_[0]", "$_[1]", "openmpi", "gcc");
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_openmpi_gcc_qlc
{
    uninstall_generic_mpi("$_[0]", "$_[1]", "openmpi", "gcc");
}

#############################################################################
##
##    OpenMPI PathScale

# immediately stops or starts given component, only
# called if HasStart
sub start_openmpi_pathscale_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_openmpi_pathscale_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_openmpi_pathscale_qlc
{
    my $srcdir = $ComponentInfo{'openmpi_pathscale_qlc'}{'SrcDir'};
    return rpm_exists ("$srcdir/OtherMPIs", "user", "openmpi_pathscale_qlc");
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_openmpi_pathscale_qlc
{
    return  installed_generic_mpi("openmpi", "pathscale");
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_openmpi_pathscale_qlc
{
    return rpm_query_version_release_pkg ("openmpi_pathscale_qlc");
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_openmpi_pathscale_qlc
{
    my $srcdir = $ComponentInfo{'openmpi_pathscale_qlc'}{'SrcDir'};
    my $rpm = rpm_resolve ("$srcdir/OtherMPIs", "user", "openmpi_pathscale_qlc");
    return rpm_query_version_release ($rpm);
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_openmpi_pathscale_qlc
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_openmpi_pathscale_qlc
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use to verify OS
# has proper dependent rpms installed.
sub check_os_prereqs_openmpi_pathscale_qlc
{
	# we allow this to install even if pathscale compiler runtime not available
	return rpm_check_os_prereqs("openmpi_pathscale_qlc", "user", ( "libstdc++"));
}                              

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_openmpi_pathscale_qlc
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_openmpi_pathscale_qlc
{
    install_generic_mpi("$_[0]", "$_[1]", "openmpi", "pathscale");
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_openmpi_pathscale_qlc
{
    uninstall_generic_mpi("$_[0]", "$_[1]", "openmpi", "pathscale");
}

#############################################################################
##
##    OpenMPI Intel

# immediately stops or starts given component, only
# called if HasStart
sub start_openmpi_intel_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_openmpi_intel_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_openmpi_intel_qlc
{
    my $srcdir = $ComponentInfo{'openmpi_intel_qlc'}{'SrcDir'};
    return rpm_exists ("$srcdir/OtherMPIs", "user", "openmpi_intel_qlc");
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_openmpi_intel_qlc
{
    return  installed_generic_mpi("openmpi", "intel");
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_openmpi_intel_qlc
{
    return rpm_query_version_release_pkg ("openmpi_intel_qlc");
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_openmpi_intel_qlc
{
    my $srcdir = $ComponentInfo{'openmpi_intel_qlc'}{'SrcDir'};
    my $rpm = rpm_resolve ("$srcdir/OtherMPIs", "user", "openmpi_intel_qlc");
    return rpm_query_version_release ($rpm);
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_openmpi_intel_qlc
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_openmpi_intel_qlc
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use to verify OS
# has proper dependent rpms installed.
sub check_os_prereqs_openmpi_intel_qlc
{
	# we allow this to install even if intel compiler runtime not available
	return rpm_check_os_prereqs("openmpi_intel_qlc", "user", ( "libstdc++"));
}                              

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_openmpi_intel_qlc
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_openmpi_intel_qlc
{
    install_generic_mpi("$_[0]", "$_[1]", "openmpi", "intel");
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_openmpi_intel_qlc
{
    uninstall_generic_mpi("$_[0]", "$_[1]", "openmpi", "intel");
}

#############################################################################
##
##    OpenMPI PGI

# immediately stops or starts given component, only
# called if HasStart
sub start_openmpi_pgi_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_openmpi_pgi_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_openmpi_pgi_qlc
{
    my $srcdir = $ComponentInfo{'openmpi_pgi_qlc'}{'SrcDir'};
    return rpm_exists ("$srcdir/OtherMPIs", "user", "openmpi_pgi_qlc");
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_openmpi_pgi_qlc
{
    return  installed_generic_mpi("openmpi", "pgi");
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_openmpi_pgi_qlc
{
    return rpm_query_version_release_pkg ("openmpi_pgi_qlc");
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_openmpi_pgi_qlc
{
    my $srcdir = $ComponentInfo{'openmpi_pgi_qlc'}{'SrcDir'};
    my $rpm = rpm_resolve ("$srcdir/OtherMPIs", "user", "openmpi_pgi_qlc");
    return rpm_query_version_release ($rpm);
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_openmpi_pgi_qlc
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_openmpi_pgi_qlc
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use to verify OS
# has proper dependent rpms installed.
sub check_os_prereqs_openmpi_pgi_qlc
{
	# we allow this to install even if pgi compiler runtime not available
	return rpm_check_os_prereqs("openmpi_pgi_qlc", "user", ( "libstdc++"));
}                              

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_openmpi_pgi_qlc
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_openmpi_pgi_qlc
{
	install_generic_mpi("$_[0]", "$_[1]", "openmpi", "pgi");
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_openmpi_pgi_qlc
{
    uninstall_generic_mpi("$_[0]", "$_[1]", "openmpi", "pgi");
}

#############################################################################
##
##    MVAPICH2 GCC

# immediately stops or starts given component, only
# called if HasStart
sub start_mvapich2_gcc_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_mvapich2_gcc_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_mvapich2_gcc_qlc
{
    my $srcdir = $ComponentInfo{'mvapich2_gcc_qlc'}{'SrcDir'};
    return rpm_exists ("$srcdir/OtherMPIs", "user", "mvapich2_gcc_qlc");
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_mvapich2_gcc_qlc
{
    return  installed_generic_mpi("mvapich2", "gcc");
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_mvapich2_gcc_qlc
{
    return rpm_query_version_release_pkg ("mvapich2_gcc_qlc");
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_mvapich2_gcc_qlc
{
    my $srcdir = $ComponentInfo{'mvapich2_gcc_qlc'}{'SrcDir'};
    my $rpm = rpm_resolve ("$srcdir/OtherMPIs", "user", "mvapich2_gcc_qlc");
    return rpm_query_version_release ($rpm);
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_mvapich2_gcc_qlc
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_mvapich2_gcc_qlc
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use to verify OS
# has proper dependent rpms installed.
sub check_os_prereqs_mvapich2_gcc_qlc
{
	return rpm_check_os_prereqs("mvapich2_gcc_qlc", "user", ( "sysfsutils", "libstdc++"));
}                              

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_mvapich2_gcc_qlc
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_mvapich2_gcc_qlc
{
	install_generic_mpi("$_[0]", "$_[1]", "mvapich2", "gcc");
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_mvapich2_gcc_qlc
{
    uninstall_generic_mpi("$_[0]", "$_[1]", "mvapich2", "gcc");
}

#############################################################################
##
##    MVAPICH2 PathScale

# immediately stops or starts given component, only
# called if HasStart
sub start_mvapich2_pathscale_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_mvapich2_pathscale_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_mvapich2_pathscale_qlc
{
    my $srcdir = $ComponentInfo{'mvapich2_pathscale_qlc'}{'SrcDir'};
    return rpm_exists ("$srcdir/OtherMPIs", "user", "mvapich2_pathscale_qlc");
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_mvapich2_pathscale_qlc
{
    return  installed_generic_mpi("mvapich2", "pathscale");
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_mvapich2_pathscale_qlc
{
    return rpm_query_version_release_pkg ("mvapich2_pathscale_qlc");
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_mvapich2_pathscale_qlc
{
    my $srcdir = $ComponentInfo{'mvapich2_pathscale_qlc'}{'SrcDir'};
    my $rpm = rpm_resolve ("$srcdir/OtherMPIs", "user", "mvapich2_pathscale_qlc");
    return rpm_query_version_release ($rpm);
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_mvapich2_pathscale_qlc
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_mvapich2_pathscale_qlc
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use to verify OS
# has proper dependent rpms installed.
sub check_os_prereqs_mvapich2_pathscale_qlc
{
	# we allow this to install even if pathscale compiler runtime not available
	return rpm_check_os_prereqs("mvapich2_pathscale_qlc", "user", ( "sysfsutils", "libstdc++"));
}                              

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_mvapich2_pathscale_qlc
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_mvapich2_pathscale_qlc
{
	install_generic_mpi("$_[0]", "$_[1]", "mvapich2", "pathscale");
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_mvapich2_pathscale_qlc
{
    uninstall_generic_mpi("$_[0]", "$_[1]", "mvapich2", "pathscale");
}

#############################################################################
##
##    MVAPICH2 Intel

# immediately stops or starts given component, only
# called if HasStart
sub start_mvapich2_intel_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_mvapich2_intel_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_mvapich2_intel_qlc
{
    my $srcdir = $ComponentInfo{'mvapich2_intel_qlc'}{'SrcDir'};
    return rpm_exists ("$srcdir/OtherMPIs", "user", "mvapich2_intel_qlc");
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_mvapich2_intel_qlc
{
    return  installed_generic_mpi("mvapich2", "intel");
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_mvapich2_intel_qlc
{
    return rpm_query_version_release_pkg ("mvapich2_intel_qlc");
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_mvapich2_intel_qlc
{
    my $srcdir = $ComponentInfo{'mvapich2_intel_qlc'}{'SrcDir'};
    my $rpm = rpm_resolve ("$srcdir/OtherMPIs", "user", "mvapich2_intel_qlc");
    return rpm_query_version_release ($rpm);
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_mvapich2_intel_qlc
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_mvapich2_intel_qlc
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use to verify OS
# has proper dependent rpms installed.
sub check_os_prereqs_mvapich2_intel_qlc
{
	# we allow this to install even if intel compiler runtime not available
	return rpm_check_os_prereqs("mvapich2_intel_qlc", "user", ( "sysfsutils", "libstdc++"));
}                              

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_mvapich2_intel_qlc
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_mvapich2_intel_qlc
{
	install_generic_mpi("$_[0]", "$_[1]", "mvapich2", "intel");
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_mvapich2_intel_qlc
{
    uninstall_generic_mpi("$_[0]", "$_[1]", "mvapich2", "intel");
}

#############################################################################
##
##    MVAPICH2 PGI

# immediately stops or starts given component, only
# called if HasStart
sub start_mvapich2_pgi_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub stop_mvapich2_pgi_qlc
{
}

# is component X available on the install media (use of this
# allows for optional components in packaging or limited availability if a
# component isn't available on some OS/CPU combos)
sub available_mvapich2_pgi_qlc
{
    my $srcdir = $ComponentInfo{'mvapich2_pgi_qlc'}{'SrcDir'};
    return rpm_exists ("$srcdir/OtherMPIs", "user", "mvapich2_pgi_qlc");
}

# is component X presently installed on the system.  This is
# a quick check, not a "verify"
sub installed_mvapich2_pgi_qlc
{
    return  installed_generic_mpi("mvapich2", "pgi");
}

# what is the version installed on system.  Only
# called if installed_X is true.  versions are short strings displayed and
# logged, no operations are done (eg. only compare for equality)
sub installed_version_mvapich2_pgi_qlc
{
    return rpm_query_version_release_pkg ("mvapich2_pgi_qlc");
}

# only called if available_X.  Indicates version on
# media.  Will be compared with installed_version_X to determine if
# present installation is up to date.  Should return exact same format for
# version string so comparison of equality is possible.
sub media_version_mvapich2_pgi_qlc
{
    my $srcdir = $ComponentInfo{'mvapich2_pgi_qlc'}{'SrcDir'};
    my $rpm = rpm_resolve ("$srcdir/OtherMPIs", "user", "mvapich2_pgi_qlc");
    return rpm_query_version_release ($rpm);
}

# used to build/rebuild component on local system (if
# supported).  We support this for many items in comp_ofed.pl,
# comp_qlgc_vnic.pl and comp_qlgc_srp.pl.  Other components (like SM) are
# not available in source and hence do not support this and simply
# implement a noop.
sub build_mvapich2_pgi_qlc
{
    my $osver = $_[0];
    my $debug = $_[1];
    my $build_temp = $_[2];
    my $force = $_[3];

    return 0;
}

# does this need to be reinstalled.  Mainly used for
# ofed due to subtle changes such as install prefix or kernel options
# which may force a reinstall.  You'll find this is a noop in most others.
sub need_reinstall_mvapich2_pgi_qlc
{
    my $install_list = shift ();
    my $installing_list = shift ();

    return "no";
}

# called for all components before they are installed.  Use to verify OS
# has proper dependent rpms installed.
sub check_os_prereqs_mvapich2_pgi_qlc
{
	# we allow this to install even if pgi compiler runtime not available
	return rpm_check_os_prereqs("mvapich2_pgi_qlc", "user", ( "sysfsutils", "libstdc++"));
}                              

# called for all components before they are installed.  Use
# to build things if needed, etc.
sub preinstall_mvapich2_pgi_qlc
{
    my $install_list = $_[0];
    my $installing_list = $_[1];

    my $full = "";
    my $rc;

    return 0;
}

# installs component.  also handles reinstall on top of
# existing installation and upgrade.
sub install_mvapich2_pgi_qlc
{
	install_generic_mpi("$_[0]", "$_[1]", "mvapich2", "pgi");
}

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

# uninstalls component.  May be called even if component is
# partially or not installed at all in which case should do its best to
# get rid or what might remain of component from a previously aborted
# uninstall or failed install
sub uninstall_mvapich2_pgi_qlc
{
    uninstall_generic_mpi("$_[0]", "$_[1]", "mvapich2", "pgi");
}
#!/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: unknown]

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="truescale";
$IB_STACK="OPENIB";
my $Force_Install = 0;# force option used to force install on unsupported distro

$Skip_UsrLocalSymLinks=1;	# no /usr/local symlinks for OFED installs

	# Names of supported install components
	# must be listed in depdency order such that prereqs appear 1st
my @TrueScaleMPIComponents = ( "mvapich2_gcc_qlc", "mvapich2_pgi_qlc",
		   			"mvapich2_intel_qlc",
					"openmpi_gcc_qlc", "openmpi_pgi_qlc",
				   	"openmpi_intel_qlc", "intel_shmem" );
# these are now gone, list them so they get uninstalled
my @old_TrueScaleMPIComponents = ( "mvapich2_pathscale_qlc", "openmpi_pathscale_qlc" );
@Components = ( "truescale", @TrueScaleMPIComponents,
					@old_TrueScaleMPIComponents, );

@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_truescale";

# 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 = (
	"iba_config_truescale" =>	{ Name => "iba_config_truescale",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => "", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"truescale" =>	{ Name => "True Scale HCA Libs",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => "", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"mvapich2_gcc_qlc" =>	{ Name => "MVAPICH2/PSM (gcc)",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " truescale ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"mvapich2_pgi_qlc" =>	{ Name => "MVAPICH2/PSM (PGI)",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " truescale ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"mvapich2_pathscale_qlc" =>	{ Name => "MVAPICH2/PSM (PSc)",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " truescale ", CoReq => "",
					  Hidden => 1, Disabled => 1,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"mvapich2_intel_qlc" =>	{ Name => "MVAPICH2/PSM (Intel)",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " truescale ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"openmpi_gcc_qlc" =>	{ Name => "OpenMPI/PSM (gcc)",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " truescale ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"openmpi_pgi_qlc" =>	{ Name => "OpenMPI/PSM (PGI)",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " truescale ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"openmpi_pathscale_qlc" =>	{ Name => "OpenMPI/PSM (PSc)",
					  DefaultInstall => $State_DoNotInstall,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " truescale ", CoReq => "",
					  Hidden => 1, Disabled => 1,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"openmpi_intel_qlc" =>	{ Name => "OpenMPI/PSM (Intel)",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " truescale ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	"intel_shmem" =>	{ Name => "SHMEM",
					  DefaultInstall => $State_Install,
					  SrcDir => ".", DriverSubdir => "",
					  PreReq => " truescale ", CoReq => "",
					  Hidden => 0, Disabled => 0,
					  HasStart => 0, HasFirmware => 0, DefaultStart => 0,
					  StartPreReq => "",
					  StartComponents => [ ],
					},
	);
	# translate from startup script name to component/subcomponent name
%StartupComponent = (
			);
	# has component been loaded since last configured autostart
%ComponentWasInstalled = (
				"truescale" => 0,
				"mvapich2_gcc_qlc" => 0,
	   			"mvapich2_pgi_qlc" => 0,
	   			"mvapich2_pathscale_qlc" => 0,
				"mvapich2_intel_qlc" => 0,
				"openmpi_gcc_qlc" => 0,
	   			"openmpi_pgi_qlc" => 0,
	   			"openmpi_pathscale_qlc" => 0,
				"openmpi_intel_qlc" => 0,
				"intel_shmem" => 0,
			);

# ==========================================================================
# iba_config_truescale 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_truescale
{
	my $srcdir=$ComponentInfo{'iba_config_truescale'}{'SrcDir'};
	return ( -e "$srcdir/INSTALL" );
}

sub install_iba_config_truescale
{
	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_truescale'}{'SrcDir'};
	NormalPrint("Installing $ComponentInfo{'iba_config_truescale'}{'Name'}...\n");

	copy_systool_file("$srcdir/INSTALL", "/sbin/iba_config_truescale");
	# no need for a version file, truescale will have its own

	$ComponentWasInstalled{'iba_config_truescale'}=1;
}

sub uninstall_iba_config_truescale
{
	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_truescale'}{'Name'}...\n")
;

	system("rm -rf $ROOT/sbin/iba_config_truescale");
	$ComponentWasInstalled{'iba_config_truescale'}=0;
}

my $allow_install;
if ( my_basename($0) ne "INSTALL" )
{
	$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";
	#}
}

# TBD can we generalize and combine with ibaccess_main.pl function
sub verify_distrib
{
	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";
		} 
		
		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";
		} 
		NormalPrint "For $supported_arch: $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";
		}
	}
}

sub Usage
{
	if ( $allow_install ) {
		#printf STDERR "Usage: $0 [-r root] [-v|-vv] [-a|-n|-U|-u|-s|-i comp|-e comp] [-E comp] [-D comp] [--no32bit|--32bit] [--without-depcheck] [--force] [--answer keyword=value]\n";
		# autostart not applicable
		printf STDERR "Usage: $0 [-r root] [-v|-vv] [-a|-U|-u|-i comp|-e comp] [--no32bit|--32bit] [--without-depcheck] [--force] [--answer keyword=value] [--with-xeon-phi=<path>]\n";
	} else {
		#printf STDERR "Usage: $0 [-r root] [-v|-vv] [-u|-s|-e comp] [-E comp] [-D comp] [--answer keyword=value]\n";
		printf STDERR "Usage: $0 [-r root] [-v|-vv] [-u|-e comp] [--answer keyword=value]\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 "       --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 "       --without-depcheck - disable check of OS dependencies\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 - enable install of xeon phi packages\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";
	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);
}

sub process_args
{
	my $arg;
	my $last_arg;
	my $setroot = 0;
	my $install_opt = 0;
	my $setcomp = 0;
	my $setanswer = 0;
	my $setenabled = 0;
	my $setdisabled = 0;
	my $comp = 0;
	my $got_32bit_option = 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 )
				{
					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 )
				{
					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 )
				{
					printf STDERR "Invalid component: $arg\n";
					Usage;
				}
			} elsif ( "$arg" eq "-r" ) {
				$setroot=1;
			} elsif ( "$arg" eq "-v" ) {
				$LogLevel=1;
			} elsif ( "$arg" eq "-vv" ) {
				$LogLevel=2;
			} elsif ( "$arg" eq "-i" ) {
				$Default_CompInstall=1;
				$Default_Prompt=1;
				$setcomp=1;
				if ($install_opt || $Default_CompUninstall) {
					# 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) {
					# 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;
			#} elsif ( "$arg" eq "-D" ) {
			#	$Default_Autostart=1;
			#	$Default_DisableAutostart=1;
			#	$Default_Prompt=1;
			#	$setdisabled=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 "--answer" ) {
				$setanswer=1;
			} elsif ( "$arg" eq "--force" ) {
				$Force_Install=1;
			} elsif ( "$arg" eq "-C" ) {
				ShowComponents;
				exit(0);
			} elsif ( "$arg" eq "-V" ) {
				printf "$VERSION\n";
				exit(0);
			} 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 || $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;
	}
}

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, 2);
	}
	if ($Default_CompUninstall ) {
		NormalPrint ("Uninstalling Selected IB Software\n");
		@INSTALL_CHOICES = ( @INSTALL_CHOICES, 2);
	}
	#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 Driver Autostart \n");
	$max_inp=1;
	if (!$allow_install)
	{
		printf ("   2) Uninstall Software\n");
		$max_inp=2;
	}
	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;
open_log("");
verify_os_ver;
verify_modtools;
set_libdir;
if ($allow_install) {
	verify_distrib;
}
# compute mand_target_cpu32 and initialize target_cpu32
init_cpu32();

RESTART:
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 == 2)
	{
		show_uninstall_menu(1);
		if (! $Default_Prompt ) {
			goto RESTART;
		} else {
			if ($exit_code == 0) {
				print "Done Uninstalling IB Software.\n"
			}
		}
	}
	#elsif ($INSTALL_CHOICE == 2) 
	#{
	#	reconfig_autostart;
	#	if (! $Default_Prompt ) {
	#		goto RESTART;
	#	} else {
	#		print "Done IB Driver Autostart Configuration.\n"
	#	}
	#}
}
close_log;
exit $exit_code;
