#!/bin/bash

# Script for configuration of network namespace and locking of one pyhsical network interface
# to be used as server listening interface in case server and sampler is running on the same machine.

# This script is launched programatically from Server Emulator plugin in JMeter.
# Possible actions are "add" or "delete"
ACTION="$1"
NETNS_NAME="$2"
LISTEN_INTERFACE="$3"
LISTEN_IP="$4"
PREFIX_LENGTH="24"

if [ $ACTION = "add" ]; then
    # If network namespace with the same name already exists it is deleted
    NS=$(ip netns | grep $NETNS_NAME)
    if [ "$NS" = "$NETNS_NAME" ]; then
	ip netns delete $NETNS_NAME
    fi
    ip netns add $NETNS_NAME &&
    ip netns exec $NETNS_NAME ip link set dev lo up &&
    ip link set dev $LISTEN_INTERFACE netns $NETNS_NAME &&
    ip netns exec $NETNS_NAME ip link set dev $LISTEN_INTERFACE up &&
    ip netns exec $NETNS_NAME ip addr add $LISTEN_IP/$PREFIX_LENGTH dev $LISTEN_INTERFACE
    if [ "$?" = "0" ]; then
	exit 0
    else
	exit 1
    fi
elif [ $ACTION = "delete" ]; then
    NS=$(ip netns | grep $NETNS_NAME)
    if [[ "$NS" == *"$NETNS_NAME"* ]]; then
        if ! ip netns delete $NETNS_NAME; then
	    exit 3
        elif [ "$?" = "0" ]; then
	    exit 0
	else
	    exit 1
	fi
    fi
fi
