#!/bin/sh
#
# usage:
#
#  virtual-link.sh <netem-cmd> <namespace-name> <subnet-prefix>
#
# e.g.
#
#  virtual-link.sh "delay 200ms 50ms 50%" abis 10.9.8.
#
# (omit any number of trailing arguments for default values)

netem_cmd="${1:-delay 200ms 50ms 50%}"
ns="${2:-abis}"
link_in="${ns}-in"
link_out="${ns}-out"
subnet_prefix="${3:-10.9.8.}"
addr_out="${subnet_prefix}1"
addr_in="${subnet_prefix}2"
addr_mask_out="${addr_out}/24"
addr_mask_in="${addr_in}/24"

set -e -x

test $USER = root

ip netns add $ns
ip link add $link_in type veth peer name $link_out
ip link set $link_in netns $ns

ip link set $link_out up
ip addr add $addr_mask_out dev $link_out
ip a

ip netns exec abis  ip link set $link_in up
ip netns exec abis  ip link set lo up
ip netns exec abis  ip addr add $addr_mask_in dev $link_in
ip netns exec abis  ip a

tc qdisc add dev $link_out root handle 1:0 netem $netem_cmd
ip netns exec abis  tc qdisc add dev $link_in root handle 1:0 netem $netem_cmd

ping -c 3 $addr_in
ip netns exec abis  ping -c 3 $addr_out

set +x
echo To clean up:  netns delete $ns
