#!/bin/bash

### This is a multicall-script - DO NOT CALL IT DIRECTLY!


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

virtual_interface=$1
bridge_device=$(basename $0)
if [ "$bridge_device" == "multicall_network_starter.bash" ]; then
  echo "ERROR: Do not call $0 directly. Instead use a symlink!" 1>&2
  exit 1
fi

if [ $(ymc_contains $bridge_device $(ymc_get_bridge_interfaces)) -eq 0 ]; then
  echo "ERROR: Bridge device $bridge_device does not exists!" 1>&2
  exit 1
fi

if [ $(ymc_interface_exists $virtual_interface) -eq 0 ]; then
  echo "ERROR: The interface $virtual_interface does not exists!" 1>&2
  exit 1
fi

echo "INFO: Bringing up $virtual_interface for bridged mode..." 1>&2
ifconfig $virtual_interface 0.0.0.0 promisc up

# Disable IPv6 on the new interface (it is purely used for layer2 purposes on the host system)
temp_loop_protection=15
while [ ! -e "/proc/sys/net/ipv6/conf/$virtual_interface/disable_ipv6" ]
do
  echo -n -e "\rINFO: Waiting for device '$virtual_interface' to appear..." 1>&2
  if [ $temp_loop_protection -le 0 ]; then
    echo "TIMEOUT - continuing anyway" 1>&2
    break
  fi
  echo -n -e "[$temp_loop_protection] "
  temp_loop_protection=$(expr $temp_loop_protection - 1)
  sleep 1
done
unset temp_loop_protection
if [ -e "/proc/sys/net/ipv6/conf/$virtual_interface/disable_ipv6" ]; then
  echo 1 > /proc/sys/net/ipv6/conf/$virtual_interface/disable_ipv6
fi

echo "INFO: Adding $virtual_interface to bridge '$bridge_device'..." 1>&2
brctl addif $bridge_device $virtual_interface


bridge_port_state_path="/sys/class/net/$virtual_interface/brport/state"
counter=0
max_loops=60
loop_delay="0.5"
fallback_delay_needed=0
if [ -r "$bridge_port_state_path" ]; then
  echo -n "INFO: Waiting for the bridge-port $virtual_interface to enter forwarding state..." 1>&2
  while [ $counter -le $max_loops ]
  do
    counter=$(expr $counter + 1)
    if [ -r "$bridge_port_state_path" ]; then
      if [ "$(cat $bridge_port_state_path)" != "3" ]; then
        echo -n "." 1>&2
      else
        echo "" 1>&2
        echo "INFO: Bridge-port $virtual_interface entered forwarding state..." 1>&2
        break
      fi
    else
      fallback_delay_needed=1
      echo "" 1>&2
      echo "ERROR: Failure in detecting the state of $virtual_interface" 1>&2
      break
    fi
    sleep $loop_delay
  done
else
  fallback_delay_needed=1
fi

if [ $fallback_delay_needed -eq 1 ]; then
  echo "INFO: Sleeping 15 seconds in order to give bridge-port $virtual_interface some time to enter forwarding state..." 1>&2
  sleep 15
fi

exit 0
