#!/bin/bash
# $Id: ip_create_br 873 2017-04-14 11:56:29Z mueller $
#
# Copyright 2017- by Walter F.J. Mueller <W.F.J.Mueller@gsi.de>
# License disclaimer see License.txt in $RETROBASE directory
#
#  Revision History:
# Date         Rev Version  Comment
# 2017-04-14   873   1.0    Initial version
# 2017-03-04   858   0.5    First draft
#

# some preparations
defeif=$(ip_inspect defeif)

if [[ -z $defeif ]]; then
  echo "ip_create_br-I: default interface not found"
  exit 1
fi

hostaddr=$(ip_inspect addr4 $defeif addr)
hostmask=$(ip_inspect addr4 $defeif mask)
hostbcast=$(ip_inspect addr4 $defeif bcast)
hostdgway=`route -n | grep ^0.0.0.0 |\
          gawk -- '{ print $2 }'`

if [[ -z "$hostaddr" || -z "$hostmask" || -z "$hostbcast" || -z "$hostdgway" ]]
then 
  echo "ip_create_br-E: failed to determine current setup"
  exit 1
fi

# echo  $defeif
# echo  $hostaddr
# echo  $hostmask
# echo  $hostbcast
# echo  $hostdgway

# sanitize PATH, use what sudo has
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

which_ip=$(which ip)
which_ifconfig=$(which ifconfig)
which_brctl=$(which brctl)
which_route=$(which route)

if [[ -z "$which_ip" || -z "$which_ifconfig" ||
      -z "$which_brctl" || -z "$which_route" ]]
then 
  echo "ip_create_br-E: ip, ifconfig, brctl, or route not in PATH"
  exit 1
fi

if $which_ifconfig | grep -q "br0\s*Link"
then
  echo "ip_create_br-I: Bridge br0 already exists"
  exit 1
fi

# print info so that sudo password prompt is expected
if [[ $(id -u) -ne 0 ]] ; then echo "ip_create_br-I: requires sudo" ; fi

sudo $which_brctl addbr br0
sudo $which_brctl addif br0 $defeif
sudo $which_brctl setfd br0 0
sudo $which_ifconfig $defeif 0.0.0.0
sudo $which_ifconfig br0 $hostaddr netmask $hostmask broadcast $hostbcast up
# set the default route to the br0 interface
sudo $which_route add -net 0.0.0.0/0 gw $hostdgway

#
$which_ifconfig br0
$which_route
