#!/bin/bash
#
# by ymc-dabe
# Takeover a MAC address for an interface
# Warning: This will down/up the interface involved!
#


### Include ymclibnettools
. /usr/lib/lib-fliwi/ymc-networktools.bash || exit 1

ymcCommand=$3
USAGE="usage: $0 mac interface {start|stop|status}";
macToUse=$1
interfaceToUse=$2

send_arp="/usr/lib/heartbeat/send_arp"

usage()
{
    echo $USAGE >&2
}

if [ $# != 3 ]; then
    usage
    exit 1
fi


mac_status()
{
    if [ $(/sbin/ifconfig $interfaceToUse | grep -F "$macToUse" | wc -l) -gt 0 ]; then
      echo "running"
    else
      echo "stopped"
    fi
}

mac_start()
{
  if [ ! -d "/var/lib/fliwi-ha-simple-heartbeat-setup/fliwiMacTakeover" ]; then
    mkdir -p /var/lib/fliwi-ha-simple-heartbeat-setup/fliwiMacTakeover
  fi

  if [ ! -f "/var/lib/fliwi-ha-simple-heartbeat-setup/fliwiMacTakeover/$interfaceToUse.orig-mac" ]; then
    # Remember the original MAC
    cat /sys/class/net/$interfaceToUse/address > /var/lib/fliwi-ha-simple-heartbeat-setup/fliwiMacTakeover/$interfaceToUse.orig-mac
  fi

  # Bring the affected interface offline, so we can change the MAC
  /sbin/ifdown $interfaceToUse

  # Change the MAC
  /sbin/ip link set dev $interfaceToUse address $macToUse

  # Bring the affected interface back online
  /sbin/ifup $interfaceToUse

  if [ -x "$send_arp" ]; then
    interfaceIP=$(ymc_get_field_from_ifconfig $interfaceToUse "inet addr:")
    interfaceNetmask=$(ymc_get_field_from_ifconfig $interfaceToUse "Mask:")
    interfaceBroadcast=$(ymc_get_field_from_ifconfig $interfaceToUse "Bcast:")

    if [ -n "$interfaceIP" ] && \
       [ -n "$interfaceNetmask" ] && \
       [ -n "$interfaceBroadcast" ]; then
      $send_arp -i 1010 -r 5 $interfaceToUse $interfaceIP auto $interfaceBroadcast $interfaceNetmask &
    fi
  fi
}

mac_stop()
{
  # Bring the affected interface offline, so we can change the MAC
  /sbin/ifdown $interfaceToUse

  if [ -f "/var/lib/fliwi-ha-simple-heartbeat-setup/fliwiMacTakeover/$interfaceToUse.orig-mac" ]; then
    originalMAC=$(cat /var/lib/fliwi-ha-simple-heartbeat-setup/fliwiMacTakeover/$interfaceToUse.orig-mac)
    # Change the MAC
    /sbin/ip link set dev $interfaceToUse address $originalMAC

    # Bring the affected interface back online
    /sbin/ifup $interfaceToUse
  fi
}



case $ymcCommand in
  start)        mac_start;;
  stop)         mac_stop;;
  status)       mac_status;;
  *)            usage
                exit 1
                ;;
esac

