#!/bin/sh
#
# This is an example of a Mandos client network hook.  This hook
# brings up a bridge interface as specified in a separate
# configuration file.  To be used, this file and any needed
# configuration file(s) should be copied into the
# /etc/mandos/network-hooks.d directory.
# 
# Copyright © 2012-2018 Teddy Hogeborn
# Copyright © 2012-2018 Björn Påhlsson
# 
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice and this notice are preserved.  This file is offered as-is,
# without any warranty.

set -e

CONFIG="$MANDOSNETHOOKDIR/bridge.conf"

addrtoif(){
    grep -liFe "$1" /sys/class/net/*/address \
	| sed -e 's,.*/\([^/]*\)/[^/]*,\1,' -e "/^${BRIDGE}\$/d"
}

# Read config file, which must set "BRIDGE", "PORT_ADDRESSES", and
# optionally "IPADDRS" and "ROUTES".
if [ -e "$CONFIG" ]; then
    . "$CONFIG"
fi

if [ -z "$BRIDGE" ] || [ -z "$PORT_ADDRESSES" ]; then
    exit
fi

if [ -n "$DEVICE" ]; then
    case "$DEVICE" in
	*,"$BRIDGE"|*,"$BRIDGE",*|"$BRIDGE",*|"$BRIDGE") :;;
	*) exit;;
    esac
fi

brctl="/sbin/brctl"
for b in "$brctl" /usr/sbin/brctl; do
    if [ -e "$b" ]; then
	brctl="$b"
	break
    fi
done

do_start(){
    "$brctl" addbr "$BRIDGE"
    for address in $PORT_ADDRESSES; do
	interface=`addrtoif "$address"`
	"$brctl" addif "$BRIDGE" "$interface"
	ip link set dev "$interface" up
    done
    ip link set dev "$BRIDGE" up
    sleep "${DELAY%%.*}"
    if [ -n "$IPADDRS" ]; then
        for ipaddr in $IPADDRS; do
	    ip addr add "$ipaddr" dev "$BRIDGE"
	done
    fi
    if [ -n "$ROUTES" ]; then
        for route in $ROUTES; do
	    ip route add "$route" dev "$BRIDGE"
	done
    fi
}

do_stop(){
    ip link set dev "$BRIDGE" down
    for address in $PORT_ADDRESSES; do
	interface=`addrtoif "$address"`
	ip link set dev "$interface" down
	"$brctl" delif "$BRIDGE" "$interface"
    done
    "$brctl" delbr "$BRIDGE"
}

case "${MODE:-$1}" in
    start|stop)
	do_"${MODE:-$1}"
	;;
    files)
	echo /bin/ip
	echo "$brctl"
	;;
    modules)
	echo bridge
	;;
esac
