#!/bin/sh

set -e
set -x

# Re-add the namespace
ip netns add amphora-haproxy || true

# Load the system sysctl into the new namespace
ip netns exec amphora-haproxy sysctl --system

# Enable kernel module ip_vs for lvs function in amphora network namespace
ip netns exec amphora-haproxy modprobe ip_vs

# Enable ip_forward and conntrack kernel configuration
ip netns exec amphora-haproxy sysctl -w net.ipv4.ip_forward=1
ip netns exec amphora-haproxy sysctl -w net.ipv4.vs.conntrack=1
ip netns exec amphora-haproxy sysctl -w net.ipv6.conf.all.forwarding=1

# We need the plugged_interfaces file sorted to join the host interfaces
/usr/bin/sort -k 1 /var/lib/octavia/plugged_interfaces > /var/lib/octavia/plugged_interfaces.sorted

# Assign the interfaces into the namespace with the appropriate name
ip link | awk '{getline n; print $0,n}' \
	| awk '{sub(":","",$2)} { for(i=1;i<=NF;i++) if ($i == "link/ether") {print $(i+1) " " $2} }' \
	| sort -k 1 | join -j 1 - /var/lib/octavia/plugged_interfaces.sorted \
	| awk '{system("ip link set "$2" netns amphora-haproxy name "$3"")}'

# Bring up all of the namespace interfaces
ip netns exec amphora-haproxy ifup -a

exit 0
