#!/bin/bash

set -e

ROOTDIR="$( cd $( dirname $0 ); pwd )"
RUNDIR="$( pwd )"
NEGENDIR="${RUNDIR}/netgen"

if [[ ! -f "${NEGENDIR}/exe/netgen" ]]; then
    echo "Failed to find Netgen binary at ${NEGENDIR}/exe/netgen"
    exit 1
fi

export PCE_NETNS="$1"
export PCE_IP="$2"
RT1_INT_IP="$3"
RT1_EXT_IP="$4"
RT6_INT_IP="$5"
RT6_EXT_IP="$6"


if [[ -z $PCE_NETNS || -z $PCE_IP || -z  RT1_INT_IP || -z  RT1_EXT_IP || -z  RT6_INT_IP || -z  RT6_EXT_IP ]]; then
    echo "USAGE: $0 PCE_NETNS PCE_IP RT1_INT_IP RT1_EXT_IP RT6_INT_IP RT6_EXT_IP"
    echo "  e.g: $0 cni-588a2d06-e64f-907b-d51b-bed0307007c9 10.1.103.133 10 11 12 13"
    exit 1
fi

IFS=. read PCE_IP1 PCE_IP2 PCE_IP3 PCE_IP4 <<< "$PCE_IP"

export RT1_PCE_INT_IF_IP="$PCE_IP1.$PCE_IP2.$PCE_IP3.$RT1_INT_IP"
export RT1_PCE_EXT_IF_IP="$PCE_IP1.$PCE_IP2.$PCE_IP3.$RT1_EXT_IP"
export RT6_PCE_INT_IF_IP="$PCE_IP1.$PCE_IP2.$PCE_IP3.$RT6_INT_IP"
export RT6_PCE_EXT_IF_IP="$PCE_IP1.$PCE_IP2.$PCE_IP3.$RT6_EXT_IP"

cp "${ROOTDIR}/2-6-netgen-config.yml" "${RUNDIR}/config.yml"
cat "${ROOTDIR}/2-6-netgen-topology.yml.template" | envsubst > "${RUNDIR}/topology.yml"

sudo -i bash -c "\
    cd ${RUNDIR}/netgen;\
    sysctl -w net.ipv6.conf.all.disable_ipv6=1;\
    sysctl -w net.ipv6.conf.default.disable_ipv6=1;\
    sysctl -w net.ipv4.conf.all.rp_filter=0;\
    PATH=/usr/lib/frr:\$PATH ./exe/netgen ../topology.yml -c ../config.yml"
