#!/bin/bash
# IBM(c) 2014 EPL license http://www.eclipse.org/legal/epl-v10.html

#-------------------------------------------------------------------------------
#=head1  confignics
#=head2  Used on Linux only. Config the Ethernet or InfiniBand adapters on the nodes
#
#  You can run the following commands on MN:
#       updatenode noderange confignics
#       updatenode noderange "confignics -s" (configures the installation nic by default and no need to configure the install nic in nics table)
#
#
#=cut
#-------------------------------------------------------------------------------


if [ "$(uname -s|tr 'A-Z' 'a-z')" = "linux" ];then
   str_dir_name=`dirname $0`
   . $str_dir_name/xcatlib.sh
fi

if [ -n "$LOGLABEL" ]; then
    log_label=$LOGLABEL
else
    log_label="xcat"
fi

error_code=0
#the nics' information contain:
#1. ip address
#2. nic network
#3. nic type
#4. custom scripts
#all of them are saved by different variable
#this function can split the varable for each nic, and svae the information for each nic
#into an hash, the key is nic name, the value are all information, which joined by ','
function splitconfig(){
    if [ ! "$1" ];then
        return
    fi
    old_ifs=$IFS
    IFS=$','
    array_conf_temp=($1)
    IFS=$old_ifs

    i=0
    while [ $i -lt ${#array_conf_temp[@]} ]
    do
        token="${array_conf_temp[$i]}"
        D=
        if echo "$token" | grep "!"; then
            D="!"
        else
            D=":"
        fi
        key=`echo "$token" | cut -d"$D" -f 1`
        str_temp_value=`echo "$token" | cut -d"$D" -f 2`

        str_temp=$(hashget hash_defined_nics $key)
        if [ -n "$str_temp" ];then
           str_temp=$str_temp",${str_temp_value}"
        else
           str_temp="$str_temp_value"
           str_all_nics=$str_all_nics"$key "
        fi
        hashset hash_defined_nics $key "$str_temp"
        i=$((i+1))
    done
}

function findnetwork(){
    local str_ip=$1
    local str_network=''
    local flag_v6=0
    echo "$str_ip" | grep ':' > /dev/null
    if [ $? -eq 0 ];then
        flag_v6=1
    fi
    local num_i=1
    while [ $num_i -le $NETWORKS_LINES ];do
        eval str_temp=\$NETWORKS_LINE$num_i
        str_net=`echo $str_temp | awk -F'net=' '{print $2}' | awk -F'|' '{print $1}'`
        str_mask=`echo $str_temp | awk -F'mask=' '{print $2}' | awk -F'|' '{print $1}' | sed 's:^/::'`
        if [ ! $str_mask ]; then
            num_i=$((num_i+1))
            continue
        fi
        echo $str_net | grep ':' > /dev/null
        if [ $? -ne 0 ];then
            if [ $flag_v6 -eq 0 ];then
                str_temp_net1=$(v4calcnet $str_ip $str_mask)
                str_temp_net2=$(v4calcnet $str_net $str_mask)
            else
                num_i=$((num_i+1))
                continue
            fi
        else
            if [ $flag_v6 -eq 1 ];then
                str_temp_net1=$(v6calcnet $str_ip $str_mask)
                str_temp_net2=$(v6calcnet $str_net $str_mask)
            else
                num_i=$((num_i+1))
                continue
            fi
        fi

        if [ "$str_temp_net1" = "$str_temp_net2" ];then
        str_network=`echo $str_temp  | awk -F'netname=' '{print $2}' | awk -F'|' '{print $1}'`
            echo "$str_network"
            return
        fi
        num_i=$((num_i+1))
    done
    echo "Error: Can not find a valid network defination for ip address: $str_ip , make sure netname,net and mask are correct in networks table."
    error_code=1
}

function checknetwork(){
    old_ifs=$IFS
    IFS=$'|'
    array_ip=($1)
    IFS=$old_ifs
    str_ret=''

    num_length=${#array_ip[@]}
    num_index=0
    while [ $num_index -lt $num_length ]
    do
        str_ip=${array_ip[$num_index]}
        str_networkname=$(findnetwork $str_ip)
        echo "$str_networkname" | grep -i 'error' > /dev/null
        if [ $? -eq 0 ];then
            echo "$str_networkname"
            return
        fi
        str_ret="${str_ret}${str_networkname}|"

        num_index=$((num_index+1))
    done

    str_ret=`echo $str_ret | sed 's/,$//'`
    echo "$str_ret"
}

bool_cfg_inst_nic=0
str_inst_nic=''
str_ib_nics=''
str_os_type=`uname | tr 'A-Z' 'a-z'`
if [ "$str_os_type" = "aix" ];then
    logger -t $log_label -p local4.err "confignics: aix does not support in this build"
    echo "confignics: aix does not support in this build"
    exit 1
fi
bool_remove=0
num_iba_ports=
str_all_nics=''
for arg in "$@"
do
    if [ "$arg" = "-s" ];then
        bool_cfg_inst_nic=1
    elif [ "$arg" = "-r" ];then
        bool_remove=1
    elif [ "${arg:0:10}" = "--ibaports" ];then
        num_iba_ports=${arg#--ibaports=}
    fi
done

if [ "$SETINSTALLNIC" = "1" ] || [ "$SETINSTALLNIC" = "yes" ]; then
    bool_cfg_inst_nic=1
fi

boot_myscript=0
if [ $# -eq 2 ]
then
    if [ "$1" = "--script" ]
    then
        if [ $bool_cfg_inst_nic -eq 1 -o $bool_remove -eq 1 -o ! -z "$num_iba_ports" ]
        then
            logger -t $log_label -p local4.info "confignics --script <myscript> could Not be used with other options"
            echo "confignics --script <myscript> could Not be used with other options"
            exit 1
        fi
        boot_myscript=1
        myscript=$2;
    fi
fi

logger -t $log_label -p local4.info "confignics is called: config install nic:$bool_cfg_inst_nic, remove: $bool_remove, iba ports: $num_iba_ports"
echo "confignics on $NODE: config install nic:$bool_cfg_inst_nic, remove: $bool_remove, iba ports: $num_iba_ports"

str_temp=''
if [ ! $INSTALLNIC ];then
    str_temp="mac"
else
    str_temp=$INSTALLNIC
fi

if [ "$str_temp" = "mac" ];then
    if [ "$str_os_type" = "aix" ];then
        old_ifs=$IFS
        IFS=$' '
        str_temp=`ifconfig -l`
        array_nicnames_temp=($str_temp)
        IFS=$old_ifs
        for temp_nic in ${array_nicnames_temp[@]}
        do
            entstat -t $temp_nic | grep -i "$MACADDRESS"
            if [ $? -eq 0 ];then
                str_inst_nic=$temp_nic
                break
            fi
        done
    else
       str_inst_nic=`ip -o link | grep -i "$MACADDRESS" | awk '{print $2;}' | sed s/://`
    fi
elif [ `echo $str_temp | grep -E "e(n|th|m)[0-9a-zA-Z]+"` ];then
    str_inst_nic=$str_temp
fi

bool_exit_flag=0
#check the required attributes
if [ -z "$NICIPS" ];then
   if [ $bool_cfg_inst_nic -eq 1 ];then
       logger -t $log_label -p local4.info "confignics: configure the install nic. "
       echo "confignics on $NODE:configure the install nic. "
   else
       logger -t $log_label -p local4.info "confignics: nicips attribute is not defined. "
       echo "confignics on $NODE: nicips attribute is not defined. "
       exit 1
   fi
fi
splitconfig "$NICIPS"
splitconfig "$NICCUSTOMSCRIPTS"



if [ $boot_myscript -eq 1 ];then
    . $str_dir_name/$myscript
    if [ $? -ne 0 ];then
        exit 1
    fi
    exit 0
fi

#get state of nic in "UP" status
#If bonded redhat then "SLAVE" or "MASTER" will be in the first line of stanza
#do not configure the loopback nic
if [ $bool_remove -eq 1 ];then
    if [ "$str_os_type" = "aix" ];then
        str_temp=`ifconfig -a | grep flags | grep -vi loopback | grep -v SLAVE | grep -v MASTER | awk -F: {'print $1'}`
    else
        str_temp=`ip link show | grep -v link | grep -vi loopback | grep -v SLAVE | grep -v MASTER | awk {'print $2'} | sed s/://`
    fi
    old_ifs=$IFS
    IFS=$'\n'
    array_nics_temp=($str_temp)
    IFS=$old_ifs
    for str_temp_nic in ${array_nics_temp[@]}
    do
        #the nic type should be ethernet
        echo $str_temp_nic | grep -E "e(n|th|m)[0-9a-zA-Z]+"
        if [ $? -ne 0 ];then
            continue
        fi
        if [ "$str_os_type" != "aix" ];then
            brctl show 2>/dev/null | grep $str_temp_nic
            #the nic belongs to a bridge, go to next
            if [ $? -eq 0 ];then
                continue
            fi
        fi
        #the nic is defined this time
        str_temp=$(hashget hash_defined_nics $str_temp_nic)
        if [ -n "$str_temp" ];then
            continue
        fi

        if [ "$str_temp_nic" = "$str_inst_nic" ];then
            continue
        fi

        #ignore the vlan interface
        echo $str_temp_nic | grep "\."
        if [ $? -eq 0 ];then
            continue
        fi

        logger -t $log_label -p local4.info "confignics: remove nic $str_temp_nic"
        echo "confignics on $NODE: remove nic $str_temp_nic"
        configeth -r $str_temp_nic
        if [ $? -ne 0 ]; then
            error_code=1
        fi
    done
fi
old_ifs=$IFS
IFS=$' '
if [ $bool_cfg_inst_nic -eq 1 ];then
    str_all_nics=$str_all_nics" "$str_inst_nic
fi
array_nics_temp=($str_all_nics)
IFS=$old_ifs
for key in ${array_nics_temp[@]}
do
    key=`echo $key | sed 's/^ \+//' | sed 's/ \+$//'`
    str_nic_type=
    str_value=$(hashget hash_defined_nics $key)
    old_ifs=$IFS
    IFS=$','
    array_temp=($str_value)
    IFS=$old_ifs

    if [ -n "${array_temp[1]}" ];then
        if [ "$key" = "$str_inst_nic" ] && [ $bool_cfg_inst_nic -ne 1 ];then
            # don't run customized script for installnic if not specify the -s
            continue
        fi
        logger -t $log_label -p local4.info "confignics: processing custom scripts: ${array_temp[1]} for interface $key"
        echo "confignics on $NODE: processing custom scripts: ${array_temp[1]} for interface $key"
        ${array_temp[1]}
    else
        if [ "$key" = "$str_inst_nic" ];then
            if [ $bool_cfg_inst_nic -eq 1 ];then
                logger -t $log_label -p local4.info "confignics: call 'configeth $str_inst_nic'"
                echo "confignics on $NODE: call 'configeth -s $str_inst_nic"
                configeth -s $str_inst_nic
                if [ $? -ne 0 ]; then
                    error_code=1
                fi
                continue
            else
                continue
            fi
        fi
        if [ `echo $key | grep -E 'e(n|th|m)[0-9a-zA-Z]+'` ];then
            str_nic_type="ethernet"
        elif [ `echo $key | grep -E 'ib[0-9]+'` ];then
            str_nic_type="infiniband"
        else
            logger -t $log_label -p local4.info "confignics: unknown nic type for $key: $str_value ."
            echo "confignics on $NODE: unknown nic type for $key: $str_value ."
            error_code=1
            continue
        fi
        str_network=$(checknetwork ${array_temp[0]})
        echo "$str_network" | grep -i 'error' > /dev/null
        if [ $? -eq 0 ];then
            logger -t $log_label -p local4.info "$str_network"
            echo "confignics on $NODE: $str_network"
            continue
        fi
        if [ "$str_nic_type" = "ethernet" ];then
             logger -t $log_label -p local4.info "confignics: call 'configeth $key ${array_temp[0]} $str_network'"
             echo "confignics on $NODE: call 'configeth $key ${array_temp[0]} $str_network'"
             configeth $key ${array_temp[0]} $str_network
             if [ $? -ne 0 ]; then
                 error_code=1
             fi
        elif [ "$str_nic_type" = "infiniband" ];then
            if [ $str_ib_nics ];then
                str_ib_nics=$str_ib_nics","$key
            else
                str_ib_nics=$key
            fi
        else
            logger -t $log_label -p local4.info "confignics: unknown type $str_nic_type for NIC: $key"
            echo "confignics on $NODE: unknown type $str_nic_type for NIC: $key"
            error_code=1
        fi
    fi
done
if [ -n "$str_ib_nics" ];then
    logger -t $log_label -p local4.info "confignics: executed script: configib for nics: $str_ib_nics, ports: $num_iba_ports"
    echo "confignics on $NODE: executed script: configib for nics: $str_ib_nics, ports: $num_iba_ports"
    NIC_IBNICS=$str_ib_nics NIC_IBAPORTS=$num_iba_ports configib
else
    if [ $bool_remove -eq 1 ];then
        logger -t $log_label -p local4.info "confignics: executed script: 'configib -u' to remove all ib nics and configuration files"
        echo "confignics on $NODE: executed script: 'configib -r' to remove all ib nics and configuration files"
        configib
        if [ $? -ne 0 ]; then
            error_code=1
        fi
    fi
fi
exit $error_code
