#!/bin/bash
#
# by ymc-dabe
# Do some basic ip-switching
#


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

ymcCommand=$4
USAGE="usage: $0 ip netmask interface {start|stop|status}";
ipToUse=$1
netmaskToUse=$2
interfaceToUse=$3

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

usage()
{
    echo $USAGE >&2
}

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


interface_alias=$(ymc_calculate_heartbeat_alias $ipToUse)
if [ $? -ne 0 ]; then
  echo "ERROR: Could not calculate virtual-id out of ip $ipToUse" 1>&2
  continue
fi



ip_status()
{
    if [ $(/sbin/ifconfig | grep -E -e "^$interfaceToUse:$interface_alias" | wc -l) -eq 1 ]; then
      echo "running"
    else
      echo "stopped"
    fi
}

ip_start_stop()
{
  ### Always (try to) take down an IP brought up by old versions of this script
  /sbin/ifconfig $interfaceToUse:$(ymc_caluclated_virtual_id $ipToUse) down 2>/dev/null || true

  ### Take IP online/offline
  /sbin/ifconfig $interfaceToUse:$interface_alias $ipToUse netmask $netmaskToUse $1
}

ip_start()
{
  ip_start_stop up
  if [ -x "$send_arp" ]; then
    $send_arp -i 1010 -r 5 $interfaceToUse $ipToUse auto $(ymc_get_field_from_ifconfig $interfaceToUse "Bcast:") $netmaskToUse &
  fi
}

ip_stop()
{
  ip_start_stop down
}



case $ymcCommand in
  start)        ip_start;;
  stop)         ip_stop;;
  status)       ip_status;;
  *)            usage
                exit 1
                ;;
esac

