#!/bin/bash
#
TC=/sbin/tc

IP=192.168.2.1   # Host IP
myLatency="10ms"
myLoss="6%"
myRate="2mbit"
myIF=enp0s17	    # Interface 

usage () {
   echo "startVMSetup <opcode> <interface> "
   echo "  opcode: {start|stop|restart|NAT|netem|show}"
   echo "  interface:  valid interface name "
   echo "Example:   setupVMRouter.sh start eth0 "
}


startTBF() {

    $TC qdisc add dev $myIF root tbf rate $myRate latency 50ms burst 1540

}

 
startOLD() {

    DNLD=1mbit          # DOWNLOAD Limit
    UPLD=1mbit          # UPLOAD Limit 
    U32="$TC filter add dev $myIF protocol ip parent 1:0 prio 1 u32"
    $TC qdisc add dev $myIF root handle 1: htb default 30
    $TC class add dev $myIF parent 1: classid 1:1 htb rate $DNLD
    $TC class add dev $myIF parent 1: classid 1:2 htb rate $UPLD
    $U32 match ip dst $IP/32 flowid 1:1
    $U32 match ip src $IP/32 flowid 1:2

}

stop() {

    $TC qdisc del dev $myIF root
    tc qdisc show

}

restart() {

    stop
    sleep 1
    startTBF

}

show() {
    tc qdisc show
    sysctl net.ipv4.conf.all.forwarding
    iptables -L
}

# ensure 3 args were passed
if [ $# -ne 2 ]
  then
   usage
   exit -1
else
  myIF=$2	    # Interface 
fi

echo "setupVMRouter.sh: opcode: $1 IF: $myIF  latency : $myLatency  loss : $myLoss "

case "$1" in


  start)

    echo -n "Starting TBF bandwidth shaping: "
    startTBF
    echo "done"
    ;;

  stop)

    echo -n "Stopping bandwidth shaping: "
    stop
    echo "done"
    ;;


  restart)

    echo -n "Restarting bandwidth shaping: "
    restart
    echo "done"
    ;;

	NAT)

    sudo sysctl net.ipv4.conf.all.forwarding=1
    sudo iptables -t nat -A POSTROUTING -o $myIF -j SNAT --to 192.168.2.1
    echo -n "set ip forwarding and nat  on IF $myIF"
    ;;

	netem)
#    tc qdisc add dev $myIF root netem limit 1000 delay 30ms loss 10% 
     tc qdisc add dev enp0s8 root netem limit 1000 delay $myLatency loss $myLoss
     echo "Setting loss rate of $myLoss latency of $myLatency "
    ;;


  show)
				    
    echo "Bandwidth shaping status for $myIF "
    show
    echo ""
    ;;

  *)

    pwd=$(pwd)
    usage
    ;;

esac

exit 0


