#!/bin/sh
#
# This script uses `ifquery` to read the config in
# /etc/network/interfaces and then runs the mstpctl-utils
# `ifupdown.sh` script to configure the specified bridge in mstpd.
#
# This is used by the `/sbin/bridge-stp` script when called as
# `mstpctl_restart_config` or `mstp_restart` or
# `/sbin/bridge-stp restart_config` or `/sbin/bridge-stp restart` to
# automatically reconfigure bridges.
#
# This may also be used to configure mstpd on systems without ifupdown (on
# systems that are not based on Debian or Ubuntu).

# Parse arguments.
if [ $# -ne 1 ]; then
    echo "Usage: $0 <bridge>" >&2
    exit 1
fi
Bridge="$1"

# Make sure this script is being run as root.
if [ "$(id -u)" != '0' ]; then
    echo 'This script must be run as root' >&2
    exit 1
fi

# Ensure that we have a sane umask.
umask 022

# Ensure that we have a sane PATH.
PATH='/sbin:/usr/sbin:/bin:/usr/bin'
export PATH

# The mstp ifupdown.sh script will not work properly unless mstpctl, bridge,
# and ip exist and are executable.
mstpctl='/sbin/mstpctl'
if [ ! -x "$mstpctl" ]; then
  echo "'mstpctl' binary does not exist or is not executable" >&2
  exit 2
fi
brcmd="$(command -v bridge)"
if [ -z "$brcmd" ] || [ ! -x "$brcmd" ]; then
  echo "'bridge' binary does not exist or is not executable" >&2
  exit 2
fi
ip="$(command -v ip)"
if [ -z "$ip" ] || [ ! -x "$ip" ]; then
  echo "'ip' binary does not exist or is not executable" >&2
  exit 2
fi

# Find ifquery.
ifquery="$(command -v ifquery 2>/dev/null)"
if [ -z "$ifquery" ]; then
    # If the real ifquery is not installed, use our emulator.
    ifquery='/lib/mstpctl-utils/ifquery'
fi
if [ ! -x "$ifquery" ]; then
    echo "'ifquery' binary does not exist or is not executable" >&2
    exit 2
fi

# Run ifquery.
Out="$("$ifquery" "$Bridge" 2>/dev/null)" ; Err=$?
if [ $Err -ne 0 ]; then
    echo "Skipping configuration of bridge '$Bridge' that is not configured in"
    echo '/etc/network/interfaces'
    exit 0
fi

# Read the interface config and generate the environment variables that are
# typically generated by ifupdown.
export IFACE="$Bridge"
export LOGICAL="$Bridge"
export ADDRFAM='inet'
export METHOD='manual'
export MODE='start'
export PHASE='post-up'
export VERBOSITY=0
eval "$(
IFS= ; echo "$Out" | \
while read -r Line; do
    OptName="${Line%%: *}"  # Strip everything after the first ': '
    OptName="IF_$(echo "$OptName" | tr '[:lower:]-' '[:upper:]_')"  # Uppercase
    OptVal="${Line#*: }"  # Strip everything before the first ': '
    echo "export $OptName=\"$OptVal\""
done
)"

# Call the mstpctl-utils ifupdown.sh script.
'/lib/mstpctl-utils/ifupdown.sh'
