#!/bin/bash
#
# iss-nvram-mac        This starts and stops ISS-NVRAM-MAC
#
# chkconfig: 3 25 75
# description: Starts and stops ISS-NVRAM-MAC
#

action() {
  STRING=$1
  echo -n "$STRING"
  shift
  $*
  rc=$?
  if test $rc -ne 0
  then
    echo " - Failure: $rc"
  else
    echo " - Success"
  fi
  return $rc
}
echo_success() {
    echo " - Success"
}
echo_failure() {
    echo " - Failure: $?"
}
failure() {
  echo -n "$* - Failure"
}

RETVAL=0
prog="iss-nvram-mac"

# Main function
start()
{
    BASE_MAC=000`/usr/bin/mlxi2c_bf --master-mode --dontclose -without_modules show fru chassis | grep UID1 | cut -d":" -f 2 | cut -d" " -f 2 | cut -b 1-3,8-13`

    case $BASE_MAC in
        0000 | 000)
        	logger -t iss-nvram-mac "EEPROM BASE_MAC missing, using MAC0 address instead"
                BASE_MAC=`/opt/tms/bin/eetool | grep MAC1 | cut -d"x" -f 2 | cut -d"\"" -f 1`
		;;
        *)
        	logger -t iss-nvram-mac "BASE_MAC taken from EEPROM"
                ;;
    esac
    BASE_MAC_EXP=`echo $BASE_MAC | sed -e "s/../&:/g" | cut -b 1-17`
    logger -t iss-nvram-mac BASE_MAC=$BASE_MAC_EXP

    ISS_CONF_FILE=/var/opt/tms/snapshots/.running/iss/issnvram.txt
    if [ -f $ISS_CONF_FILE ]; then
        sed -i ${ISS_CONF_FILE} -e "s/ff:01:02:03:04:05/${BASE_MAC_EXP}/g"
    fi
}

stop()
{
    echo "Stopping $prog"
}

print_status()
{
    # Check modules
    echo "Modules status"
    echo "--------------"
    for M in switchx mellaggra_mod sx_glue_if
    do
    if  lsmod | grep ${M} > /dev/null
    then
        echo "    ${M} module loaded"
    else
        echo "    ${M} module is not loaded"
    fi
    done
}

# Main body
# See how we were called.
case "$1" in
    help)
        cat <<END

   $0 start

       Start ISS-NVRAM-MAC service..

   $0 stop

       Stop ISS-NVRAM-MAC service.

   $0 restart

       Just like "iss-nvram-mac stop" followed by "iss-nvram-mac start"

   $0 status

       Print current status of Mellanox devices

END
        ;;
    start)
        if [ `id -u` -ne 0 ]; then
            echo "You must be root to do that"
            exit 1
        fi
        start
        ;;
    stop)
        if [ `id -u` -ne 0 ]; then
            echo "You must be root to do that"
            exit 1
        fi
        stop
        ;;
    status)
        print_status
        ;;
    restart)
        if [ `id -u` -ne 0 ]; then
            echo "You must be root to do that"
            exit 1
        fi
        stop
        start
        ;;
    *)
        echo "Usage:"
        echo "    $0 {start|stop|status|restart|help}"
        echo
        echo "Type \"$0 help\" for detailed help"
        RETVAL=1
esac
exit $RETVAL
