#!/bin/bash

set -x
set -e

get_default_iface() {
	ip -4 r show default | awk '{print $5}'
}

declare -A UPSTREAMS=(
	[mtsil]=102
	[mtsazov]=100
	[rtazov]=101
)

for name in "${!UPSTREAMS[@]}"; do
	mark=${UPSTREAMS[$name]}
	veth_addr=10.${mark}.1.1
	vpeer_addr=10.${mark}.1.2
	veth_if=veth${name}
	vpeer_if=vpeer${name}

	ip netns add $name
	ip link add $veth_if type veth peer name $vpeer_if
	ip link set $vpeer_if netns $name
	ip addr add $veth_addr/24 dev $veth_if
	ip link set $veth_if up

	ip netns exec $name ip addr add $vpeer_addr/24 dev $vpeer_if
	ip netns exec $name ip link set $vpeer_if up
	ip netns exec $name ip link set lo up
	ip netns exec $name ip route add default via $veth_addr

	iptables -t mangle -A PREROUTING -s $vpeer_addr/24 -j MARK --set-mark $mark
	iptables -t nat -A POSTROUTING -s $vpeer_addr/24 -o "$(get_default_iface)" -j MASQUERADE
done

sysctl net.ipv4.ip_forward=1
