#!/bin/bash
################################################################################
# Version: 1.4
# Date: 19/10/2017
# Last update:
#  - Fix bug if /etc/hosts contain comments # at the beginning of the line
#  - Support ClearSee and get the management I/F from environment parameter
#  - Support DHCP, to get port name from IP address using the command
#     ip a | grep $CurrentHostIP | grep -o '[^ ]*$'
#  - change 'hostname -f' to 'uname -n'
#  - Fix to support all interfaces e* and b* (ifcfg-{e,b}*)
# Date: 08/10/2018
# Last update:
#  - Fix bug for case 236515, support for subnet interface (line 51)
#
# Allot Boxkey extraction
# The script return the boxkey number according to host I/F
################################################################################
set -o pipefail
RCODE=0
kickstartVersion=`/opt/admin/bin/allottype | head -n 1`
CurrentMNG=$MANAGEMENT_IF # Get the MGMNT I/F from environment parameter

if [ -z $CurrentMNG ] ; then # if not Environment parameter exits for the MGMT I/F
    # Get the host name
    HOSTFULL=`uname -n 2>/dev/null`
    if [ $? -ne 0 ] ; then
        echo 'Hostname not defined correctly in /etc/hosts.' $kickstartVersion
        exit 1
    fi

    # Get Host IP address
    CurrentHostIP=`grep -v '^[[:space:]]*#' /etc/hosts 2>/dev/null | grep $HOSTFULL | egrep -v "^::1|127.0.0.1" | awk  -F " " '{print $1}' | head -1 2>/dev/null`
    if [ $? -ne 0 ] ; then
        echo 'Hostname not defined correctly in /etc/hosts.' $kickstartVersion
        exit 1
    fi

    # Get the physical port of the MNGT I/F
    CurrentMNG=`grep -l $CurrentHostIP /etc/sysconfig/network-scripts/ifcfg-* 2>/dev/null | head -1 2>/dev/null | awk  -F "-" '{print $3}' 2>/dev/null`
    if [ $? -ne 0 ] ; then
        # Check if this IP is in other I/F for DHCP cases
    #    CurrentMNG=`ip a | grep $CurrentHostIP | grep -o '[^ ]*$'`
        CurrentMNG=`ip -o a | grep $CurrentHostIP | awk '{print $2}'`
        if [ -z $CurrentMNG ] ; then
            echo 'Management port not defined correctly.' $kickstartVersion
            exit 1
        fi
    fi
fi

# Check if the physical port of the MNGT I/F contain special character i.e. subnet interface
if [ `expr "$CurrentMNG" : ".*[!:@#\$%^\&*()_+.].*"` -gt 0 ];
    then
        HWADDR=`ip addr show $CurrentMNG | awk '/ether/ {print $2}'`
    else
        HWADDR=`cat /sys/class/net/$CurrentMNG/address 2>/dev/null`
fi

# Get the MAC of the MNGT
#HWADDR=`cat /sys/class/net/$CurrentMNG/address 2>/dev/null`
if [ $? -ne 0 ] ; then
    echo "Could not find Management MAC address for $CurrentMNG." $kickstartVersion
    exit 1
fi

BKH=`echo $HWADDR | awk -F ":" '{print $6$5$4"00"}'`
#echo "Return=$BKH"
printf "%d\n" 0x$BKH