#!/bin/bash

# Voltaire IB setup script.
# configure / install /uninstall IB stack.
COLUMNS=60
export PATH=/usr/mst/bin:/usr/voltaire/scripts:/usr/voltaire/bin:/usr/mellanox/bin:$PATH
PS3="=> "
#This flag will determine if continue with HCA burning or halt` 
BURNING_FLAG=1 
xver=$(cat /usr/voltaire/ibhost-release 2>/dev/null)
if [ "X$xver" = X ]; then
    xver="unknown version"
fi
MODDIRS="/usr/voltaire/modules/$(uname -r)"
FW_IMAGE=/usr/mst/fw-23108-rel-3.0.0/fw-23108-a1-rel.host.sanmina.img
DHCP_ON=1
DHCP_OFF=0
KEEP_IP_IN_REPOSITORY="yes"
MIN_MTU=68


#arrays declaration for supporting more than one pkey

declare -a IPOIB_UD
declare -a ALIP_ARR
declare -a ALNM_ARR
declare -a ALBR_ARR
declare -a AMTU_ARR

declare -a DHCP_MODE_ARR
declare -a ACTIVE_ARR

declare -a LIP_ARR
declare -a LNM_ARR
declare -a LBR_ARR
declare -a LMTU_ARR


function verify_ip(){
	echo "$1" | perl -ne 'chomp;exit 0 if /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/&&$1<256&&$2<256&&$3<256&&$4<256;exit 1'
}

function loadmodule(){
    m=$1
    if [ `uname -r | cut -f 1,2 -d .` = "2.6" ]; then   # 2.6 module names end with a ".ko" instead of 2.4's ".o"
        m=`echo "$1" | sed s/\.o$/\.ko/g`
    fi
    shift
    #echo "loading $m"
    for d in ${MODDIRS} ; do
        if [ -e $d/$m ] ; then
            if ! insmod $d/$m "${@}" >/dev/null 2>&1 ; then
		echo "failed to load $d/$m ${@} !"
                return 1
            fi
            return 0
        fi
    done
    echo "module '$m' not found."
    return 1
}

# -------------- Start.
ib_start(){
    ibhost.init start
}
# -------------- Stop.
ib_stop(){
    ibhost.init stop
}

# -------------- Configure
ipoib_config_auto()
{
    for (( i=0; i<64; i++ ))
    do
    	if [[ $IB_IF == 'ipoib'$i ]]; then
		break
	fi
    done
    
    pkey=$(rep-get interfaces/ipoib-ud pkey$i | perl -ne 'print hex')
    if [[ $pkey -eq 0 ]]; then
	echo "You trying to configure not existing interface"
	echo "If you want to add interface use ib-setup"
	exit 1
    fi
    
    if [[ -z $ACTIVE ]]; then
    	ACTIVE_ARR[$i]=$(rep-get interfaces/ipoib-ud active$i | perl -ne 'print hex')
	if [[ -z ${ACTIVE_ARR[$i]} ]]; then
		ACTIVE_ARR[$i]=1
	fi
    else
    	ACTIVE_ARR[$i]=$ACTIVE
	rep-set interfaces/ipoib-ud active$i $(printf "0x%08x" ${ACTIVE_ARR[$i]})
    	rep_mset voltaire/interfaces/ipoib-ud/ active$i $(printf "0x%08x" ${ACTIVE_ARR[$i]})
    fi

    if [[ ! -z $NEW_NNN && ! -z $NEW_LIP ]] ; then
	echo "You can only enter one of the following options :network,ip or dhcp"
	exit 1
    elif [[ ! -z $NEW_NNN && ! -z $NEW_LDHCP ]] ; then
	echo "You can only enter one of the following options :network,ip or dhcp"
	exit 1
    elif [[ ! -z $NEW_LDHCP && ! -z $NEW_LIP ]] ; then
	echo "You can only enter one of the following options :network,ip or dhcp"
	exit 1
# Network was entered calculate params from eth0 
    elif [[ ! -z $NEW_NNN ]] ; then
        exec 2>/dev/null
	
        case "${OS}" in
        Darwin)
	ELIP=$(ifconfig $ETH_IF 2>/dev/null | perl -ne 'print "$1\n"if/inet \s*(\S+)/i')
	ELNM=$(ifconfig $ETH_IF 2>/dev/null | perl -ne 'print "$1\n"if/netmask \s*(\S+)/i')
	ELBR=$(ifconfig $ETH_IF 2>/dev/null | perl -ne 'print "$1\n"if/broadcast \s*(\S+)/i')
        ;;
        *)

	ELIP=$(ifconfig ${ETH_IF} 2>/dev/null | perl -ne 'print "$1\n"if/inet addr:\s*(\S+)/i')
	ELNM=$(ifconfig ${ETH_IF} 2>/dev/null | perl -ne 'print "$1\n"if/mask:\s*(\S+)/i')
	ELBR=$(ifconfig ${ETH_IF} 2>/dev/null | perl -ne 'print "$1\n"if/bcast:\s*(\S+)/i')
        ;;
        esac


	NIP=$( perl -e 'use Socket ; $iaddr = inet_aton("'$ELIP'") ; $netmask = inet_aton("'$ELNM'") ; $newip = inet_aton("'$NEW_NNN'") ; $newip= ($iaddr & ~ $netmask) | $newip ; $NIP=inet_ntoa($newip);print $NIP' )
	NBR=$( perl -e 'use Socket ; $iaddr = inet_aton("'$ELBR'") ; $netmask = inet_aton("'$ELNM'") ; $newip = inet_aton("'$NEW_NNN'") ; $newip= ($iaddr & ~ $netmask) | $newip ; $NIP=inet_ntoa($newip);print $NIP' )

	if [[ $OS == "Darwin" ]]; then
		LIP=$NIP
		LNM=$ELNM
		LBR=$NBR
		LMTU=1500
	else
		LIP_ARR[$i]=$NIP
		LNM_ARR[$i]=$ELNM
		LBR_ARR[$i]=$NBR
		LMTU_ARR[$i]=1500
	fi
# IP address was entered calculate params from IP
    elif [[ ! -z $NEW_LIP ]] ; then
    	    if [[ $OS == "Darwin" ]]; then
	    	LIP=$NEW_LIP
	    else
    	    	LIP_ARR[$i]=$NEW_LIP
	    fi

	    if [[ -z "$NEW_LNM" ]] ; then
                if [[ -e /bin/ipcalc ]] ; then
                        if [[ $OS == "Darwin" ]]; then
                                LNM=$(/bin/ipcalc -m ${LIP} | awk -F= '/NETMASK/{print $2}')
                        else
                                LNM_ARR[$i]=$(/bin/ipcalc -m ${LIP_ARR[$i]} | awk -F= '/NETMASK/{print $2}')
                        fi
                else
                        exec 2>/dev/tty
                        echo "Your system doesn't support ipcalc. Enter Netmask address and try again"
                        exit 1
                fi
            else
                LNM_ARR[$i]=$NEW_LNM
            fi
                                                                                                                            
            if [[ -z "$NEW_LBR" ]] ; then
                if [[ -e /bin/ipcalc ]] ; then
                        if [[ $OS == "Darwin" ]]; then
                                LBR=$(/bin/ipcalc -b ${LIP} ${LNM} | awk -F= '/BROADCAST/{print $2}')
                        else
                                LBR_ARR[$i]=$(/bin/ipcalc -b ${LIP_ARR[$i]} ${LNM_ARR[$i]} | awk -F= '/BROADCAST/{print $2}')
                        fi
                else
                        if [[ $OS == "Darwin" ]]; then
                                LBR=$( perl -e 'use Socket ; $iaddr = inet_aton("'${LIP}'") ; $netmask = inet_aton("'${LNM}'") ; $newbroadcast = ( $iaddr | ~ $netmask ) ; ${LBR}=inet_ntoa($newbroadcast) ; print $NEW_LBR')
                        else
                                LBR_ARR[$i]=$( perl -e 'use Socket ; $iaddr = inet_aton("'${LIP_ARR[$i]}'") ; $netmask = inet_aton("'${LNM_ARR[$i]}'") ; $newbroadcast = ( $iaddr | ~ $netmask ) ; ${LBR_ARR[$i]}=inet_ntoa($newbroadcast) ; print $NEW_LBR')
                        fi
                fi
            else
                LBR_ARR[$i]=$NEW_LBR
            fi

# Use DHCP
    elif [[ ! -z $NEW_LDHCP ]] ; then
	echo "Auto configuration - Using DHCP do configure ${IPOIB_UD[$i]}"
	dhcp_config $i ${ACTIVE_ARR[$i]}
	exit 0
    else
        exec 2>/dev/tty
	usage
        exec 2>/dev/null
	
   fi
   exec 2>/dev/tty
    if [[ -z $NEW_LMTU ]] ; then
    	if [[ $OS == "Darwin" ]]; then
		LMTU=1500
	else
		LMTU_ARR[$i]=$(rep-get interfaces/ipoib-ud mtu$i | perl -ne 'print hex')
		if [[ -z ${LMTU_ARR[$i]} ]] ; then
			LMTU_ARR[$i]=1500
			echo "MTU not configured, using default : 1500"
		fi
	fi
    else
	LMTU_ARR[$i]=$NEW_LMTU
    fi
    
    exec 2>/dev/null
    
    if [[ `ifconfig | grep ${IPOIB_UD[$i]}` ]]; then
    	ifdown  ${IPOIB_UD[$i]}  2>&1 1>/dev/null
    fi

    # remove DHCP configuration files 
    dhcp_remove $i
    ipoib_static_set ${LIP_ARR[$i]} ${LNM_ARR[$i]} ${LBR_ARR[$i]} ${LMTU_ARR[$i]} $i

   echo "Auto configuration is done on $HOSTNAME using IP ${LIP_ARR[$i]} Netmask ${LNM_ARR[$i]} Broadcast ${LBR_ARR[$i]} Mtu ${LMTU_ARR[$i]}"
   exec 2>/dev/null
    
    # update current ipoib-ud configuration
    if [[ ${ACTIVE_ARR[$i]} -eq 1 ]]; then
    	ifup  ${IPOIB_UD[$i]} 2>&1 1>/dev/null 
    fi
    #ifconfig ${IPOIB_UD} $LIP netmask $LNM broadcast $LBR mtu $LMTU
   
    if [[ $OS == "Darwin" ]]; then 
    	# update /usr/voltaire/config/repository.rps file
    	rep-set interfaces/ipoib-ud mtu$i $(printf "0x%08x" ${LMTU})
    	# update in-memory-repository.
    	rep_mset voltaire/interfaces/ipoib-ud/ mtu$i $(printf "0x%08x" ${LMTU})
    else
	rep-set interfaces/ipoib-ud mtu$i $(printf "0x%08x" ${LMTU_ARR[$i]})
        rep-set interfaces/ipoib-ud active$i $(printf "0x%08x" ${ACTIVE_ARR[$i]})
        # update in-memory-repository.
        rep_mset voltaire/interfaces/ipoib-ud/ mtu$i $(printf "0x%08x" ${LMTU_ARR[$i]})
        rep_mset voltaire/interfaces/ipoib-ud/ active$i $(printf "0x%08x" ${ACTIVE_ARR[$i]})
    fi
    exec 2>/dev/tty
    exit 0
}

interface_restart()
{
    i=$1

    #This is from ipoib_config_auto
    if [[ $2 -eq 1 ]]; then
    	ACTIVE_ARR[$i]=1
    elif [[$2 -eq 2 ]]; then
    	ACTIVE_ARR[$i]=0
    #This is from ipoib_config
    else  
	OLDACTIVE= $(rep-get interfaces/ipoib-ud active$i | perl -ne 'print hex')
    	if [[ $OLDACTIVE -eq 1 ]]; then
    		echo "This interface is active"
    	else
        	echo "This interface is disable"
    	fi
    	echo "Do you want this interface to be active ? (y/n)"
    	read ans
    	if [[  "$ans" = y* ]]; then
		ACTIVE_ARR[$i]=1
    	else
       	 	ACTIVE_ARR[$i]=0
    	fi
    fi
    rep-set interfaces/ipoib-ud active$i $(printf "0x%08x" ${ACTIVE_ARR[$i]})
    rep_mset voltaire/interfaces/ipoib-ud/ active$i $(printf "0x%08x" ${ACTIVE_ARR[$i]})

    if [[ ${ACTIVE_ARR[$i]} -eq 0 ]]; then
	if [[ `ifconfig | grep ${IPOIB_UD[$i]}` ]]; then
    		ifdown ${IPOIB_UD[$i]} 2>&1 1>/dev/null 
	fi
    else
    	if [ ${ACTIVE_ARR[$i]} -eq 1 ]; then
        	#echo "Would you like to restart the network interface ${IPOIB_UD[$i]} now?  (y/n)"
        	#read a
		a=yes
        	if [[ "$a" = y* ]]; then
			if [[ `ifconfig | grep ${IPOIB_UD[$i]}` ]]; then
           			ifdown ${IPOIB_UD[$i]} 2>&1 1>/dev/null
			fi
           		(ifup  ${IPOIB_UD[$i]} 2>&1 1>/dev/null  &)
        	fi
    	fi
    fi
}

dhcp_config(){
	i=$1
	exec 2>/dev/null
       #copy the relevant file(s)
       case "${LIN_DIST}" in
	   rhas21|rh90|rh80|rh73|rhas3|rhas4|rhes4)
	   \rm /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}

	   echo "DEVICE=${IPOIB_UD[$i]}" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	   if [[ ${ACTIVE_ARR[$i]} -eq 1 ]]; then
	   	echo "ONBOOT=yes" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	   else
	   	echo "ONBOOT=no" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	   fi
	   echo "BOOTPROTO=dhcp" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	   echo "DHCPCDARGS=\"-t 10 -B\"" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	   echo "PUMPARGS="--config-file=/usr/voltaire/config/volt-pump.conf"" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	  # \cp /usr/voltaire/config/ifcfg-${IPOIB_UD[$i]}.RH /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
           interface_restart $i $2
	   ;;
	   sles80|sl80|sl81|sul10|suse9|suse9.1|sles9|suse92|suse93)
	   \rm /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]} 
	   \cp /usr/voltaire/config/ifcfg-${IPOIB_UD[$i]}.SuSE /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]}
           interface_restart $i $2
	   ;;
           Darwin)
	   echo "DHCP configuration not supported yet"
           ;;
	   *) echo -n "Unsupported distribution ... ${LIN_DIST}"
	   ;;
       esac

       rep_mset voltaire/interfaces/ipoib-ud/ dhcp_mode_on$i $(printf "0x%08x" ${DHCP_ON})
       rep-set  interfaces/ipoib-ud dhcp_mode_on$i $(printf "0x%08x" ${DHCP_ON})
       exec 2>/dev/tty

       return
}

ipoib_static_set()
{	
	i=$5
        exec 2>/dev/null
       #copy the relevant file(s)
       case "${LIN_DIST}" in
           rhas21|rh90|rh80|rh73|rhas3|rhas4|rhes4)
           \rm /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
          # \cp /usr/voltaire/config/ifcfg-ipoib0.static.RH /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
		
  	   echo "DEVICE=${IPOIB_UD[$i]}" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	   if [[ ${ACTIVE_ARR[$i]} -eq 1 ]]; then
	   	echo "ONBOOT=yes" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	   else
	   	echo "ONBOOT=no" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	   fi
	   echo "BOOTPROTO=static" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
           echo "IPADDR=$1" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
           echo "NETMASK=$2" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
           echo "BROADCAST=$3" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
           echo "MTU=$4" >> /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
           ;;
           sles80|sl80|sl81|sul10|suse9|suse9.1|sles9|suse92|suse93)
           \rm /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]}
           \cp /usr/voltaire/config/ifcfg-ipoib0.static.SuSE /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]}
	   echo 
           echo "IPADDR=$1" >> /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]}
           echo "NETMASK=$2" >> /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]}
           echo "BROADCAST=$3" >> /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]}
           echo "MTU=$4" >> /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]}
           ;;
	   Darwin)
	   ;;
           *) echo -n "Unsupported distribution ..."
           ;;
       esac

       if [ $KEEP_IP_IN_REPOSITORY == "yes" ]; then
           # update /usr/voltaire/config/repository.rps file
           rep-set interfaces/ipoib-ud ip-addr$i "$1"
           rep-set interfaces/ipoib-ud net-mask$i "$2"
           rep-set interfaces/ipoib-ud broadcast1$i "$3"
           rep-set interfaces/ipoib-ud mtu$i $(printf "0x%08x" ${4})
           # update in-memory-repository.
           rep_mset voltaire/interfaces/ipoib-ud/ ip-addr$i "\"$1\""
           rep_mset voltaire/interfaces/ipoib-ud/ net-mask$i "\"$2\""
           rep_mset voltaire/interfaces/ipoib-ud/ broadcast$i "\"$3\""
           rep_mset voltaire/interfaces/ipoib-ud/ mtu$i $(printf "0x%08x" ${4})
       fi

       exec 2>/dev/tty

       return

}

dhcp_remove(){
	i=$1
	exec 2>/dev/null
       #delete the DHCP file(s) if present.
       case $LIN_DIST in
	   rhas21 | rh90 | rh80 | rh73 | rhas3 | rhas4 |rhes4)
	   \rm /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
	   ;;
	   sles80 | sl80 | sl81 | sul10 | suse9 | suse9.1 | sles9 | suse92 | suse93)
	   \rm /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]} 
	   ;;
           Darwin)
           ;;
	   *) echo -n "Unsupported distribution ..."
	   ;;
       esac
    
       rep_mset voltaire/interfaces/ipoib-ud/ dhcp_mode_on$i $(printf "0x%08x" ${DHCP_OFF})
       rep-set  interfaces/ipoib-ud dhcp_mode_on$i $(printf "0x%08x" ${DHCP_OFF})
       exec 2>/dev/tty

}

ipoib_get_if_data_from_repository() 
{
    i=$5

    if [[ ${LIN_DIST} == Darwin ]]; then
    	LOC_IP=$(rep-get interfaces/ipoib-ud ip-addr1 )
    	LOC_NM=$(rep-get interfaces/ipoib-ud net-mask1)
    	LOC_BROADCAST=$(rep-get interfaces/ipoib-ud broadcast1)
    	LOC_MTU=$(rep-get interfaces/ipoib-ud mtu | perl -ne 'print hex')
    else
	LOC_IP=$(rep-get interfaces/ipoib-ud ip-addr$i )
	LOC_NM=$(rep-get interfaces/ipoib-ud net-mask$i )
        LOC_BROADCAST=$(rep-get interfaces/ipoib-ud broadcast$i )
        LOC_MTU=$(rep-get interfaces/ipoib-ud mtu$i | perl -ne 'print hex')
    fi

    eval "$1=\"$LOC_IP\""
    eval "$2=\"$LOC_NM\""
    eval "$3=\"$LOC_BROADCAST\""
    eval "$4=\"$LOC_MTU\""
}

ipoib_get_if_data()
{
  i=$5
  if [[ ${DHCP_MODE_ARR[$i]} = 0 ]]; then
         case "${LIN_DIST}" in
         rhas21|rh90|rh80|rh73|rhas3|rhas4|rhes4)
              if [ -e /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]} ]; then
              		LOC_IP=$(awk -F"=" '/IPADDR=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]})
                        LOC_NM=$(awk -F"=" '/NETMASK=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]})
                        LOC_BROADCAST=$(awk -F"=" '/BROADCAST=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]})
                        LOC_MTU=$(awk -F"=" '/MTU=[0-9]+/ { print $2}' /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]})
               fi
               ;;
          sles80|sl80|sl81|sul10|suse9|suse9.1|sles9|suse92|suse93)
               if [  -e /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]} ]; then
               		LOC_IP=$(awk -F"=" '/IPADDR=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]})
                        LOC_NM=$(awk -F"=" '/NETMASK=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]})
                        LOC_BROADCAST=$(awk -F"=" '/BROADCAST=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]})
                        LOC_MTU=$(awk -F"=" '/MTU=[0-9]+/ { print $2}' /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]})
               fi
                                                                                                                            
                ;;
            Darwin)
                LOC_IP=$(ifconfig eth0 |awk '/inet addr/ {print $2}' |awk -F":" '/[0-9]+\.[0-9]*/ { print $2}')
                #FIX ME
                LOC_NM=$(ifconfig eth0 |awk '/inet addr/ {print $2}' |awk -F":" '/[0-9]+\.[0-9]*/ { print $2}')
                LOC_BROADCAST=$(ifconfig eth0 |awk '/inet addr/ {print $2}' |awk -F":" '/[0-9]+\.[0-9]*/ { print $2}')
                LOC_MTU=$(ifconfig eth0 |awk '/inet addr/ {print $2}' |awk -F":" '/[0-9]+\.[0-9]*/ { print $2}')
                #END OF FIX ME
                ;;
                *) echo -n "Unsupported distribution ... ${LIN_DIST}"
                ;;
           esac
  else  #DHCP MODE on
                if [ $KEEP_IP_IN_REPOSITORY == "yes" ]; then
                        ipoib_get_if_data_from_repository LOC_IP LOC_NM LOC_BROADCAST LOC_MTU $i
                else
                        LOC_IP=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/inet addr:\s*(\S+)/i')
                        LOC_NM=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/mask:\s*(\S+)/i')
                        LOC_BROADCAST=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/bcast:\s*(\S+)/i')
                        LOC_MTU=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/MTU:\s*(\S+)/i')
                fi
        fi
                                                                                                                            
    eval "$1=\"$LOC_IP\""
    eval "$2=\"$LOC_NM\""
    eval "$3=\"$LOC_BROADCAST\""
    eval "$4=\"$LOC_MTU\""
    return 0
}



ipoib_get_if_data_all()
{
    for ((i=0;i<64;i++))
    do
	if [[ ${IPOIB_UD[$i]} == ipoib$i ]]; then
    		if [[ ${DHCP_MODE_ARR[$i]} = 0 ]]; then
			case "${LIN_DIST}" in
            		rhas21|rh90|rh80|rh73|rhas3|rhas4|rhes4)
                		if [ -e /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]} ]; then
                    			LIP_ARR[$i]=$(awk -F"=" '/IPADDR=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]})
                    			LNM_ARR[$i]=$(awk -F"=" '/NETMASK=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]})
                    			LBR_ARR[$i]=$(awk -F"=" '/BROADCAST=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]})
                    			LMTU_ARR[$i]=$(awk -F"=" '/MTU=[0-9]+/ { print $2}' /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]})
                		fi
            			;;
                 	sles80|sl80|sl81|sul10|suse9|suse9.1|sles9|suse92|suse93)
                		if [  -e /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]} ]; then
                    			LIP_ARR[$i]=$(awk -F"=" '/IPADDR=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]})
                    			LNM_ARR[$i]=$(awk -F"=" '/NETMASK=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]})
                    			LBR_ARR[$i]=$(awk -F"=" '/BROADCAST=[0-9]+\.[0-9]*/ { print $2}' /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]})
                    			LMTU_ARR[$i]=$(awk -F"=" '/MTU=[0-9]+/ { print $2}' /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]})
                		fi
	    
            			;;
            		Darwin)
                		LOC_IP=$(ifconfig eth0 |awk '/inet addr/ {print $2}' |awk -F":" '/[0-9]+\.[0-9]*/ { print $2}')	
                		#FIX ME
                		LOC_NM=$(ifconfig eth0 |awk '/inet addr/ {print $2}' |awk -F":" '/[0-9]+\.[0-9]*/ { print $2}')
                		LOC_BROADCAST=$(ifconfig eth0 |awk '/inet addr/ {print $2}' |awk -F":" '/[0-9]+\.[0-9]*/ { print $2}')
                		LOC_MTU=$(ifconfig eth0 |awk '/inet addr/ {print $2}' |awk -F":" '/[0-9]+\.[0-9]*/ { print $2}')
                		#END OF FIX ME
                		;;
                	*) echo -n "Unsupported distribution ... ${LIN_DIST}"
                		;;
            		esac
    		else  #DHCP MODE on
			if [ $KEEP_IP_IN_REPOSITORY == "yes" ]; then
				if [[ ${LIN_DIST} == "Darwin" ]]; then
            				ipoib_get_if_data_from_repository LOC_IP LOC_NM LOC_BROADCAST LOC_MTU $i
				else
					ipoib_get_if_data_from_repository LIP_ARR[$i] LNM_ARR[$i] LBR_ARR[$i] LMTU_ARR[$i] $i
				fi
        		else
            			LIP_ARR[$i]=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/inet addr:\s*(\S+)/i')
            			LNM_ARR[$i]=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/mask:\s*(\S+)/i')
            			LBR_ARR[$i]=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/bcast:\s*(\S+)/i')
            			LMTU_ARR[$i]=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/MTU:\s*(\S+)/i')
	   		fi
		fi
	fi
    done
       
    eval "$1=\"$LOC_IP\""  
    eval "$2=\"$LOC_NM\""  
    eval "$3=\"$LOC_BROADCAST\""  
    eval "$4=\"$LOC_MTU\""  
    return 0
}

ipoib_config()
{
	if [[ ! $1 ]]; then
		echo Please enter ipoib device number you want to configure
    		read ans
		if [[ ${IPOIB_UD[$ans]} == "" ]]; then
			echo You trying to configure not existing interface
			echo If you want to add interface use Partitioning menu from ib-setup
			sleep 2
			return
    		else
			i=$ans
		fi
	else
		i=$1
	fi
    	
    	echo You are now configuring  ${IPOIB_UD[$i]} 
	
	OLDLIP=""
	OLDLNM=""
	OLDLBR=""
	OLDLMTU=1500

	if [[ ! $1 ]]; then
    		ipoib_get_if_data OLDLIP OLDLNM OLDLBR OLDLMTU $i
	fi

    	LIP_ARR[$i]=""
    	LNM_ARR[$i]=""
    	LBR_ARR[$i]=""
    	ACTIVE_ARR[$i]=""
    	DHCP_MODE_ARR[$i]=$(rep-get interfaces/ipoib-ud dhcp_mode_on$i | perl -ne 'print hex')
	if [[ DHCP_MODE_ARR[$i]=="" ]]; then
		DHCP_MODE_ARR[$i]=0
	fi
		
    	case "${OS}" in
    		Darwin)
            		DHCP_MODE=0
        		;;
            	*)
            		LIN_DIST=$(ibhost-linux-dist-name)
            		echo -n "Please enter DHCP mode for  ${IPOIB_UD[$i]} [1=on 0=off] [${DHCP_MODE_ARR[$i]}]: "
            		read ans
            		if [ ! -z "$ans" ]; then
               			DHCP_MODE_ARR[$i]="$ans"
            		fi
            		if [[ ${DHCP_MODE_ARR[$i]} = 1 ]]; then
        			dhcp_config $i
        			return
            		fi
         		;;
    		esac

    if [[ $KEEP_IP_IN_REPOSITORY == "yes" ]]; then
	if [[ ! $1 ]]; then
        	ipoib_get_if_data_from_repository OLDLIP OLDLNM OLDLBR OLDLMTU $i
		OLDACTIVE=$(rep-get interfaces/ipoib-ud active$i | perl -ne 'print hex')
	fi
    else
    	 if ifconfig ${IPOIB_UD[$i]} 2>/dev/null | grep error; then 
	        OLDACTIVE=1
	 else
	   	OLDACTIVE=0
	 fi
    fi

    while [ -z "${LIP_ARR[$i]}" ]
    do
    	echo -n "Please enter IP address for ${IPOIB_UD[$i]} [$OLDLIP]: "
    	read ans
    	if [ ! -z "$ans" ]; then
       		LIP_ARR[$i]="$ans"
    	else
       		LIP_ARR[$i]="$OLDLIP"
    	fi
    
    	if ! verify_ip "${LIP_ARR[$i]}"  ; then
		echo "Please enter valid IP address."
		LIP_ARR[$i]=""
	fi
    done

    while  [ -z "${LNM_ARR[$i]}" ]
    do

	if [ -e /bin/ipcalc ]; then                        
		LNM_ARR[$i]=$(/bin/ipcalc -m ${LIP_ARR[$i]} | awk -F= '/NETMASK/{print $2}')
	fi

	if [[ -z $OLDLNM ]]; then
		OLDLNM=${LNM_ARR[$i]}
	fi
        echo -n "Please enter network mask for ${IPOIB_UD[$i]} [${OLDLNM}]: "
        read ans
        if [ ! -z "$ans" ]; then
           LNM_ARR[$i]="$ans"
	else
	   LNM_ARR[$i]=${OLDLNM}
        fi
        if ! verify_ip "${LNM_ARR[$i]}" ; then
            echo "Please enter valid network mask."
            LNM_ARR[$i]=""
        fi
    done


    while  [ -z "${LBR_ARR[$i]}" ]
    do
        if [ -e /bin/ipcalc ]; then
           LBR_ARR[$i]=$(/bin/ipcalc -b ${LIP_ARR[$i]} ${LNM_ARR[$i]} | awk -F= '/BROADCAST/{print $2}')
        fi

	if [[ -z $OLDLBR ]]; then
		OLDLBR=${LBR_ARR[$i]}
        fi

        # echo "IP: $LIP  NM: $LNM BR: $LBR"
        echo -n "Please enter broadcast address for ${IPOIB_UD[$i]} [${OLDLBR}]: "
        read ans
        if [ ! -z "$ans" ]; then
           LBR_ARR[$i]="$ans"
	else
	   LBR_ARR[$i]=${OLDLBR}
        fi
        if ! verify_ip "${LBR_ARR[$i]}" ; then
            echo "Please enter valid broadcast address."
            LBR_ARR[$i]=""
        fi
    done

    if [  -z "$OLDLMTU" ]; then
        OLDLMTU=1500
    fi
    OK_MTU='no'

    while [ $OK_MTU == 'no' ]
    do
        echo "Please enter network MTU for ${IPOIB_UD[$i]}"
        echo -n "   (MTU must be in range from $MIN_MTU to $MTU_LIMIT bytes) [$OLDLMTU]: "
        read ans
        if [ ! -z "$ans" ]; then
           LMTU_ARR[$i]="$ans"
        else
           LMTU_ARR[$i]=$OLDLMTU
        fi
        if [[ (${LMTU_ARR[$i]} -le $MTU_LIMIT) && (${LMTU_ARR[$i]} -ge $MIN_MTU) ]]
        then
            OK_MTU='yes'
        fi
    done

    if [[ $OLDACTIVE -eq 1 ]]; then
   	 echo "This interface is active"
    else 
    	echo "This interface is disabled"
    fi	 
    echo "Do you want this interface to be active ? (y/n)"
    read ans
    if [[  "$ans" = y* ]]; then
    	ACTIVE_ARR[$i]=1
    else
    	ACTIVE_ARR[$i]=0
    fi
    
    rep-set interfaces/ipoib-ud active$i $(printf "0x%08x" ${ACTIVE_ARR[$i]})
    rep_mset voltaire/interfaces/ipoib-ud/ active$i $(printf "0x%08x" ${ACTIVE_ARR[$i]})
    
    # echo "IP: $LIP  NM: $LNM BR: $LBR"
    # update current ipoib-ud configuration

    exec 2>/dev/null
    
    if [[ `ifconfig | grep ${IPOIB_UD[$i]}` ]]; then
    	ifdown ${IPOIB_UD[$i]} 2>&1 1>/dev/null
    fi

    dhcp_remove $i
    ipoib_static_set ${LIP_ARR[$i]} ${LNM_ARR[$i]} ${LBR_ARR[$i]} ${LMTU_ARR[$i]} $i
    exec 2>/dev/tty

    if [ ${ACTIVE_ARR[$i]} -eq 1 ]; then
	if [[ `ifconfig | grep ${IPOIB_UD[$i]}` ]]; then
        	ifdown ${IPOIB_UD[$i]} 2>&1 1>/dev/null 
	fi
        ifup  ${IPOIB_UD[$i]}  2>&1 1>/dev/null
    fi  
}

partitioning_menu()
{
	select c in Delete_interface Add_interface Exit
	do
		case $c in
		Delete_interface)
			delete_interface 1
			break
			;;
		Add_interface)
			add_interface 1
			break
			;;
		Exit)
			return;
			break
			;;		    
		*)
		     	echo "Choose a number from the above range."
			break
			;;
		esac
	done
}

get_hca_id(){
	for ((s=0;s<3;s++)); do
		hca_id=$(vstat|grep hca_id|cut -f2 -d=)
		if [ -z $hca_id ] ; then
			sleep 1
		else
			break
		fi
	done
}
add_interface()
{
	for(( i=0;i<64;i++ ))
	do
		if [[ ${IPOIB_UD[$i]} == "" ]]; then
			break
		fi
	done
	#Function was called from ib-setup
	if [[ $1 -eq 1 ]]; then
		echo In order to add additional ipoib interface, enter pkey number
		read ans
		if [[ -z "$ans" ]]; then
			echo You should enter pkey '(decimal number)'
			sleep 2
			return
		else
	   		pkey=$ans
		fi
	#Function was called from CLI
	else	
		pkey=$2
	fi
	if [ -e /proc/voltaire/ipoib-ud/control ] ; then
		get_hca_id
		if [  -z $hca_id ] ; then
			echo  HCA ID is unknown. not configuring ipoib.
		else
			echo 'add_r '$hca_id' '$pkey' '$i'' > /proc/voltaire/ipoib-ud/control
		fi
	else
		echo  stack is  down. delaying configuration of IPoIB to stack restart.
	fi
	
	rep-set interfaces/ipoib-ud pkey$i $(printf "0x%08x" $pkey)
	rep_mset voltaire/interfaces/ipoib-ud/ pkey$i $(printf "0x%08x" $pkey)
	
	echo "You added interface ipoib$i"

	IPOIB_UD[$i]=ipoib$i
	if [[ $1 -eq 1 ]]; then
		ipoib_config $i
	elif [[ ! -z $3 ]]; then
		option--config --interface ipoib$i $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12}  
	else
		exit
	fi 
}	

delete_interface()
{
	#Function was called from ib-setup
	if [[ $1 -eq 1 ]]; then
		echo "Please enter the number of interface you want to delete"
		read i
	#Function was called from CLI
	else
		i=$2
	fi

	for(( j=0;j<64;j++ ))
        do
                if [[ ${IPOIB_UD[$j]} == "ipoib"$i ]]; then
                        break
                fi
        done
	
	if [[ $j -eq 64 ]]; then
		echo "You are trying to delete interface that doesn't exist"
		sleep 2
		if [[ $1 -eq 1 ]]; then
			return
		else
			exit
		fi
	fi

	pkey=$(rep-get interfaces/ipoib-ud pkey$i | perl -ne 'print hex')
	if [[ $pkey -eq 0 ]]; then
		echo "You are trying to delete interface that doesn't exist"
		sleep 2
		if [[ $1 -eq 1 ]]; then
			return
		else
			exit
		fi
	fi

	if [[ `ifconfig | grep ${IPOIB_UD[$i]}` ]]; then	
		ifdown ${IPOIB_UD[$i]} 2>&1 1>/dev/null 
	fi

	echo "del ${IPOIB_UD[$i]}" > /proc/voltaire/ipoib-ud/control

	case "${LIN_DIST}" in 
	rhas21|rh90|rh80|rh73|rhas3|rhas4|rhes4)
		if [[ -e /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]} ]]; then
           	\rm /etc/sysconfig/network-scripts/ifcfg-${IPOIB_UD[$i]}
		fi
		;;
	sles80|sl80|sl81|sul10|suse9|suse9.1|sles9|suse92|suse93)
		if [[ -e /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]} ]]; then
           	\rm /etc/sysconfig/network/ifcfg-${IPOIB_UD[$i]}
		fi
		;;
	*) echo -n "Unsupported distribution ... ${LIN_DIST}"
	   sleep 2
	   return
           ;;
      	 esac
   
	 rep-set interfaces/ipoib-ud pkey$i $(printf "0x%08x" 0)
         rep_mset voltaire/interfaces/ipoib-ud/ pkey$i $(printf "0x%08x" 0)
	 rep-set interfaces/ipoib-ud active$i $(printf "0x%08x" 0)
	 rep_mset voltaire/interfaces/ipoib-ud/ active$i $(printf "0x%08x" 0)
	 rep-set interfaces/ipoib-ud dhcp_mode_on$i 0
	 rep_mset voltaire/interfaces/ipoib-ud/ dhcp_mode_on$i 0

	 IPOIB_UD[$i]=""
         	 	
	 echo "Please note: this changes will be valid only on the next IB restart"
	 if [[ $1 -eq 1 ]]; then
	 	echo "Do you want to restart the stack ? (y/n)"
	 	read ans  
	 	if [[ "$ans" == y* ]]; then
			echo Please wait while restarting the ib stack ....
			ibhost.init restart
	 	fi
	 	sleep 1
	else
		exit
	fi
}
							    
ibsm_config(){
    IBSMENABLE=$(rep-get modules/subnet-manager enabled | perl -ne 'print hex')
    IBSMINTERVAL=$(rep-get modules/subnet-manager interval | perl -ne 'print hex')

    SMF=""
    echo "Would you like to enable the IB-Subnet-Manager on this IB-Host ?"
    echo -n "Note: only one host should run SM, (y/n): "
    read A
    if [[ "$A" = y* ]]; then
        SMF=1
    else
        SMF=0
    fi
    rep-set modules/subnet-manager enabled "0x00000$SMF"
    exec 2>/dev/null
    rep_mset voltaire/modules/subnet-manager/ enabled $(printf "0x%08x" ${SMF})
    exec 2>/dev/tty

    if [ $SMF -eq 1 ]; then
        echo "Note: Zero scanning interval - scan only once at system startup."
        echo -n "IB scanning interval [${IBSMINTERVAL}]: "
        read ans ; if [ ! -z "$ans" ]; then IBSMINTERVAL="$ans" ; fi
        rep-set modules/subnet-manager interval $(printf "0x%08x" ${IBSMINTERVAL})
        exec 2>/dev/null
        rep_mset voltaire/modules/subnet-manager/ interval $(printf "0x%08x" ${IBSMINTERVAL})
        exec 2>/dev/tty
    fi
}

autostart_config(){
    echo "Would you like to enable IB stack, on system startup?"
    echo -n "(y/n): "
    read a

    case "${LIN_DIST}" in
           rhas21|rh90|rh80|rh73|rhas3|rhas4|rhes4)
       if [[ "$a" = n* ]]; then
           chkconfig --del voltaireibhost >/dev/null 2>&1
       else
           chkconfig --del voltaireibhost >/dev/null 2>&1
           chkconfig --level 2345 voltaireibhost on
           chkconfig --level 016 voltaireibhost off
       fi
    ;;
    sles80|sl80|sl81|sul10|suse9|suse9.1|sles9|suse92|suse93)
       if [[ "$a" = n* ]]; then
          chkconfig  voltaireibhost  off>/dev/null 2>&1
       else
          chkconfig  voltaireibhost  off >/dev/null 2>&1
          chkconfig  voltaireibhost 2345
       fi
    ;;
    Darwin)
       cd /usr/voltaire/scripts
       if [[ "$a" = n* ]]; then
           ln -snf ibhost.dummy.init ibhost.apple.auto.init
       else
           ln -snf ibhost.apple.init ibhost.apple.auto.init
       fi
       return
    ;;
    *) echo -n "Unsupported distribution ..."
    ;;
    esac
}

# -------------- SDP Setup.
sdp_setup(){

    echo "SDP setup"
    echo
    # -- Read variable
    # Read SDP Variables
    SDP_BUF_SIZE=$(rep-get modules/sdp buf_size | perl -ne 'print hex')
    SDP_BUF_NUMBER=$(rep-get modules/sdp buf_number | perl -ne 'print hex')
    SDP_RCV_LIST_SIZE=$(rep-get modules/sdp rcv_list_size | perl -ne 'print hex')
    SDP_RDMA_TRESHOLD=$(rep-get modules/sdp rdma_treshold)
    SDP_UPD_CRDT_LOW=$(rep-get modules/sdp update_credit_low | perl -ne 'print hex')
    SDP_UPD_CRDT_HIGH=$(rep-get modules/sdp update_credit_high | perl -ne 'print hex')
    SDP_SIGNALLING_TH=$(rep-get modules/sdp signalling_th | perl -ne 'print hex')
    SDP_SOCK_SEND_LIMIT=$(rep-get modules/sdp-sockets send_limit | perl -ne 'print hex')
    SDP_SOCK_FIXED_SIZE=$(rep-get modules/sdp-sockets fixed_size | perl -ne 'print hex')
    # Read Q-MNG Variables
    QMNG_CQ_SIZE=$(rep-get modules/q-mng cq_size | perl -ne 'print hex')
    QMNG_QP_SEND_SIZE=$(rep-get modules/q-mng send_qp_size | perl -ne 'print hex')
    QMNG_QP_RECV_SIZE=$(rep-get modules/q-mng recv_qp_size | perl -ne 'print hex')
    QMNG_CQ_NUMBER=$(rep-get modules/q-mng cq_number | perl -ne 'print hex')
    QMNG_QPS_PER_CQ=$(rep-get modules/q-mng qp_per_cq | perl -ne 'print hex')

    # Read FMR variables
    FMR_UNMAP_AT_ONCE=$(rep-get modules/sdp fmr_unmap_at_once  | perl -ne 'print hex') 
    FMR_AVG_RECV_SIZE=$(rep-get modules/sdp avg_recv_size   | perl -ne 'print hex')
    FMR_AVG_RECV_SIZE_PERCENT=$(rep-get modules/sdp avg_recv_size_percent  | perl -ne 'print hex')
    FMR_NUM_OF_HNDLS=$(rep-get modules/sdp num_of_fmr_hndls | perl -ne 'print hex')
    FMR_WATERMARK=$(rep-get modules/sdp fmr_water_mark  | perl -ne 'print hex')
    FMR_ACTIVE=$(rep-get modules/sdp active_fmr  | perl -ne 'print hex')

    for v in SDP_BUF_SIZE SDP_BUF_NUMBER SDP_RCV_LIST_SIZE SDP_RDMA_TRESHOLD SDP_UPD_CRDT_LOW SDP_UPD_CRDT_HIGH SDP_SIGNALLING_TH SDP_SOCK_SEND_LIMIT SDP_SOCK_FIXED_SIZE QMNG_CQ_SIZE QMNG_QP_SEND_SIZE QMNG_QP_RECV_SIZE QMNG_CQ_NUMBER QMNG_QPS_PER_CQ FMR_ACTIVE FMR_UNMAP_AT_ONCE FMR_AVG_RECV_SIZE FMR_AVG_RECV_SIZE_PERCENT FMR_NUM_OF_HNDLS FMR_WATERMARK ; do printf '%-22s %s\n' $v: $(eval echo \$$v) ;done
    # -- User Update Veriables

    echo -n "SDP Buffer size [${SDP_BUF_SIZE}]: "
    read ans ; if [ ! -z "$ans" ]; then SDP_BUF_SIZE="$ans" ; fi
    echo -n "SDP Buffer number [${SDP_BUF_NUMBER}]: "
    read ans ; if [ ! -z "$ans" ]; then SDP_BUF_NUMBER="$ans" ; fi
    echo -n "SDP Receive list size [${SDP_RCV_LIST_SIZE}]: "
    read ans ; if [ ! -z "$ans" ]; then SDP_RCV_LIST_SIZE="$ans" ; fi
    echo -n "SDP RDMA threshold [${SDP_RDMA_TRESHOLD}]: "
    read ans ; if [ ! -z "$ans" ]; then SDP_RDMA_TRESHOLD="$ans" ; fi
    echo -n "SDP Update credit low [${SDP_UPD_CRDT_LOW}]: "
    read ans ; if [ ! -z "$ans" ]; then SDP_UPD_CRDT_LOW="$ans" ; fi
    echo -n "SDP Update credit high [${SDP_UPD_CRDT_HIGH}]: "
    read ans ; if [ ! -z "$ans" ]; then SDP_UPD_CRDT_HIGH="$ans" ; fi
    echo -n "SDP Signalling threshold: use 0 to disable siganlling [${SDP_SIGNALLING_TH}]: "
    read ans ; if [ ! -z "$ans" ]; then SDP_SIGNALLING_TH="$ans" ; fi
    echo -n "SDP socket send limit [${SDP_SOCK_SEND_LIMIT}]: "
    read ans ; if [ ! -z "$ans" ]; then SDP_SOCK_SEND_LIMIT="$ans" ; fi
    echo -n "SDP socket send buf size: 1 - fixed size, 0 - Application controlled [${SDP_SOCK_FIXED_SIZE}]: "
    read ans ; if [ ! -z "$ans" ]; then SDP_SOCK_FIXED_SIZE="$ans" ; fi

    #FMR variables
    echo -n "FMR unmap at once [${FMR_UNMAP_AT_ONCE}]: "
    read ans ; if [ ! -z "$ans" ]; then FMR_UNMAP_AT_ONCE="$ans" ; fi

    echo "Please note: the following changes are valid only on the next IB restart."

    echo -n "QP send size [${QMNG_QP_SEND_SIZE}]: "
    read ans ; if [ ! -z "$ans" ]; then QMNG_QP_SEND_SIZE="$ans" ; fi
    echo -n "QP recive size [${QMNG_QP_RECV_SIZE}]: "
    read ans ; if [ ! -z "$ans" ]; then QMNG_QP_RECV_SIZE="$ans" ; fi
    echo -n "CQ size [${QMNG_CQ_SIZE}]: "
    read ans ; if [ ! -z "$ans" ]; then QMNG_CQ_SIZE="$ans" ; fi
    echo -n "CQ number [${QMNG_CQ_NUMBER}]: "
    read ans ; if [ ! -z "$ans" ]; then QMNG_CQ_NUMBER="$ans" ; fi
    echo -n "QP per CQ [${QMNG_QPS_PER_CQ}]: "
    read ans ; if [ ! -z "$ans" ]; then QMNG_QPS_PER_CQ="$ans" ; fi

    #FMR variables
    echo -n "FMR active  [${FMR_ACTIVE}]: "
    read ans ; if [ ! -z "$ans" ]; then FMR_ACTIVE="$ans" ; fi
    echo -n "FMR pool size  [${FMR_NUM_OF_HNDLS}]: "
    read ans ; if [ ! -z "$ans" ]; then FMR_NUM_OF_HNDLS="$ans" ; fi
    echo -n "FMR avg recv size  [${FMR_AVG_RECV_SIZE}]: "
    read ans ; if [ ! -z "$ans" ]; then FMR_AVG_RECV_SIZE="$ans" ; fi
    echo -n "FMR avg recv size percent   [${FMR_AVG_RECV_SIZE_PERCENT}]: "
    read ans ; if [ ! -z "$ans" ]; then FMR_AVG_RECV_SIZE_PERCENT="$ans" ; fi
    echo -n "FMR watermark   [${FMR_WATERMARK}]: "
    read ans ; if [ ! -z "$ans" ]; then FMR_WATERMARK="$ans" ; fi
    
    # -- User Update Veriables
 for v in SDP_BUF_SIZE SDP_BUF_NUMBER SDP_RCV_LIST_SIZE SDP_RDMA_TRESHOLD SDP_UPD_CRDT_LOW SDP_UPD_CRDT_HIGH SDP_SIGNALLING_TH SDP_SOCK_SEND_LIMIT SDP_SOCK_FIXED_SIZE QMNG_CQ_SIZE QMNG_QP_SEND_SIZE QMNG_QP_RECV_SIZE QMNG_CQ_NUMBER QMNG_QPS_PER_CQ FMR_ACTIVE FMR_UNMAP_AT_ONCE FMR_AVG_RECV_SIZE FMR_AVG_RECV_SIZE_PERCENT FMR_NUM_OF_HNDLS FMR_WATERMARK ; do printf '%-22s %s\n' $v: $(eval echo \$$v) ;done

    # -- Update repository.rps file
    #  SDP Variables
    rep-set modules/sdp buf_size $(printf "0x%08x" ${SDP_BUF_SIZE})
    rep-set modules/sdp buf_number $(printf "0x%08x" ${SDP_BUF_NUMBER})
    rep-set modules/sdp rcv_list_size $(printf "0x%08x" ${SDP_RCV_LIST_SIZE})
    rep-set modules/sdp rdma_treshold ${SDP_RDMA_TRESHOLD}
    rep-set modules/sdp update_credit_low $(printf "0x%08x" ${SDP_UPD_CRDT_LOW})
    rep-set modules/sdp update_credit_high $(printf "0x%08x" ${SDP_UPD_CRDT_HIGH})
    rep-set modules/sdp signalling_th  $(printf "0x%08x" ${SDP_SIGNALLING_TH})
    rep-set modules/sdp-sockets send_limit $(printf "0x%08x" ${SDP_SOCK_SEND_LIMIT})
    rep-set modules/sdp-sockets fixed_size $(printf "0x%08x" ${SDP_SOCK_FIXED_SIZE})
    # Q-MNG Variables
    rep-set modules/q-mng cq_size $(printf "0x%08x" ${QMNG_CQ_SIZE})
    rep-set modules/q-mng send_qp_size $(printf "0x%08x" ${QMNG_QP_SEND_SIZE})
    rep-set modules/q-mng recv_qp_size $(printf "0x%08x" ${QMNG_QP_RECV_SIZE})
    rep-set modules/q-mng cq_number $(printf "0x%08x" ${QMNG_CQ_NUMBER})
    rep-set modules/q-mng qp_per_cq $(printf "0x%08x" ${QMNG_QPS_PER_CQ})
  
    #FMR Variables
    rep-set modules/sdp active_fmr  $(printf "0x%08x" ${FMR_ACTIVE})
    rep-set modules/sdp fmr_unmap_at_once $(printf "0x%08x" ${FMR_UNMAP_AT_ONCE})
    rep-set modules/sdp avg_recv_size $(printf "0x%08x" ${FMR_AVG_RECV_SIZE})
    rep-set modules/sdp avg_recv_size_percent  $(printf "0x%08x" ${FMR_AVG_RECV_SIZE_PERCENT})
    rep-set modules/sdp num_of_fmr_hndls  $(printf "0x%08x" ${FMR_NUM_OF_HNDLS})
    rep-set modules/sdp fmr_water_mark $(printf "0x%08x" ${FMR_WATERMARK})


 

    exec 2>/dev/null

    # -- Update in-memory repository
    rep_mset voltaire/modules/sdp/ buf_size $(printf "0x%08x" ${SDP_BUF_SIZE})

    rep_mset voltaire/modules/sdp/ buf_number $(printf "0x%08x" ${SDP_BUF_NUMBER})
    rep_mset voltaire/modules/sdp/ rcv_list_size $(printf "0x%08x" ${SDP_RCV_LIST_SIZE})
    rep_mset voltaire/modules/sdp/ rdma_treshold ${SDP_RDMA_TRESHOLD}
    rep_mset voltaire/modules/sdp/ update_credit_low $(printf "0x%08x" ${SDP_UPD_CRDT_LOW})
    rep_mset voltaire/modules/sdp/ update_credit_high $(printf "0x%08x" ${SDP_UPD_CRDT_HIGH})
    rep_mset voltaire/modules/sdp/ signalling_th $(printf "0x%08x" ${SDP_SIGNALLING_TH})
    rep_mset voltaire/modules/sdp-sockets/ send_limit $(printf "0x%08x" ${SDP_SOCK_SEND_LIMIT})
    rep_mset voltaire/modules/sdp-sockets/ fixed_size $(printf "0x%08x" ${SDP_SOCK_FIXED_SIZE})

    rep_mset voltaire/modules/q-mng/ cq_size $(printf "0x%08x" ${QMNG_CQ_SIZE})
    rep_mset voltaire/modules/q-mng/ send_qp_size $(printf "0x%08x" ${QMNG_QP_SEND_SIZE})
    rep_mset voltaire/modules/q-mng/ recv_qp_size $(printf "0x%08x" ${QMNG_QP_RECV_SIZE})
    rep_mset voltaire/modules/q-mng/ cq_number $(printf "0x%08x" ${QMNG_CQ_NUMBER})
    rep_mset voltaire/modules/q-mng/ qp_per_cq $(printf "0x%08x" ${QMNG_QPS_PER_CQ})

   #FMR values
    rep_mset voltaire/modules/sdp/ active_fmr  $(printf "0x%08x" ${FMR_ACTIVE})
    rep_mset voltaire/modules/sdp/ fmr_unmap_at_once $(printf "0x%08x" ${FMR_UNMAP_AT_ONCE})
    rep_mset voltaire/modules/sdp/ avg_recv_size $(printf "0x%08x" ${FMR_AVG_RECV_SIZE})
    rep_mset voltaire/modules/sdp/ avg_recv_size_percent  $(printf "0x%08x" ${FMR_AVG_RECV_SIZE_PERCENT})
    rep_mset voltaire/modules/sdp/ num_of_fmr_hndls $(printf "0x%08x" ${FMR_NUM_OF_HNDLS})
    rep_mset voltaire/modules/sdp/ fmr_water_mark $(printf "0x%08x" ${FMR_WATERMARK})

   

    # -- Update sdp, sdp-sockets, q-mng components.
    echo "change_buf_size ${SDP_BUF_SIZE}" > /proc/voltaire/sdp/control
    echo "fmr_change_unmap_at_once_value ${FMR_UNMAP_AT_ONCE}" > /proc/voltaire/sdp/control

    echo "change_buf_num ${SDP_BUF_NUM}" > /proc/voltaire/sdp/control
    echo "change_post_rcv_pnd_th ${SDP_RCV_LIST_SIZE}" > /proc/voltaire/sdp/control
    echo "change_send_bcopy_th ${SDP_RDMA_TRESHOLD}" > /proc/voltaire/sdp/control
    echo "change_uc_watermark ${SDP_UPD_CRDT_LOW}" > /proc/voltaire/sdp/control
    echo "change_uc_posted_buff_th ${SDP_UPD_CRDT_HIGH}" > /proc/voltaire/sdp/control
    echo "change_send_signal_th ${SDP_SIGNALLING_TH}" > /proc/voltaire/sdp/control
    # SDP Socket Setup
    # Fixed Size :1 - configuration controll, 0 - Application controll (default)
    echo "sndbuf_status ${SDP_SOCK_FIXED_SIZE}" > /proc/voltaire/sdp-sockets/control
    echo "sndbuf_size ${SDP_SOCK_SEND_LIMIT}" > /proc/voltaire/sdp-sockets/control

    exec 2>/dev/tty

    echo -n 'Press <Enter> to continue: '
    read ans
}

VSD_EXT=""
ib_burn()
{
    mst start > /dev/null
	case "${OS}" in
         Darwin)
         # Temporary:
         # On Darwin we still use the old-style flint
             flint b  $1 $2;
         ;;
         *)
            flint -d $1 -i $2  $VSD_EXT  -nofs  $ANSWER_YES_BURN burn;
         ;;
    esac
    mst stop > /dev/null
}

# -------------- MST firmware upgrade.



ib_firmware()
{
    # There is no HCA
    if [[ $NUM_HCAS -eq 0 ]]; then
	echo "There is no HCA, burning is halted!!!"
        echo "Please insert HCA and than try again"
        return
    fi
                                                                                                                            
    echo "There is $NUM_HCAS HCA on this machine"
    echo "Please enter number of HCA you want to burn"
    echo "If you want to burn all HCAs please enter \"all\""
    read ans
    
    if [[ "$ans" = all ]];then
	  HCA_TO_BURN=all	
    elif [[ $ans -gt 0 && $ans -le $NUM_HCAS ]]; then
	  HCA_TO_BURN=$ans
    else
	echo "Wrong parameter"
	usleep 1000
	return
    fi  
    
    for(( hca_num=1;$hca_num<=$NUM_HCAS;hca_num++ ))
    do  
	if [[ "$HCA_TO_BURN" != all ]]; then
		if [[ $HCA_TO_BURN -ne $hca_num ]];then
			continue
		fi
	fi
    		
	echo "Burning HCA$hca_num ....."
	
	get_fw_and_vsd $(($hca_num-1))

    	if [[ $BURNING_FLAG -eq 0 ]]; then
		echo "To forse burning you should specify image file"
		echo "Do you want to continue? (y/n)"
		read ans
		if [[ "$ans" = y* ]]; then
			echo "Please enter the image name using full path"
			read ans
			if  [ ! -z "$ans" ]; then 
				FW_IMAGE="$ans" 
			else
				echo "You didn't specify image file. Burning is halted!!!" 
				sleep 1
				return
			fi
		else
			echo "Action canceled. please wait ..."
			sleep 1
			return
		fi
    	fi
 
    	echo "You are about to upload new FW to the HCA"
    	echo "FW image is: ${FW_IMAGE}"
 	echo "VPD-VSD is : ${VSD_EXT}"
    	echo "This operation would change the FW on the HCA and requires a system shutdown"
    	echo -n " Do you wish to continue (y/n):"
    	read ans
    	if [[ "$ans" = y* ]]; then
	    	if [[ $BURNING_FLAG -eq 1 ]]; then	
	    		echo -n "If you wish to use a different image please enter the image name, using full path:"     
	    		read ans; if  [ ! -z "$ans" ]; then FW_IMAGE="$ans" ; fi
	    	fi
   
	    	#validation check
	    	if [ -e $FW_IMAGE ] ; then
		#echo "before FW update $HCA_DEV $FW_IMAGE "
      	        	ib_burn ${HCA_DEV} ${FW_IMAGE}
		     	echo
		     	echo "FW update done. press any key to continue ... "
                     	read -n 1 b;
	    	else
	        	echo "ERROR! could not find file ${FW_IMAGE}" 
	        	echo "press any key to continue..."
        		read -n 1 ans
	    	fi
     	else echo "Action canceled. please wait ..."
     	fi
    done
    
}

get_hca_vsd()
{	
    exec 2>/dev/null
    mst start >/dev/null
  
    OS=`uname`
    case "${OS}" in
    Darwin)
        HCA_DEV=/dev/mst_pci_apple
    ;;
    *)
	HCA_DEV=$(ls /dev/mst/mt*cr$1)
#        if [ ! -e /dev/mst/mt23108_pci_cr0 ]; then
#            HCA_DEV=/dev/mst/mt25208_pci_cr0
#        else
#            HCA_DEV=/dev/mst/mt23108_pci_cr0
#        fi
    esac
# There is a mellanox bug , that the first flint query doesn't work 100% , so read once just as workaround 
    flint -d $HCA_DEV q >/dev/null
    exec 2>/dev/tty
    VSD=$( flint -d $HCA_DEV q |grep -i board | awk   '{ print $3  }' >/dev/null)
# Sorry for this ugly work around - MLX has a bug. On PCI-Express the first time you run flint query you get an error
    VSD=$( flint -d $HCA_DEV q |grep -i board | awk   '{ print $4  }' )
 #in new MLX cards only VSD2 appears and it starts with "("
    VSD_HP=$( echo $VSD | awk '{ print substr($0,2,2) }' )
    if [ "$VSD_HP" == "HP" ]; then
        VSD2_Board_type=$( echo $VSD | awk '{ print substr($0,5,3) }' ) 
    else
    	VSD_first_char=$( echo $VSD | awk '{ print substr($0,1,1) }' )
    	if [ "$VSD_first_char" == "(" ]; then
        	VSD2=$VSD
    	else
        	VSD1=$VSD
        	VSD2=$( flint -d $HCA_DEV q |grep -i board | awk   '{ print  $4 }' )
    	fi
	VSD2_Board_type=$( echo $VSD2 | awk '{ print substr($0,5,3) }' )
    	VSD2_Manufacture=$( echo $VSD2 | awk '{ print substr($0,8,3) }' )
    	VSD2_reserve=$( echo $VSD2 | awk '{ print substr($0,11,4) }' )
    fi
    mst stop >/dev/null
    exec 2>/dev/tty
}

get_fw_and_vsd()
{
 #Check HCA existence
# HCA_existentce=$(/sbin/lspci -n | grep 15b3 | wc -l)
#if [ $HCA_existentce -eq 0 ]; then
#	echo "There is no HCA, burning is halted!!!"
#	echo "Please insert HCA and than try again"
#	BURNING_FLAG=2
#	sleep 2
#	return
# fi	

 	
 #Mellnox args
 #-------------
 MLX_Manufac_id="001"
 Board_type_LP="001"
 Board_type_PCI_exp="002"
 Board_type_PCI_exp_MF="003"
 Board_type_PCI_exp_DDR="004"
 Board_type_PCI_exp_MF_DDR="005"
 Board_type_PCI_exp_REVC="006"

 LP_fw=/usr/mst/fw-23108-rel-3.0.0/HCA400-MLX_LP-23108-3_5_0.img 
 PCI_exp_fw=/usr/mst/fw-23108-rel-3.0.0/HCA400Ex-25208-4_7_6.img
 PCI_exp_DDR_fw=usr/mst/fw-23108-rel-3.0.0/HCA400Ex-D-25208-4_7_6.img
 PCI_exp_MF_fw=/usr/mst/fw-23108-rel-3.0.0/HCA410Ex-25204-1_2_0.img
 PCI_exp_MF_DDR_fw=/usr/mst/fw-23108-rel-3.0.0/HCA410Ex-D-25204-1_2_0.img
 PCI_exp_REVC_fw=/usr/mst/fw-23108-rel-3.0.0/HCA400Ex-rC-25208-4_7_6.img

 #Sanmina args
 #-----------
 Sanmina_Manufac_id="002"
 Sanmina_fw=/usr/mst/fw-23108-rel-3.0.0/HCA400-SANMINA-23108-3_5_0.img

 # HP args
 HP_001_fw=/usr/mst/fw-23108-rel-3.0.0/hpmezz-1.1.0.bin
 HP_003_fw=/usr/mst/fw-23108-rel-3.0.0/HCA400-MLX_LP-23108-3_5_0.img
 HP_004_fw=/usr/mst/fw-23108-rel-3.0.0/HCA400-MLX_LP-23108-3_5_0.img
 HP_005_fw=/usr/mst/fw-23108-rel-3.0.0/HCA400Ex-rC-25208-4_7_6.img
 HP_006_fw=/usr/mst/fw-23108-rel-3.0.0/HCA400Ex-D-25208-4_7_6.img
 HP_007_fw=/usr/mst/fw-23108-rel-3.0.0/HCA410Ex-D-25204-1_2_0.img
 HP_008_fw=/usr/mst/fw-23108-rel-3.0.0/HCA410Ex-25204-1_2_0.img
 
 #HCA args
 #----------
 get_hca_vsd $1

#for debug:
#echo "Board_type = $VSD2_Board_type, Manufacture= $VSD2_Manufacture, reserve=$VSD2_reserve"
#echo "MLX man $MLX_Manufac_id LP $Board_type_LP PCI-EX $Board_type_PCI_exp"

if [ "$VSD_HP" == "HP" ]; then
	case "${VSD2_Board_type}" in
	"001")
	   FW_IMAGE=$HP_001_fw
	   ;;
	"003")
	   FW_IMAGE=$HP_003_fw
	   ;;
	"004")
	   FW_IMAGE=$HP_004_fw
	   ;;
 	"005")
           FW_IMAGE=$HP_005_fw
	   ;;
	"006")
	   FW_IMAGE=$HP_006_fw
	   ;;
	"007")
	   FW_IMAGE=$HP_007_fw
  	   ;;
	"008")
	   FW_IMAGE=$HP_008_fw
	   ;;
	*)
            echo "ERROR. unknow Board type $VSD2_Board_type for HP"
            BURNING_FLAG=0
            sleep 2
            ;;
        esac

	VSD_EXT="-psid HP_"$VSD2_Board_type"0000001 -use_image_ps"
 
elif [ -e $VSD2_Manufacture ]; then
        echo "VPD-VSD is not burned, HCA Identification failed"
	BURNING_FLAG=0
        sleep 2

elif [ $VSD2_Manufacture == $MLX_Manufac_id ]; then
	case "${VSD2_Board_type}" in
            "$Board_type_LP")
                   FW_IMAGE=$LP_fw
                   VSD_EXT=" -vsd1 VLT-LP  -vsd2 VLT$Board_type_LP$MLX_Manufac_id$VSD2_reserve "
            ;;
            "$Board_type_PCI_exp")
                    FW_IMAGE=$PCI_exp_fw
                    VSD_EXT=" -vsd1 VLT-EXP -vsd2 VLT$Board_type_PCI_exp$MLX_Manufac_id$VSD2_reserve "
            ;;
            "$Board_type_PCI_exp_MF")
                    FW_IMAGE=$PCI_exp_MF_fw
                    VSD_EXT=" -vsd1 VLT-MF -vsd2 VLT$Board_type_PCI_exp_MF$MLX_Manufac_id$VSD2_reserve "
            ;;
            "$Board_type_PCI_exp_DDR")
                    FW_IMAGE=$PCI_exp_DDR_fw
                    VSD_EXT=" -vsd1 VLT-EXPD -vsd2 VLT$Board_type_PCI_exp_DDR$MLX_Manufac_id$VSD2_reserve "
            ;;
            "$Board_type_PCI_exp_MF_DDR")
                    FW_IMAGE=$PCI_exp_MF_DDR_fw
                    VSD_EXT=" -vsd1 VLT-MFD -vsd2 VLT$Board_type_PCI_exp_MF_DDR$MLX_Manufac_id$VSD2_reserve "
            ;;
            "$Board_type_PCI_exp_REVC")
		   FW_IMAGE=$PCI_exp_REVC_fw
		   VSD_EXT=" -vsd1 VLT-EXP-C -vsd2 VLT$Board_type_PCI_exp_REVC$MLX_Manufac_id$VSD2_reserve "
	    ;;
            *)
                   echo "ERROR. unknow Board type $VSD2_Board_type for MLX"
		   BURNING_FLAG=0
		   sleep 2		
                   
            ;;
            esac
elif [ $VSD2_Manufacture == $Sanmina_Manufac_id ]; then
	FW_IMAGE=$Sanmina_fw
        VSD_EXT="-vsd1 VLT-SAN -vsd2 VLT0010020001"
else  	
 	echo "Failed with HCA identification, burning is halted !!!"
	BURNING_FLAG=0
        sleep 2
fi

}

# -------------- Rescan the IB fabric.
ib_rescan(){
    echo "IB fabric LID assignment."
    echo "This function should run only on the SM enabled system."
    echo -n "Are you sure you would like to run it (y/n): "
    read a
    if [[ "$a" = y* ]]; then
	get_hca_id
        /usr/mellanox/bin/vapi start
        echo x | minism $hca_id
    else
        echo "skipped."
    fi
}
set_join_multicast_group(){
    SAMGJ=$(rep-get modules/ipoib-ud link-join )
    echo "Setting Join Multicast Group"
    echo "no-join - using minism, no SA/SM."
    echo "join    - using Voltaire-SM, join the created Multicast Group."
    echo "create  - using Voltaire-SM, created the Multicast Group."
    echo "Current settings: $SAMGJ"

    select j in no-join join create exit
    do
        case $j in
        no-join|join|create)
            rep-set modules/ipoib-ud link-join $j
    	    exec 2>/dev/null
            rep_mset voltaire/modules/ipoib-ud/ link-join \"$j\"
            exec 2>/dev/tty
	    echo "the new mode is $j"
            if [[ "X$SAMGJ" != "X$j" ]]; then
                echo "In order to activate the new mode '$j',"
                echo " you should restart the IB stack,"
                echo -n " would you like to do it now (y/n): "
                read a
                if [[ "$a" = y* ]]; then
                    ib_stop
                    ib_start
                else
                    echo "ok, restart later."
                    usleep 200000
                fi
            fi
            return
        ;;
	exit)
	    return
	    ;;
	*)
	    echo "unknown option, exit"
            return
        esac 
    done
}

function set_VFM_parameters()
{
 	rep-set modules/ipoib-ud link-join "join"
	rep_mset voltaire/modules/ipoib-ud/ link-join '"join"'
	rep-set modules/ib-arp-table sa-queries $(printf "0x%08x" 1)
	rep_mset voltaire/modules/ib-arp-table/ sa-queries $(printf "0x%08x" 1)
	rep-set modules/subnet-manager type "VFM"
	rep_mset voltaire/modules/subnet-manager/ type '"VFM"'
	rep-set modules/ats active_mode $(printf "0x%08x" 1)
	rep_mset voltaire/modules/ats/ active_mode $(printf "0x%08x" 1)
}

function set_minism_parameters()
{
	rep-set modules/ipoib-ud link-join "no-join"
	rep_mset voltaire/modules/ipoib-ud/ link-join '"no-join"'
	rep-set modules/ib-arp-table sa-queries $(printf "0x%08x" 0)
	rep_mset voltaire/modules/ib-arp-table/ sa-queries $(printf "0x%08x" 0)
	rep-set modules/subnet-manager type "minism"
	rep_mset voltaire/modules/subnet-manager/ type '"minism"'
	
	if [[ "$ATS_ENABLE" = 'yes' ]]; then
		rep-set modules/ats active_mode $(printf "0x%08x" 1)
                rep_mset voltaire/modules/ats/ active_mode $(printf "0x%08x" 1)
        else
                rep-set modules/ats active_mode $(printf "0x%08x" 0)
                rep_mset voltaire/modules/ats/ active_mode $(printf "0x%08x" 0)
        fi
}

fabric_related_prameters()
{
    LJOIN=$(rep-get modules/ipoib-ud link-join )
    LPATH=$(rep-get modules/ib-arp-table sa-queries | perl -ne 'print hex')
    LSM=$(rep-get modules/subnet-manager type) 
    ATS=$(rep-get modules/ats active_mode | perl -ne 'print hex')
    
    echo "This menu configures fabric related parameters"
    echo "VFM - Enable join multicast group and path queries support"
    echo "minism - No join multicast group and no Path qureies support"
    echo "advanced - advanced users only"
    echo "Current configuration: SM Type $LSM ATS=$ATS"
    select j in VFM minism advanced exit
    do
        case $j in
        VFM)
            exec 2>/dev/null
	    set_VFM_parameters
            exec 2>/dev/tty
	    break
	    ;;
	minism)
	    exec 2>/dev/null
	    echo "Do you want to enable ats?  (y/n)"
	    read a
	    if [[ "$a" = 'y' ]]; then
	    	ATS_ENABLE='yes'	
	    else
		ATS_ENABLE='no'
	    fi
    	    set_minism_parameters
	    exec 2>/dev/tty
	    break
	    ;;
	advanced)
	    echo "path = $LPATH"
	    if (( ${LPATH} == 1 )) ; then
		LPATH_STR=YES
	    else
		LPATH_STR=NO
	    fi
	    echo "Current configuartion SM=$LSM ; join=$LJOIN ;  path query=$LPATH_STR"
	    select k in join-multicast-group path-query exit
		do
		case $k in
		join-multicast-group)
		    echo -n "support join multicast group? (y/n): "
		    read a
    		    exec 2>/dev/null
		    if [[ "$a" = y* ]]; then
			rep-set modules/ipoib-ud link-join "join"
			rep_mset voltaire/modules/ipoib-ud/ link-join '"join"'
		    else
			rep-set modules/ipoib-ud link-join "no-join"
			rep_mset voltaire/modules/ipoib-ud/ link-join '"no-join"'
		    fi
		    exec 2>/dev/tty
		    break
		    ;;
			
		path-query)
		    echo -n "Enable dynamic path queries ? (y/n): "
		    read a
    		    exec 2>/dev/null
		    if [[ "$a" = y* ]]; then
			rep-set modules/ib-arp-table sa-queries $(printf "0x%08x" 1)
			rep_mset voltaire/modules/ib-arp-table/ sa-queries $(printf "0x%08x" 1)
		    else
			rep-set modules/ib-arp-table sa-queries $(printf "0x%08x" 0)
			rep_mset voltaire/modules/ib-arp-table/ sa-queries $(printf "0x%08x" 0)
		    fi
		    exec 2>/dev/tty
		    break
		    ;;
		exit)
		    return
		    ;;
		*)
		    echo "unknown option"
		    ;;
		esac
		done
	    break
	    ;;
	exit)
	    return
	    ;;
	*)
	    echo "unknown option"
	    ;;
        esac
    done
    echo "Stack restart is required to enable change"
    echo -n "would you like to restart the stack now ? (y/n): "
    read a
    if [[ "$a" = y* ]]; then
       ib_stop
       ib_start
    else
       echo "ok, restart later."
       usleep 200000
    fi
}
    
function ucm_settings(){
    UCMENABLED=$(rep-get modules/devucm enabled | perl -ne 'print hex')
    echo "Setting for the uCM (User mode Communication Manager)."
    echo
    echo -n "current mode: "
    if (( $UCMENABLED )) ; then echo Active ; else echo "Non Active" ; fi
    echo
    echo "Do you want to activate the uCM at startup (y/N)?"
    echo -n ": "
    local ans
    read ans
    if [[ $ans = y* ]]; then
        echo "uCM will start it on startup, loading now uCM."
        rep-set modules/devucm enabled 0x00000001
    	exec 2>/dev/null
        rep_mset voltaire/modules/devucm/ enabled 0x00000001
	exec 2>/dev/tty
        loadmodule devucm.o
        ibhost-mkmisc ucm
    else
        echo "uCM will not start nn Startup, unloading uCM."
        rep-set modules/devucm enabled 0x00000000
	exec 2>/dev/null
        rep_mset voltaire/modules/devucm/ enabled 0x00000000
	exec 2>/dev/tty
        rmmod devucm
    fi
    sleep 1
}

function ucm_settings(){
    UCMENABLED=$(rep-get modules/devucm enabled | perl -ne 'print hex')
    echo "Setting for the uCM (User mode Communication Manager)."
    echo
    echo -n "current mode: "
    if (( $UCMENABLED )) ; then echo Active ; else echo "Non Active" ; fi
    echo
    echo "Do you want to activate the uCM at startup (y/N)?"
    echo -n ": "
    local ans
    read ans
    if [[ $ans = y* ]]; then
        echo "uCM will start it on startup, loading now uCM."
        rep-set modules/devucm enabled 0x00000001
        exec 2>/dev/null
        rep_mset voltaire/modules/devucm/ enabled 0x00000001
        exec 2>/dev/tty
        loadmodule devucm.o
        ibhost-mkmisc ucm
    else
        echo "uCM will not start nn Startup, unloading uCM."
        rep-set modules/devucm enabled 0x00000000
        exec 2>/dev/null
        rep_mset voltaire/modules/devucm/ enabled 0x00000000
        exec 2>/dev/tty
        rmmod devucm
    fi
    sleep 1
}

function ats_settings(){

   ATS_NOT_LOADED="not-loaded" #(active_mode=0 in repository)
   ATS_LOAD="not-resolver" #(active_mode=1 " ")
   ATS_LOAD_ONLY="resolver" #(active_mode=2  " ") ats will do the address resolving

    ATS_REP_VAL=$(rep-get modules/ats active_mode | perl -ne 'print hex')
    if (( $ATS_REP_VAL == 0 )); then
         CURR_STAT=$ATS_NOT_LOADED
    else if (( $ATS_REP_VAL == 1 )); then
        CURR_STAT=$ATS_LOAD
        else if (( $ATS_REP_VAL == 2 )); then
          CURR_STAT=$ATS_LOAD_ONLY
             fi
         fi
    fi

    echo
    echo "ATS load mode options (current status: $CURR_STAT):"

    KDAPL_ENABLED=$(rep-get modules/kdapl enabled | perl -ne 'print hex')

    EXTRA=$ATS_LOAD_ONLY

     select c in $ATS_LOAD $EXTRA $ATS_NOT_LOADED Exit
     do
        case $c in
        $ATS_NOT_LOADED)
           rep-set modules/ats active_mode 0x00000000 > /dev/null 2>&1
           rep_mset voltaire/modules/ats/ active_mode 0x00000000 > /dev/null 2>&1
            break
        ;;
        $ATS_LOAD)
            rep-set modules/ats active_mode 0x00000001 > /dev/null 2>&1
            rep_mset voltaire/modules/ats/ active_mode 0x00000001 > /dev/null 2>&1

            break
        ;;
        $ATS_LOAD_ONLY)
           rep-set modules/ats active_mode 0x00000002 > /dev/null 2>&1
           rep_mset voltaire/modules/ats/ active_mode 0x00000002 > /dev/null 2>&1

          break
        ;;
        Exit)
            return;
            break
        ;;
        *)
            echo "Choose a number from the above range."
            break
        ;;
        esac
    done

}
function kdapl_settings()
{
	KDAPL_ENABLED=$(rep-get modules/kdapl enabled | perl -ne 'print hex')
    	echo "Setting for the kdapl"
    	echo
    	echo -n "current mode: "
    	if (( $KDAPL_ENABLED )) ; then echo Active ; else echo "Non Active" ; fi
    	echo
    	echo "Do you want to activate the kdapl at startup (y/N)?"
    	echo -n ": "
    	local ans
    	read ans
    	if [[ $ans = y* ]]; then
		KDAPL_ENABLED=1
		kdapl_rep_settings
	else
		KDAPL_ENABLED=0
		kdapl_rep_settings
	fi
	sleep 1
}

function kdapl_rep_settings()
{
    if [[ $KDAPL_ENABLED -eq 1 ]]; then
	echo "kdapl will be started on next startup."
        rep-set  modules/kdapl enabled 0x00000001
        rep_mset voltaire/modules/kdapl/ enabled 0x00000001
    elif [[ $KDAPL_ENABLED -eq 0 ]]; then
        echo "kdapl will not start on next Startup."
        rep-set modules/kdapl enabled 0x00000000
        rep_mset voltaire/modules/kdapl/ enabled 0x00000000

	#if ats is in state "load as address translator" (active_mode=2), 
	#change it to load not as address translator (active_mode=1).
        ATS_REP_VAL=$(rep-get modules/ats active_mode | perl -ne 'print hex')
        if (( $ATS_REP_VAL == 2 )); then
            rep-set modules/ats active_mode 0x00000001 > /dev/null 2>&1
            rep_mset voltaire/modules/ats/ active_mode 0x00000001 > /dev/null 2>&1
        fi
    fi
    sleep 1
}

function sdp_rep_settings()
{
	if [[ $SDP_ENABLED -eq 1 ]]; then
		echo "SDP will be started on the next startup."
        	rep-set  modules/sdp enabled 0x00000001
        	rep_mset voltaire/modules/sdp/ enabled 0x00000001
	elif [[ $SDP_ENABLED -eq 0 ]]; then
		echo "SDP won't be started on the next startup."
        	rep-set modules/sdp enabled 0x00000000
        	rep_mset voltaire/modules/sdp/ enabled 0x00000000
    	fi
}



function sdp_settings(){
    SDP_ENABLED=$(rep-get modules/sdp enabled | perl -ne 'print hex')
    echo "Settings for the SDP module"
    echo
    echo -n "current mode: "
    if (( $SDP_ENABLED )) ; then echo Active ; else echo "Non Active" ; fi
    echo
    echo "Do you want to activate the SDP at startup (y/N)?"
    echo -n ": "
    local ans
    read ans
    if [[ $ans = y* ]]; then
	SDP_ENABLED=1
	sdp_rep_settings
    else
	SDP_ENABLED=0
	sdp_rep_settings
    fi
    sleep 1
}


set_log_levels(){
    # Gather information
    LGlogger_key=modules/logger
    LGlogger=$(rep-get       modules/logger         debug-level | perl -ne 'print hex')
    LGvverbs_key=modules/vverbs
    LGvverbs=$(rep-get       modules/vverbs         debug-level | perl -ne 'print hex')
    LGadaptor_key=modules/adaptor-mlx
    LGadaptor=$(rep-get       modules/adaptor-mlx   debug-level | perl -ne 'print hex')
    LGats_key=modules/ats
    LGats=$(rep-get       modules/ats                debug-level | perl -ne 'print hex')
    LGipoib_key=modules/ipoib-ud
    LGipoib=$(rep-get     modules/ipoib-ud       debug-level | perl -ne 'print hex')
    LGgsi_key=modules/gsi
    LGgsi=$(rep-get          modules/gsi            debug-level | perl -ne 'print hex')
    LGib_arp_table_key=modules/ib-arp-table
    LGib_arp_table=$(rep-get modules/ib-arp-table   debug-level | perl -ne 'print hex')
    LGcm_key=modules/cm
    LGcm=$(rep-get           modules/cm             debug-level | perl -ne 'print hex')
    # LGiblan=$(rep-get        modules/iblan          debug-level | perl -ne 'print hex')
    LGsdp_key=modules/sdp
    LGsdp=$(rep-get          modules/sdp            debug-level | perl -ne 'print hex')
    LGsdp_sockets_key=modules/sdp-sockets
    LGsdp_sockets=$(rep-get  modules/sdp-sockets    debug-level | perl -ne 'print hex')
    LGkdapl_key=modules/kdapl
    LGkdapl=$(rep-get  modules/kdapl                debug-level | perl -ne 'print hex')
    LGdevugsi_key=modules/devugsi
    LGdevugsi=$(rep-get          modules/devugsi            debug-level | perl -ne 'print hex')
    LGdevucm_key=modules/devucm
    LGdevucm=$(rep-get           modules/devucm             debug-level | perl -ne 'print hex')

    for v in LGlogger LGvverbs LGadaptor LGats LGipoib LGgsi LGib_arp_table LGcm LGsdp LGsdp_sockets LGkdapl LGdevugsi LGdevucm;
    do
        ans=-1
        while [[ $ans -lt 0 || $ans -gt 100 ]] ;
        do
             printf '%-22s [%s]: ' $v: $(eval echo \$$v);
	     read ans ;
        done
        if [ ! -z "$ans" ]; then eval $v="$ans" ; fi

        rep-set $(eval echo \$${v}_key) debug-level $(printf "0x%08x" $(eval echo \$$v))
        exec 2>/dev/null
        rep_mset voltaire/$(eval echo \$${v}_key)/ debug-level $(printf "0x%08x" $(eval echo \$$v))
        exec 2>/dev/tty
    done

}

sdp_menu(){
        select c in work-mode setup Exit
            
        do
        case $c in
        work-mode)
		sdp_settings
		break
        	;;
	
        setup)
	        sdp_setup
		break
                ;;

	*)
		echo
		break
		;;
	esac
	done

    echo "Stack restart is required to enable change"
    echo -n "would you like to restart the stack now ? (y/n): "
    read a
    if [[ "$a" = y* ]]; then
       ib_stop
       ib_start
    else
       echo "ok, restart later."
       usleep 200000
    fi

}
set_backward_comp(){
        select c in cm rmpp  Exit
        do
        case $c in
        cm)
		echo "Do you want to use cm 1.1 (y/n):"
    		read a
		    if [[ "$a" = y* ]]; then
	              	exec 2>/dev/null
	        	rep-set modules/cm  cm-type $(printf "0x%08x" 1 )
	        	rep_mset voltaire/modules/cm/ cm-type $(printf "0x%08x" 1)
		        exec 2>/dev/tty
		    else
	              	exec 2>/dev/null
	        	rep-set modules/cm  cm-type $(printf "0x%08x" 0 )
	        	rep_mset voltaire/modules/cm/ cm-type $(printf "0x%08x" 0)
		        exec 2>/dev/tty
					 
           	    fi 
	            break
        	;;
	
        rmpp)
                echo "Do you want to use spec compliant rmpp (y/n):"
                read a
                    if [[ "$a" = y* ]]; then
                        exec 2>/dev/null
                        rep-set modules/gsi  rmpp-comp $(printf "0x%08x" 1 )
                        rep_mset voltaire/modules/gsi/ rmpp-comp $(printf "0x%08x" 1)
                        exec 2>/dev/tty
                    else
                        exec 2>/dev/null
                        rep-set modules/gsi  rmpp-comp $(printf "0x%08x" 0 )
                        rep_mset voltaire/modules/gsi/ rmpp-comp $(printf "0x%08x" 0)
                        exec 2>/dev/tty

                    fi
                    break
                ;;

	*)
		echo
		break
		;;
	esac
	done

    echo "Stack restart is required to enable change"
    echo -n "would you like to restart the stack now ? (y/n): "
    read a
    if [[ "$a" = y* ]]; then
       ib_stop
       ib_start
    else
       echo "ok, restart later."
       usleep 200000
    fi

}

function set_heart_beat_join()
{
	echo bc_mc_group_period $INTERVAL_JOIN $SKEW_JOIN > /proc/voltaire/ipoib-ud/control
                                                                                                                            
	rep-set modules/ipoib-ud sm-heart-beat $(printf "0x%08x" ${INTERVAL_JOIN})
	rep_mset voltaire/modules/ipoib-ud/ sm-heart-beat $(printf "0x%08x" ${INTERVAL_JOIN})
                                                                                                                            
	rep-set modules/ipoib-ud sm-heart-beat-skew $(printf "0x%08x" ${SKEW_JOIN})
	rep_mset voltaire/modules/ipoib-ud/ sm-heart-beat-skew $(printf "0x%08x" ${SKEW_JOIN})
}

function set_heart_beat_ats()
{
        echo sa_verify_period $INTERVAL_ATS $SKEW_ATS> /proc/voltaire/ats/control
                                                                                                                            
	rep-set modules/ats sm-heart-beat $(printf "0x%08x" ${INTERVAL_ATS})
        rep_mset voltaire/modules/ats/ sm-heart-beat $(printf "0x%08x" ${INTERVAL_ATS})
                                                                                                                            
        rep-set modules/ats sm-heart-beat-skew $(printf "0x%08x" ${SKEW_ATS})
        rep_mset voltaire/modules/ats/ sm-heart-beat-skew $(printf "0x%08x" ${SKEW_ATS})
}
                                                                                                                            

function sm_heart_beat_join(){
    echo "When set to enable , the stack will actively inquire" 
    echo "the SM about it's join status every interval+(interval*skew)100*random sec"
    echo "To disable - Please set the interval to 0"
	
    JOIN_HERT_BEAT=$(rep-get modules/ipoib-ud sm-heart-beat)
    JOIN_SKEW=$(rep-get modules/ipoib-ud sm-heart-beat-skew)
    echo Current parameters are heart_beat_join=$JOIN_HERT_BEAT and skew=$JOIN_SKEW 	
    echo -n "Would you like to configure the join heart beat ? (y/n): "
    read a
    if [[ "$a" = y* ]]; then
	echo -n "Please configure update interval: "
        read INTERVAL_JOIN
	if [ ! -z "$INTERVAL_JOIN" ]; then
		echo -n "Would you like to configure the skew for join heart beat ? (y/n): "
        	read a
        	if [[ "$a" = y* ]]; then
                	echo -n "Please insert skew value: "
                	read SKEW_JOIN
			if [[ ! -z  "$SKEW_JOIN" ]]; then
				if [[ (( $SKEW_JOIN -lt 1 )) || (( $SKEW_JOIN -gt 100 )) ]]; then
					echo "Skew should be between 1 and 100"
					sleep 2
				else
					set_heart_beat_join 
				fi
			else
				echo "You must specify a value"
				sleep 2
			fi
		else
			SKEW_JOIN=0
			set_heart_beat_join
		fi
	else
		echo "You must specify an interval"
		sleep 2   
	fi
  fi
}

function sm_heart_beat_ats(){
    echo "When set to enable , the stack will actively inquire"
    echo "the SM about it's ATS status every interval+(interval*skew)100*random sec"
    echo "To disable - Please set the interval to 0"

    ATS_HEART_BEAT=$(rep-get modules/ats sm-heart-beat)
    ATS_SKEW=$(rep-get modules/ats sm-heart-beat-skew)
    echo "Current parameters are haert_beat_ats=$ATS_HEART_BEAT ans skew=$ATS_SKEW" 		
    echo -n "Would you like to configure the join heart beat ? (y/n): "
    read a
    if [[ "$a" = y* ]]; then
        echo -n "Please configure update interval: "
        read INTERVAL_ATS
        if [ ! -z "$INTERVAL_ATS" ]; then
                echo -n "Would you like to configure the skew for ats heart beat ? (y/n): "
                read a
                if [[ "$a" = y* ]]; then
                        echo -n "Please insert skew value: "
                        read SKEW_ATS
                        if [[ ! -z  "$SKEW_ATS" ]]; then
                                if [[ (( $SKEW_ATS -lt 1 )) || (( $SKEW_ATS -gt 100 )) ]]; then
                                        echo "Skew should be between 1 and 100"
					sleep 2
                                else
                                        set_heart_beat_ats
                                fi
                        else
                                echo "You must specify a value"
				sleep 2
                        fi
                else
                        SKEW_ATS=0
                        set_heart_beat_ats
                fi
        else
                echo "You must specify an interval"
		sleep 2
        fi
  fi
}

function verify_hca_pci_type()
{

  if [[ $HCA_NAME == "InfiniHost_III_Lx$(($hca_num-1))" ]]; then
	echo "PCI-Express" 
  else
  	if  [[ $VAPI_FLAG -eq 1 ]] ; then
		LINE_ID=`lspci | grep InfiniBand: |  awk -F " " ' {print $1} '`
		PART_ID=`lspci -n | grep $LINE_ID | awk -F ":" '{print $4}' |  awk -F " " '{print $1}'`
		PART_ID="0x$PART_ID"
	else
  		PART_ID=`/usr/mellanox/bin/vapi status | grep -A 3 InfiniHost$1 | awk -F "=" '/vendor_part_id/ {print $2}'`
	fi
  	if [[ $PART_ID == "0x5A44" ]]; then
		echo "PCI-X"
  	elif [[ $PART_ID == "0x6278" ]]; then
      		echo "PCI-Express"
  	else
		echo "UNKNOWN"
  	fi
	
  fi	
}

function set_join_arp_failure()
{
	echo join_arp_failure $JOIN_ARP_FAILURE > /proc/voltaire/ipoib-ud/control
	rep-set modules/ipoib-ud join_arp_failure $(printf "0x%08x" ${JOIN_ARP_FAILURE})
	rep_mset voltaire/modules/ipoib-ud/ join_arp_failure $(printf "0x%08x" ${JOIN_ARP_FAILURE})
}

function join_arp_failure()
{
	echo "When set to disable join will not be sent after arp failure"
	echo "Enable join_arp_failure ? (y/n)"
	read a
	
	if [[ "$a" = y* ]]; then
		JOIN_ARP_FAILURE=1
		set_join_arp_failure
	else
		JOIN_ARP_FAILURE=0
                set_join_arp_failure
	fi
} 

function set_arp_retries()
{
        rep-set modules/ib-arp-table path_retries $(printf "0x%08x" ${ARP_RETRIES})
        rep_mset voltaire/modules/ib-arp-table/ path_retries $(printf "0x%08x" ${ARP_RETRIES})
                                                                                                                            
       echo set_retry_cnt $ARP_RETRIES > /proc/voltaire/ib-arp-table/control
}

function arp_retries()
{
	echo "Please insert then number of arp retries"
	read ARP_RETRIES
	set_arp_retries
}

function mpi_select() {

        if [ ! -L /usr/voltaire/mpi ]; then
             if [ -d /usr/voltaire/mpi ]; then
                 echo "/usr/voltaire/mpi is not a symbolic link"
                 echo "Press any key to continue"
                 read dummy
                 return
             fi
        fi 

        echo ""
        echo "There can be several available MPI compiled versions,"
        echo "to use different C & FORTRAN compilers, like"
        echo "       GNU            compilers    (gcc, g77),"
        echo "       Intel          compilers    (icc, ifc),"
        echo "       Pathscale      compilers    (pathcc, pathf90),"
        echo "       Portland Group compilers    (pgcc, pgf77, pgf90)"
        echo ""
        echo "The versions may be built to run by remote shell (rsh)" 
        echo "      or MPI deamon (mpd)"
        echo ""

        if [ -L /usr/voltaire/mpi ]; then
             echo ""
             echo -n "Currently used version: "
             ls -ld  /usr/voltaire/mpi |awk -F'>' '{print $2}'
             echo ""
        fi

        echo "Which one would you like to use?"
        echo

        select c in `ls /usr/voltaire | grep 'mpi\.'`  Exit
        do
        case $c in
        Exit)
        ;;
        *)
              echo $c
              ln -snf $c /usr/voltaire/mpi
        ;;
        esac
        return
        done
}
not_unreg_dev()
{
       NOT_UNREG_DEV=$(rep-get modules/ipoib-ud not-unreg-dev | perl -ne 'print hex')
       if [[ $NOT_UNREG_DEV -eq 1 ]]; then
               echo "IPOIB module set to NOT unreg_dev during stack stop"
       else
               echo "IPOIB module set to unreg_dev during stack stop"
       fi

       echo "If you want to disable unreg_dev please enter 1 else enter 0"
       read ans
       if [[ $ans -eq 1 ]]; then
               NOT_UNREG_DEV=1
       elif [[ $ans -eq 0 ]]; then
               NOT_UNREG_DEV=0
       else
               echo "Incorrect option, try again"
               sleep 1
               return
       fi

       set_unreg_dev
}

set_unreg_dev()
{
       rep-set modules/ipoib-ud not-unreg-dev $(printf "0x%08x" $NOT_UNREG_DEV)
       rep_mset voltaire/modules/ipoib-ud/ not-unreg-dev $(printf "0x%08x" $NOT_UNREG_DEV)
       if [[ $NOT_UNREG_DEV -eq 1 ]]; then
               echo "This will disable unreg_dev on the next start up"
               sleep 1
       else
               echo "This will enable unreg_dev on the next start up"
               sleep 1
       fi
}


usage(){
        case "${OS}" in
        Darwin)
	   echo "Usage:"
           echo "ib-setup [--config] [--ip | --network ] [--netmask] [--broadcast] [--mtu]"
        ;;
        *)
	   echo "Usage:"
	   echo "ib-setup [--config] [--ip | --network | --dhcp ] [--netmask] [--broadcast] [--mtu] [--interface] [--active](active = 0 or 1) [--eth_interface]"
        ;;
        esac
	echo "ib-setup [--burn_hca] [--hca_num] [--yes] [--file]"
	echo "ib-setup [--sdp] [--on|off]"
	echo "ib-setup [--kdapl] [--on|off]"
	echo "ib-setup [--path-query] [--on|off]"
	echo "ib-setup [--set-stat-path] [raw_traffic] [flow_lbl] [hop_lmt] [traffic_cls] [pkey] [sl_mask] [mtu_sel]"
	echo "         [mtu] [rate_sel] [rate] [pkt_life_time_sel] [pkt_life_time]"
	echo "ib-setup [--heart-beat-join] [interval] [skew]"
	echo "ib-setup [--heart-beat-ats] [interval] [skew]"
	echo "ib-setup [--join_arp_failure] [--on|off]"	
	echo "ib-setup [--set_arp_retries] [arp-retries]"        
	echo "ib-setup [--work-mode] [--minism|VFM] [--ats-on|ats-off] (--ats-on|off relevant only for minism)"
	echo "ib-setup [--query_config]"
	echo "ib-setup [--query_hca]"
	echo "ib-setup [--add_interface] [--pkey] [--dhcp | --ip] [--netmask] [--broadcast] [--mtu] [--active](active = 0 or 1) "
	echo "ib-setup [--delete_interface] [interface num]"
        echo "ib-setup [--unreg_dev] [--yes|no]"
	echo "Examples:"
	echo "ib-setup --config --ip 192.168.1.10 --netmask 255.255.0.0 --broadcast 192.168.255.255 --interface ipoib1 --active 0 --mtu 1500"
	echo "ib-setup --config --network 192.168.1.0 --interface ipoib2 --eth_interface eth1"
        case "${OS}" in
        Darwin)
        ;;
        *)
	echo "ib-setup --config --interface [interface name] --dhcp (restarts the interface)"
        ;;
        esac
	echo "Main options:"
	echo "--ip       	  	Configure static ip."
	echo "--network  	  	Configure Infiniband ip acording to the Ethernet network interface,"
	echo "			  	using the base network."
	echo "           	  	The IP is based on eth0/en0 unless specifed with --intarface" 
        case "${OS}" in
        Darwin)
        ;;
        *)
	   echo "--dhcp     	  	Use dhcp to retrive ip from the dhcp server and restart the network interface"
        ;;
        esac

	echo "--burn_hca 	  	Upload new image to the HCA," 
	echo "       			HCA number can be specified by using option --hca_num,"
        echo "      			if HCA number wasn't specified, all HCAs will be burn."
	echo "      			After burning please shutdown the system"				
	echo "           	  	The file option should be used by advanced users only"
	echo "--sdp      	  	Enable or disable SDP loading on the next startup"
	echo "--kdapl			Enable or disable KDAPL loading on the next startup"
	echo "--path-query	  	Enable or disable dynamic path_query"  
	echo "--set-stat-path		Set static path"
	echo "--heart-beat-join" 
	echo "--heart-beat-ats" 	
	echo "                    	Set heart beat and skew of sm." 
	echo "                    	When set to enable, the stack will actively inquire"
        echo "                    	the SM about it's status and information every" 
	echo "                  	interval+(interval*skew)100*random sec"
        echo "                    	To disable - Please set the interval to 0"
	echo "--join_arp_failure	Enable or disable join sending after an arp failure"
	echo "--set_arp_retries 	Set the number of arp retries"
	echo "--work-mode		Work mode can be minism or VFM"
	echo "          		VFM - Enable join multicast group and path queries support"
    	echo "          		minism - No join multicast group and no path qureies support"               
	echo "--query_config		This query will return stack configuration"
	echo "--query_hca		This query will return hca type, fw and bus type"             
	echo "--add_interface		This will add additional ipoib interface with the given pkey number"
	echo "--delete_interface	This will delete the given ipoib interface"
        echo "--unreg_dev               Enable (--yes)  or disable (--no) unreg_dev during stack's stop
                                        (By default it is enabled)"

}


# -------------- Main.

export MTHOME='/usr/mellanox'

if [[ ("X$1" == "X--help") || ("X$1" == "X-?") || ("X$1" == "X-usage") ]]; then
	usage
	exit 0
fi

AUTOSTART="Auto-start"
FIRMWAREUPDATE="Firmware-update"

OS=`uname`
case "${OS}" in
    Darwin)
        LIN_DIST="Darwin"
        MTU_LIMIT=1500
        IPOIB_UD=`ifconfig |  awk -F: '/ipoib-ud/ {print $1}'`
        if [[ -z "$ETH_IF" ]] ; then
                ETH_IF='en0'
        fi
        usleep() {
                echo ""
        }
    ;;
    *)
        LIN_DIST=$(ibhost-linux-dist-name)
        MTU_LIMIT=2044

	for ((i=0;i<64;i++))
	do
		pkey=$(rep-get interfaces/ipoib-ud pkey$i | perl -ne 'print hex')
		if [[ $pkey -ne 0 ]]; then
			 IPOIB_UD[$i]='ipoib'$i
		else
			 IPOIB_UD[$i]=""
		fi
	done	
	if [[ -z "$ETH_IF" ]] ; then
                ETH_IF='eth0'
        fi
	if [[ -z "$IB_IF" ]] ; then
                IB_IF='ipoib0'
        fi

        # Add MPI configuration option if there are alternatives
        # and /usr/voltaire/mpi is not a real directory
        #
        ls /usr/voltaire | grep 'mpi\.' > /dev/null 2>&1
        if [ $? -eq 0 ]; then
            if [[ ! -e /usr/voltaire/mpi || -L /usr/voltaire/mpi ]]; then
                MPIOPTIONS="MPI"
            fi
        fi

        FABRICOPTIONS="Fabric"
    esac

function check_existance_KDAPL()
{
	KDAPL_MOD=kdapl.o
   	if [ `uname -r | cut -f 1,2 -d .` = "2.6" ]; then   # 2.6 module names end with a ".ko" instead of 2.4's ".o"
        	KDAPL_MOD=kdapl.ko
        fi
	 
	for z in /usr/voltaire/modules/*/${KDAPL_MOD}; do
		if [ -e "$z" ]; then
                	KDAPLOPTION="kDAPL"
            	fi
        done

}

function check_existance_SDP()
{
	SDP_MOD=sdp.o
        if [ `uname -r | cut -f 1,2 -d .` = "2.6" ]; then   # 2.6 module names end with a ".ko" instead of 2.4's ".o"
           	SDP_MOD=sdp.ko
        fi
                                                                                                                            
        for z in /usr/voltaire/modules/*/${SDP_MOD}; do
        	if [ -e "$z" ]; then
                	SDPOPTION="SDP"
            	fi
        done
}

function option-d()
{
    if [[ "$OS" == "Darwin" ]]; then
        EXTRAOPTIONS="Log-levels"
    else
        EXTRAOPTIONS="uCM ATS Log-levels Backward-compatible SM-heart-beat-join SM-heart-beat-ats Join-arp-failure Arp-retries"
        #check existence of SDP
	check_existance_SDP

        #check exsitance of kDAPL
	check_existance_KDAPL
 

    fi
}

function option--burn_hca()
{
	# There is no HCA
    	if [[ $NUM_HCAS -eq 0 ]]; then
        	echo "There is no HCA, burning is halted!!!"
        	echo "Please insert HCA and than try again"
        	exit 0
    	fi

	if [[ "X$1" == "X--hca_num" ]]; then
		HCA_TO_BURN=$2
		if [[ $HCA_TO_BURN -le 0 && $ans -gt $NUM_HCAS ]]; then
        		echo "Wrong hca_num"
        	 	exit 0	
    		fi		
		shift
		shift
	else
		HCA_TO_BURN=all
	fi	

	if [[ "X$1" == "X--yes" ]] ; then
		ANSWER_YES_BURN="-y"
		shift
	fi

	for(( hca_num=1;$hca_num<=$NUM_HCAS;hca_num++ ))
    	do
        	if [[ "$HCA_TO_BURN" != all ]]; then
                	if [[ $HCA_TO_BURN -ne $hca_num ]];then
                        	continue
                	fi
		fi
                                                                                                                            
        	echo "Burning HCA$hca_num ....."
                                                                                                                            
        	get_fw_and_vsd $(($hca_num-1))	
	
		if [[ $BURNING_FLAG -eq 0 ]]; then
			if [[ -z $1 ]]; then
				echo "In order to force burning you should use the following command:"
				echo "--ib-setup --hca_num hca-num --burn_hca --file path-to-image-file"
				exit 0
			fi
		fi
 
   		if [[ ! -z "$1" ]] ; then
			if [[ "$1" == "--file" ]];then
				FW_IMAGE=$2
			else
				echo $1 - wrong option  
				echo Burning is halted
				exit 0
			fi	
		fi
	
		echo "You are burning the HCA with ${FW_IMAGE}"
		echo "with the following arguments:  $VSD_EXT" 

      		ib_burn ${HCA_DEV} ${FW_IMAGE}
	done
		exit 0
}

function option--config()
{ 
  while [[ ! -z "$1" ]] ; do
	case "$1" in
	--ip)
		NEW_LIP="$2"		
		shift
		shift
	;;
	--netmask | -m)
		NEW_LNM="$2"
		shift
		shift
	;;
	--broadcast | -b)
		NEW_LBR="$2"
		shift
		shift
	;;
	--network | -n)
		NEW_NNN="$2"
		shift
		shift
	;;
	--mtu)
		NEW_LMTU="$2"
		shift
		shift
	;;
	--dhcp)
		NEW_LDHCP=1
		shift
	;;
	--interface)
		IB_IF="$2"
		shift
		shift
	;;
	--eth_interface)
		ETH_IF="$2"
		shift
		shift
	;;
	--active)
		ACTIVE="$2"
		shift
		shift
	;;
	--help | -h | *)
		usage
		exit
	;;
	esac
   done


   if [[ -z "$IB_IF" ]]; then
   	echo You should enter interface 
	usage
	exit 1
   fi
	
   if [[ -z "$NEW_LIP" && -z "$NEW_NNN" && -z "$NEW_LDHCP" ]] ; then
	usage
	exit 1
   else
   	AUTOCONFIG=1
   fi	
 
   if [[ ( $ACTIVE -ne 0 ) && ( $ACTIVE -ne 1) ]]; then
	echo You enter wrong --active value please enter 0 or 1
	exit 1
   fi
   if [[ $AUTOCONFIG ]]  ; then 
   	ipoib_config_auto 
   fi
	
   exit
}

if [[ $AUTOCONFIG ]]  ; then
        if ! ifconfig -a | grep -q $ETH_IF  ; then
                echo "Interface does not exist"
                echo
                usage
                exit 1
        fi
        ipoib_config_auto
fi


#SDP enable/disable option
function option--sdp()
{
	check_existance_SDP
	if [[ "$SDPOPTION" != "SDP" ]]; then
		echo "The installed stack version doesn't contain SDP module"
		exit 1
	fi
        if [[ -z "$1" ]]; then
                echo "Argument is missing for this option"
		echo""
                usage
                exit 1
        elif [[ "X$1" == "X--on" ]]; then
		SDP_ENABLED=1
        	sdp_rep_settings
		exit 0
        elif [[ "X$1" == "X--off" ]]; then
		SDP_ENABLED=0
                sdp_rep_settings
		exit 0
        else
                echo "Wrong argument for this option"
		echo ""
                usage
                exit 1
        fi
}

# KDAPL enable/disable option
function option--kdapl()
{
	check_existance_KDAPL
	if [[ "$KDAPLOPTION" != "kDAPL" ]]; then
                echo "The installed stack version doesn't contain KDAPL module"
                exit 0
	fi
	if [[ -z "$1" ]]; then
                echo "Argument is missing for this option"
                echo""
                usage
                exit 1
	elif [[ "X$1" == "X--on" ]]; then
		echo "KDAPL will be started on the next startup."
		KDAPL_ENABLED=1
		kdapl_rep_settings
		exit 0
	elif [[ "X$1" == "X--off" ]]; then
		echo "KDAPL won't be started on the next startup."
		KDAPL_ENABLED=0
		kdapl_rep_settings
		exit 0
	 else
                echo "Wrong argument for this option"
                echo ""
                usage
                exit 1
        fi
}

#path_quary sending enable/disable option
function option--path-query()
{
	if [[ -z "$1" ]]; then
                echo "Argument is missing for this option"
		echo ""
                usage
                exit 1
	elif [[ "X$1" == "X--on" ]]; then
		echo "This will enable dynamic path queries on the next startup"
		rep-set modules/ib-arp-table sa-queries 0x00000001
                rep_mset voltaire/modules/ib-arp-table/ sa-queries 0x00000001
		echo sa_queries on > /proc/voltaire/ib-arp-table/control
		exit 0
	elif [[ "X$1" == "X--off" ]]; then
		echo "This will disable dynamic path queries and eanble static path queries on the next startup"
                rep-set modules/ib-arp-table sa-queries 0x00000000
                rep_mset voltaire/modules/ib-arp-table/ sa-queries 0x00000000
                echo sa_queries off > /proc/voltaire/ib-arp-table/control

		exit 0
        else
		echo "Wrong argument for this option"
		echo ""
                usage
                exit 1
	fi
}

#join_arp_failure enable/disable
function option--join_arp_failure()
{ 
       if [[ -z "$1" ]]; then
                echo "Argument is missing for this option"
                echo ""
                usage
                exit 1
        elif [[ "X$1" == "X--on" ]]; then
                echo "This will enable join sending after an arp failure"
		JOIN_ARP_FAILURE=1
		set_join_arp_failure
                exit 0
        elif [[ "X$1" == "X--off" ]]; then
                echo "This will disable join sending after an arp failure"
		JOIN_ARP_FAILURE=0
                set_join_arp_failure
                exit 0
        else
                echo "Wrong argument for this option"
                echo ""
                usage
                exit 1
	fi
}

#set work mode to minism or VFM
function option--work-mode()
{
        if [[ -z "$1" ]]; then
                echo "Argument is missing for this option"
                echo ""
                usage
                exit 1
        elif [[ "X$1" == "X--minism" ]]; then
		if [[ ! -z "$2" ]]; then
			if [[ "X$2" == "X--ats-on" ]]; then
                		echo "This will set work mode to minism with ATS enable for the next startup"
				ATS_ENABLE="yes"
				set_minism_parameters
                		exit 0
			elif [[ "X$2" == "X--ats-off" ]]; then
				echo "This will set work mode to minism with ATS disable for the next startup"
                        	ATS_ENABLE="no"
                        	set_minism_parameters
                        	exit 0
			else 
				echo "Wrong option"
				usage
				exit 1
			fi
		else 
			echo "This will set work mode to minism with ATS enable for the next startup"
                        ATS_ENABLE="yes"
                        set_minism_parameters
                        exit 0
		fi
	elif [[ "X$1" == "X--VFM" ]]; then
                echo "This will set work mode to VFM for the next startup"
		set_VFM_parameters
		exit 0
        else
                echo "Wrong argument for this option"
                echo ""
                usage
                exit 1
        fi
}

#set static path
function option--set_stat_path()
{
	echo setstaticpath $1 $2 $3 $4 $5 $6 $7 $8 ${9} ${10} ${11} ${12}  > /proc/voltaire/ib-arp-table/control
        rep-set modeles/ib-arp-table raw_traffic $(printf "0x%08x" $1)
        rep_mset voltaire/modules/ib-arp-table/ raw_traffic $(printf "0x%08x" $1)
	
	rep-set modules/ib-arp-table flow_lbl $(printf "0x%08x" $2)
        rep_mset voltaire/modules/ib-arp-table/ flow_lbl $(printf "0x%08x" $2)
	
	rep-set modules/ib-arp-table hop_lmt $(printf "0x%08x" $3)
        rep_mset voltaire/modules/ib-arp-table/ hop_lmt $(printf "0x%08x" $3)

	rep-set modules/ib-arp-table traffic_cls $(printf "0x%08x" $4)
        rep_mset voltaire/modules/ib-arp-table/ traffic_cls $(printf "0x%08x" $4)

	rep-set modules/ib-arp-table pkey $(printf "0x%08x" $5)
        rep_mset voltaire/modules/ib-arp-table/ pkey $(printf "0x%08x" $5)
	
	rep-set modules/ib-arp-table sl_mask $(printf "0x%08x" $6)
        rep_mset voltaire/modules/ib-arp-table/ sl_mask $(printf "0x%08x" $6)
	
	rep-set modules/ib-arp-table mtu_sel $(printf "0x%08x" $7)
        rep_mset voltaire/modules/ib-arp-table/ mtu_sel $(printf "0x%08x" $7)
	
	rep-set modules/ib-arp-table mtu $(printf "0x%08x" $8)
        rep_mset voltaire/modules/ib-arp-table/ mtu $(printf "0x%08x" $8)
	
	rep-set modules/ib-arp-table rate_sel $(printf "0x%08x" ${9})
        rep_mset voltaire/modules/ib-arp-table/ rate_sel $(printf "0x%08x" ${9})
	
	rep-set modules/ib-arp-table rate  $(printf "0x%08x" ${10})
        rep_mset voltaire/modules/ib-arp-table/ rate  $(printf "0x%08x" ${10})
	
	rep-set modules/ib-arp-table pkt_life_time_sel $(printf "0x%08x" ${11})
        rep_mset voltaire/modules/ib-arp-table/ pkt_life_time_sel $(printf "0x%08x" ${11})
	
	rep-set modules/ib-arp-table pkt_life_time $(printf "0x%08x" ${12})
        rep_mset voltaire/modules/ib-arp-table/  pkt_life_time $(printf "0x%08x" ${12})
	
	exit 1
}

#SM Heart Beat Join - Setting time interval that Host will send join to SM 

function option--heart-beat-join()
{
	if [ ! -z "$1" ]; then
		if [ ! -z "$2" ]; then	
			if [[ (( $2 -lt 1)) || (( $2 -gt 100 )) ]]; then
				echo "Skew should be between 1 and 100"
				exit 1
			else 
				echo This will set sm heart beat to $1 and skew to $2
		  		echo ""
				INTERVAL_JOIN=$1
				SKEW_JOIN=$2
				set_heart_beat_join		
				exit 0
			fi	
		else
			echo This will set sm heart beat to $1 and skew to 0
                        echo ""
			INTERVAL_JOIN=$1
                        SKEW_JOIN=0
			set_heart_beat_join
                        exit 0                                                                                                    
		fi
	else
		echo "Arguments are missing. You must specify at least an interval"
		usage
	        exit 1  			
          fi
}
                                                                                                                            
#SM Heart Beat ATS - Setting time interval that Host will send ATS to SM
function option--heart-beat-ats()
{
        if [ ! -z "$1" ]; then
                if [ ! -z "$2" ]; then
                        if [[ (( $2 -lt 1)) || (( $2 -gt 100 )) ]]; then
                                echo "Skew should be between 1 and 100"
                                exit 1
                        else
                                echo This will set sm heart beat to $1 and skew to $2
                                echo ""
                                INTERVAL_ATS=$1
                                SKEW_ATS=$2
                                set_heart_beat_ats
                                exit 0
                        fi
                else
                        echo This will set sm heart beat to $1 and skew to 0
                        echo ""
                        INTERVAL_ATS=$1
                        SKEW_ATS=0
                        set_heart_beat_ats
                        exit 0                                                                                                                             
                fi
        else
                echo "Arguments are missing. You must specify at least an interval"
                usage
                exit 1
          fi
}

#Set the number of arp retries (path retries)
function option--set_arp_retries()
{
	if [ ! -z "$1" ]; then
		ARP_RETRIES=$1
		set_arp_retries
		echo "This will set the number of the arp retries to $1"
		exit 0 
	else
		echo "Arguments are missing. You must specify the number of the arp retries"
		usage
		exit 1
	fi
}
		
#This query wil return HCA type, firmware and bus type
function option--query_hca()
{
	#Mellnox args
	#-------------
	MLX_Manufac_id="001"
	
	#Sanmina args
	#-----------
 	Sanmina_Manufac_id="002"

	#Check HCA existence
	if [[ $NUM_HCAS -eq 0 ]]; then
                echo "There is no HCA"
		exit 0
	fi
 
	for(( hca_num=1;$hca_num<=$NUM_HCAS;hca_num++ ))
    	do
		#check HCA_TYPE
		get_hca_vsd $(($hca_num-1))

	 	
		if [ -e $VSD2_Manufacture ]; then
        		HCA_TYPE="UNKNOWN"
		elif [ "$VSD_HP" == "HP" ]; then
			HCA_TYPE="HP" 
		elif [ $VSD2_Manufacture == $MLX_Manufac_id ]; then
			HCA_TYPE="MLX"
		elif [ $VSD2_Manufacture == $Sanmina_Manufac_id ]; then
			HCA_TYPE="SANMINA"
		else
			HCA_TYPE="UNKNOWN"
		fi
		
		echo HCA$hca_num: HCA_TYPE = $HCA_TYPE FW_VER = ${FW_VER[$hca_num]} BUS_TYPE = ${BUS_TYPE[$hca_num]}
	done
	
	exit 1
}

#This query will return stack configuration
function option--query_config()
{		
	Hostname=$(hostname)
	
	if [[ "$OS" == "Darwin" ]]; then
        	cd /usr/voltaire/scripts;
        	AUTOSTART=$(if [ ibhost.apple.auto.init  -ef ibhost.init ] ; then echo on ;else echo off ; fi)
		SM=VFM
	else
        	AUTOSTART=$(if chkconfig --list voltaireibhost 2>/dev/null | grep -q :on ; then echo on ;else echo off ; fi)
		SM=$(rep-get modules/subnet-manager type )
		ATS_MODE=$(rep-get modules/ats active_mode | perl -ne 'print hex')
		if [[ $ATS_MODE -eq 1 ]] ; then
                	ATS="Enable"
        	else
                	ATS="Disable"
        	fi

    	fi

	STACK_VER=$(rpm -qa | grep ibhost)
	
	PATH_QUERY_ENABLED=$(rep-get modules/ib-arp-table sa-queries | perl -ne 'print hex')
	if [[ $PATH_QUERY_ENABLED -eq 1 ]] ; then
                PATH_QUERY="Dynamic"
        else
                PATH_QUERY="Static"
        fi

	check_existance_SDP
	if [[ "$SDPOPTION" == "SDP" ]]; then	
		SDP_ENABLED=$(rep-get modules/sdp enabled | perl -ne 'print hex')	
  		if [[ $SDP_ENABLED -eq 1 ]] ; then 
			SDP="Active"
		else 	
			SDP="Not Active" 
		fi
	else
		SDP="Not Installed"
	fi

	check_existance_KDAPL
	if [[ "$KDAPLOPTION" == "kDAPL" ]]; then
		KDAPL_ENABLED=$(rep-get modules/kdapl enabled | perl -ne 'print hex')
		if [[ $KDAPL_ENABLED -eq 1 ]] ; then
                	KDAPL="Active"
        	else
                	KDAPL="Not Active"
        	fi
	else
		KDAPL="Not Installed"
	fi

	JOIN_HERT_BEAT=$(rep-get modules/ipoib-ud sm-heart-beat | perl -ne 'print hex')
	JOIN_SKEW=$(rep-get modules/ipoib-ud sm-heart-beat-skew | perl -ne 'print hex')

	ATS_HEART_BEAT=$(rep-get modules/ats sm-heart-beat | perl -ne 'print hex')
	ATS_SKEW=$(rep-get modules/ats sm-heart-beat-skew | perl -ne 'print hex')
	
	JOIN_ARP_FAILURE_ENABLE=$(rep-get modules/ipoib-ud join_arp_failure |  perl -ne 'print hex')
	if [[ $JOIN_ARP_FAILURE_ENABLE -eq 1 ]] ; then
                JOIN_ARP_FAILURE="Enable"
        else
                JOIN_ARP_FAILURE="Disable"
        fi
	
	NUM_ARP_RETRIES=$(rep-get modules/ib-arp-table path_retries | perl -ne 'print hex')
	
	echo "Hostname: 		$Hostname"
	echo "Stack version: 		$STACK_VER"
	for(( hca_num=1;hca_num<=$NUM_HCAS;hca_num++ ))
    	do
        	echo -n  "HCA$hca_num Ports status:"
        	for(( port_num=1;port_num<=${NUM_PORT[$hca_num]};port_num++ ))
        	do
                	index=$(($((${NUM_PORT[$hca_num]}*$(($hca_num-1))+$port_num))-1))
                	if [[ $port_num -eq 1 ]]; then
                        	echo -en "\tPORT$port_num - ${IBPORT[$index]}"
                	else
                        	echo -en "\tPORT$port_num - ${IBPORT[$index]}"
                	fi
        	done
		echo ""
	done
	echo "Autostart:		$AUTOSTART"
	echo "Work mode:		$SM" 	 
	echo "ATS:			$ATS" 
	echo "SDP: 			$SDP"
	echo "KDAPL:			$KDAPL"
	echo "Path Query: 		$PATH_QUERY"
	echo "join_arp_failure: 	$JOIN_ARP_FAILURE"
	echo "arp_retries:		$NUM_ARP_RETRIES"
	echo "sm-join-heart-beat:	$JOIN_HERT_BEAT		join-skew:	$JOIN_SKEW"
	echo "sm-ats-heart-beat:	$ATS_HEART_BEAT		ats-skew:	$ATS_SKEW"
	exit 1
}

function option--unreg_dev()
{
       if [[ "$1" == "--yes" ]]; then
               NOT_UNREG_DEV=0
       elif [[ "$1" == "--no" ]]; then
               NOT_UNREG_DEV=1
       else
               echo $1 wrong option
               sleep 1
               usage
               exit
       fi

       set_unreg_dev
       exit
}

function option--add_interface()
{
	if [[ "pkey"=="$1" ]]; then
		if [[ ! -z $2 ]]; then 
			add_interface 0 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12}
		else
			echo "You should insert pkey_num"
			usage
			exit
		fi
	else
		echo "Wrong option"
		usage
		exit
	fi
}

function option--delete_interface()
{
	delete_interface 0 $1
}

####################################################################################################
#MAIN

    
    if  [[ `/usr/mellanox/bin/vapi status | grep "Error" | wc -l` -ne 0 ]] ; then
        VAPI_FLAG=1
    else
        VAPI_FLAG=0
    fi

    declare -a IBPORT
    declare -a NUM_PORT
    declare -a FW_VER
    declare -a BUS_TYPE
        
    if [[ `lsmod | grep mod_ib_mgt |wc -l` -eq 1 ]]; then
	NUM_HCAS=2
    else                                                                   
 	NUM_HCAS=`/usr/mellanox/bin/vapi status | grep hca_id | wc -l`
    fi
#set $(/usr/mellanox/bin/vapi status | perl -ne 'chomp;s/^\s*//;@f=split/[ =]+/;print"$f[1]\n"if/port_state=/') > /dev/null 2>&1

    for(( hca_num=1;hca_num<=$NUM_HCAS;hca_num++ ))
    do
	 HCA_NAME=`/usr/mellanox/bin/vapi status | awk -F "=" '/hca_id/{print $2}' | awk 'NR=='$hca_num'{print}' | grep InfiniHost_III`
	if  [[ $VAPI_FLAG -eq 1 ]] ; then
		if [[ $HCA_NAME == "InfiniHost_III_Lx$(($hca_num-1))" ]]; then
			NUM_PORT[$hca_num]=1
		else
			NUM_PORT[$hca_num]=2
		fi
	else
        	NUM_PORT[$hca_num]=`/usr/mellanox/bin/vapi status | awk -F "=" '/num_phys_ports/ {print $2}' | awk 'NR=='$hca_num'{print}'`
	fi

	for(( port_num=1;port_num<=${NUM_PORT[$hca_num]};port_num++ ))
        do
                if [[ $VAPI_FLAG -eq 1 ]] ; then
                        index=$(($((${NUM_PORT[$hca_num]}*$(($hca_num-1))+$port_num))-1))
                        IBPORT[$index]="PORT_DOWN"
                else
                        index=$(($((${NUM_PORT[$hca_num]}*$(($hca_num-1))+$port_num))-1))
                        IBPORT[$index]=`/usr/mellanox/bin/vapi status | awk -F "=" '/port_state/ {print $2}' | awk 'NR=='$(($index+1))'{print}'`
                fi
        done
        
	                                                                                                                    
        FW_VER[$hca_num]=`/usr/mellanox/bin/vapi status | awk -F "=" '/fw_ver/ {print $2}' | awk 'NR=='$hca_num' {print}'`
	BUS_TYPE[$hca_num]=$(verify_hca_pci_type $(($hca_num-1)))
    done

if [[ $1 ]]; then

	CASE_OPTION=$1
	case $CASE_OPTION in
        	"-d")
                	option-d
        	;;
        	"--burn_hca")
                	option--burn_hca $2 $3 $4 $5 $6
        	;;
        	"--config")
                	option--config $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13}
        	;;
		"--add_interface")
			option--add_interface $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13} 
		;;
		"--delete_interface")
			option--delete_interface $2
		;;
        	"--sdp")
                	option--sdp $2
        	;;
        	"--kdapl")
                	option--kdapl $2
        	;;
        	"--path-query")
                	option--path-query $2
        	;;
        	"--set-stat-path")
			if [[ $# -ne 13 ]]; then
                	echo Number of arguments is $(($#-1)) and should be 12
                	echo ""
                	usage
                	exit 1
        		fi
			option--set_stat_path $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13}
        	;;
        	"--heart-beat-ats")
                	option--heart-beat-ats $2 $3
        	;;
        	"--heart-beat-join") 
                	option--heart-beat-join $2 $3
        	;;
        	"--join_arp_failure")
                	option--join_arp_failure $2
        	;;
        	"--query_hca")
                	option--query_hca
        	;;
        	"--query_config")
                	option--query_config
        	;;
        	"--work-mode")
                	option--work-mode $2 $3
        	;;
        	"--set_arp_retries")
                	option--set_arp_retries $2
        	;;
               "--unreg_dev")
                       option--unreg_dev $2
               ;;
        	*)      usage
                exit 1
        	;;
	esac
fi

sleep 1
                                                                                                                            
while true ; do
    # Gather information
    for ((i=0;i<64;i++))
    do
    	pkey=$(rep-get interfaces/ipoib-ud pkey$i | perl -ne 'print hex')
        if [[ $pkey -ne 0 ]]; then
        	IPOIB_UD[$i]='ipoib'$i
        else
                IPOIB_UD[$i]=""
        fi
    done

    if [[ "$OS" == "Darwin" ]]; then
        cd /usr/voltaire/scripts;
        IBAUTOSTART=$(if [ ibhost.apple.auto.init  -ef ibhost.init ] ; then echo on ;else echo off ; fi)
    else
        IBAUTOSTART=$(if chkconfig --list voltaireibhost 2>/dev/null | grep -q :on ; then echo on ;else echo off ; fi)
    fi
    IBSMENABLE=$(rep-get modules/subnet-manager enabled | perl -ne '$e=hex; if ($e){print "on"}else{print "off"}')
    for (( i=0; i<64; i++ ))
    do
	if [[ ${IPOIB_UD[$i]} == ipoib$i ]]; then
    		DHCP_MODE_ARR[$i]=$(rep-get interfaces/ipoib-ud dhcp_mode_on$i | perl -ne 'print hex') 
	fi
    done
    
    
    ipoib_get_if_data_all LIP LNM LBR LMTU 
    ALIP=""
    ALNM=""
    ALBR=""
    AMTU=""

    case "${OS}" in
        Darwin)
        IPOIB_UD=`ifconfig |  awk -F: '/ipoib-ud/ {print $1}'`
        ;;
        *)
        ;;
    esac


    if [ ${IPOIB_UD} ];
    then
        case "${OS}" in
        Darwin)
        ALIP=$(ifconfig ${IPOIB_UD} 2>/dev/null | perl -ne 'print "$1\n"if/inet \s*(\S+)/i')
        ALNM=$(ifconfig ${IPOIB_UD} 2>/dev/null | perl -ne 'print "$1\n"if/netmask \s*(\S+)/i')
        ALBR=$(ifconfig ${IPOIB_UD} 2>/dev/null | perl -ne 'print "$1\n"if/broadcast \s*(\S+)/i')
        AMTU=$(ifconfig ${IPOIB_UD} 2>/dev/null | perl -ne 'print "$1\n"if/mtu \s*(\S+)/i')
        ;;
        *)
	
	for ((i=0;i<64;i++)) 
	do
		if [[ ${IPOIB_UD[$i]} == ipoib$i ]]; then
        		ALIP_ARR[$i]=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/inet addr:\s*(\S+)/i')
        		ALNM_ARR[$i]=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/mask:\s*(\S+)/i')
        		ALBR_ARR[$i]=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/bcast:\s*(\S+)/i')
        		AMTU_ARR[$i]=$(ifconfig ${IPOIB_UD[$i]} 2>/dev/null | perl -ne 'print "$1\n"if/MTU:\s*(\S+)/i')
		fi
	done
        ;;
        esac
    fi

#in case ats is used as address resolver (ipoib module is not loaded), update network details from repository
   if  (! (lsmod |grep ipoib) > /dev/null && lsmod |grep ats > /dev/null );
   then
	if [[ "$OS" == "Darwin" ]]; then
		ALIP=$LIP  
		ALNM=$LNM
		ALBR=$LBR
		AMTU=$LMTU
   	else
		for ((i=0;i<64;i++))
		do
			if [[ ${IPOIB_UD[$i]} == ipoib$i ]]; then
				ALIP_ARR[$i]=${LIP_ARR[$i]}
				ALNM_ARR[$i]=${LNM_ARR[$i]}
                		ALBR_ARR[$i]=${LBR_ARR[$i]}
                		AMTU_ARR[$i]=${LMTU_ARR[$i]}
			fi
		done
    	fi
    fi
    
    ASM_TYPE=$(rep-get modules/subnet-manager type )
    
    for (( i=0; i<64; i++ ))
    do
	if [[ ${IPOIB_UD[$i]} == ipoib$i ]]; then
    		if [[ ${DHCP_MODE_ARR[$i]} -eq 1 ]]; then
			LIP_ARR[$i]="DHCP"
			LNM_ARR[$i]=""
			LBR_ARR[$i]=""
			LMTU_ARR[$i]=""
    		fi
	fi
    done
        
    exec 1>/dev/null

    PATH_QUERY_ENABLED=$(rep-get modules/ib-arp-table sa-queries | perl -ne 'print hex')
    if [[ $PATH_QUERY_ENABLED -eq 1 ]] ; then
    	PATH_QUERY="Dynamic"
    else
    	PATH_QUERY="Static"
    fi

    NUM_ARP_RETRIES=$(rep-get modules/ib-arp-table path_retries | perl -ne 'print hex')
    
    ATS_MODE=$(rep-get modules/ats active_mode | perl -ne 'print hex')
    if [[ $ATS_MODE -eq 1 ]] ; then
    	ATS="Enable"
    else
        ATS="Disable"
    fi

    exec 1>/dev/tty
    #sleep 2
    # Show System information.
    clear
    echo "====== Voltaire HCA400 InfiniBand Stack Setup  ======"
    echo "Version:          $xver"
    echo -n "System:           kernel version: $(uname -r)"
    if [[ "$OS" == "Darwin" ]]; then
        echo ""
    else
        echo ", memory $(free -m | awk '/Mem/{print $2}')MB."
    fi
    echo "Hostname:         $(hostname)."
    if [[ "$OS" == "Darwin" ]]; then
        echo "IB configuration: AutoStart: $IBAUTOSTART, SM: VFM."
    else
        echo "IB configuration: AutoStart: $IBAUTOSTART, SM: $ASM_TYPE, ATS: $ATS, Path Query: $PATH_QUERY, ARP Retries: $NUM_ARP_RETRIES"
    fi
    echo ""    
    for(( hca_num=1;hca_num<=$NUM_HCAS;hca_num++ ))
    do
    	echo "HCA$hca_num "
	echo "=====" 
	echo -n "Ports status:" 
	for(( port_num=1;port_num<=${NUM_PORT[$hca_num]};port_num++ ))
        do
                index=$(($((${NUM_PORT[$hca_num]}*$(($hca_num-1))+$port_num))-1))
		if [[ $port_num -eq 1 ]]; then
                	echo -e "\t$port_num - ${IBPORT[$index]}"
		else
			echo -e "\t\t$port_num - ${IBPORT[$index]}"
		fi
	done
	echo "Firmware version: ${FW_VER[$hca_num]}"
	echo "Bus Type: ${BUS_TYPE[$hca_num]}"
	echo ""
    done

    for ((i=0;i<64;i++)) 
    do
	 if [[ ${IPOIB_UD[$i]} == ipoib$i ]]; then 
	    	if [[ -e /usr/bin/printf ]]; then
        		printf '           %-16s \t %s\n' "IPoIB$i (config)" "IPoIB$i (active)"
        		printf 'ip-addr:   %-16s \t %s\n' "${LIP_ARR[$i]}" "${ALIP_ARR[$i]}"
        		printf 'netmask:   %-16s \t %s\n' "${LNM_ARR[$i]}" "${ALNM_ARR[$i]}"
        		printf 'broadcast: %-16s \t %s\n' "${LBR_ARR[$i]}" "${ALBR_ARR[$i]}"
			printf 'mtu:       %-16s \t %s\n' "${LMTU_ARR[$i]}" "${AMTU_ARR[$i]}"
    		else
        		echo   "           IPoIB (config) 		 IPoIB (active)"
       			echo   "ip-addr:   ${LIP_ARR[$i]} 		 ${ALIP_ARR[$i]}"
        		echo   "netmask:   ${LNM_ARR[$i]} 		 ${ALNM_ARR[$i]}"
	        	echo   "broadcast: ${LBR_ARR[$i]} 		 ${ALBR_ARR[$i]}"
			echo   "mtu:       ${LMTU_ARR[$i]} 		 ${AMTU_ARR[$i]}"
    		fi
	fi
    done
    
    
    echo

    # Menu & Actions
    # Update Status SDP_Setup Uninstall Exit
    select c in $AUTOSTART IPoIB Partition $FABRICOPTIONS $FIRMWAREUPDATE Start Stop $MPIOPTIONS $SDPOPTION $KDAPLOPTION $EXTRAOPTIONS Exit
    do
        case $c in
        Auto-start)
            autostart_config
            break
        ;;
        IPoIB)
            ipoib_config
            break
        ;;
	Partition)
	    partitioning_menu
	    break
	;; 
        IB-SM)
            ibsm_config
            break
        ;;
        Firmware-update)
            ib_firmware
            break
        ;;
        Start)
            ib_start
            break
        ;;
        Stop)
            ib_stop
            break
        ;;
        IB-rescan)
            ib_rescan
            break
        ;;
	Log-levels)
	    set_log_levels
            break
        ;;
        Join-MCG)
            set_join_multicast_group
            break
        ;;
        Fabric)
            fabric_related_prameters
            break
        ;;
        uCM)
            ucm_settings
            break
        ;;
        kDAPL)
            kdapl_settings
            break
        ;;
        SDP)
            sdp_menu
            break
        ;;
        ATS)
            ats_settings
            break
        ;;
	MPI)
	    mpi_select
	    break
	;;
	Backward-compatible)
	    set_backward_comp
	    break
	;;
	SM-heart-beat-join)
	    sm_heart_beat_join
	    break
	;;
	SM-heart-beat-ats)
            sm_heart_beat_ats
            break
        ;;
	Join-arp-failure)
	    join_arp_failure
  	    break
	;;
	Arp-retries)
	    arp_retries
	    break
	;;
       Not-UnregDev)
           not_unreg_dev
           break
       ;;
        Exit)
            exit 0
        ;;
        *)
            echo "Choose a number from the above range."
            usleep 300000
            break
        ;;
        esac
    done
done
exit 0
