#!/bin/sh
set -e
LOCAL="$1"; shift
REMOTE="$1"; shift
TUN="$1"; shift
MTU="$1"; shift

# I hope your host names are unique within the first 11 chars. This is
# a Linux kernel restriction. If there is a clash, it should just fall
# back to using tunN; of course, your firewall rules probably won't
# allow such traffic.

DEV="$(echo "vpn-$REMOTE"|cut -c -15)"
ip li set dev "$TUN" name "$DEV" || DEV="$TUN"
ip li set dev "$DEV" up mtu "$MTU"

ADDR='127.0.0.1'
if [ -e "config/$LOCAL/vpnaddress" ]; then
    read VPNADDRESS <"config/$LOCAL/vpnaddress"
    ADDR="$VPNADDRESS"
fi

ip a add "$ADDR"/32 scope host dev "$DEV"
if [ -e "config/$LOCAL/peers/$REMOTE/rp_filter" ]; then
    cat "config/$LOCAL/peers/$REMOTE/rp_filter" \
        >"/proc/sys/net/ipv4/conf/$DEV/rp_filter"
fi

while read ROUTE; do
    if [ -n "$VPNADDRESS" ]; then
	ip ro add "$ROUTE" dev "$DEV" src "$VPNADDRESS"
    else
	ip ro add "$ROUTE" dev "$DEV"
    fi
done <"config/$LOCAL/peers/$REMOTE/routes"
