#! /usr/bin/env python

import json
import subprocess
from argparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument('-n', '--namespace',
                    dest='namespace',
                    help='network namespace for the link to modify'
                    )
parser.add_argument('-d', '--device',
                    dest='device',
                    help='device to modify'
                    )
parser.add_argument('-B', '--bandwidth',
                    dest='bandwidth',
                    help='bandwidth to set'
                    )
parser.add_argument('-D', '--delay',
                    dest='delay',
                    help='link latency'
                    )
parser.add_argument('-L', '--loss',
                    dest='loss',
                    help='loss rate'
                    )

args = parser.parse_args()

errs = False
if args.device is None:
    print 'You must specify a device with --device.'
    errs = True
if args.namespace is None:
    print 'You must specify a network namespace with --namespace.'
    errs = True
if errs:
    print 'Run with --help for invocation syntax'
    exit(1)

# Enable network emulation on the device.
cmd = ["sudo", "/sbin/ip",
       "netns", "exec", args.namespace,
       "tc", "qdisc", "change", "dev", args.device, "root",
       "netem"]

if args.delay is not None:
    cmd.append("delay")
    cmd.append(str(args.delay))
if args.bandwidth is not None:
    cmd.append("rate")
    cmd.append(str(args.bandwidth))
if args.loss is not None:
    cmd.append("loss")
    cmd.append(str(args.loss))

subprocess.check_output(cmd,stderr=subprocess.STDOUT)