#!/bin/bash

pickup_defaults
pickup_options

[ -x "${BRCTL:=$DEFAULT_BRCTL}" ] || {
	print_error "$BRCTL does not exist or is not executable. Try installing bridge-utils RPM."
	exit 1
}

[ -x "${BRIDGE:=$DEFAULT_BRIDGE}" ] || {
	print_error "$BRIDGE does not exist or is not executable. Try installing iproute2 RPM."
	exit 1
}

$BRCTL addbr $NAME

# Give brctl a chance to set necessary parameters on a bridge before adding ports into it,
# so we don't suddenly plug unconfigured bridge into network. The only thing we can't
# set this way are port priority and cost (which shouldn't be critical in most cases).
if profiled_filename PROF_BRCTL "$MYIFACEDIR/brctl"; then
	$DENOISE $PROF_BRCTL |
		trim |
		sed "s/ AUTO / $NAME /" |
		xargs --max-lines=1 $BRCTL
fi && print_progress

is_yes "$VLAN_AWARE" && {
	[ -f /sys/class/net/$NAME/bridge/vlan_filtering ] && {
		printf '%s' 1 > /sys/class/net/$NAME/bridge/vlan_filtering && print_progress
	}
}

for host in $HOST; do
	$BRCTL addif $NAME $host && print_progress
	if [ -n "$VIDS" ]; then
		for vid in $VIDS; do
			$BRIDGE vlan add dev $host vid $vid && print_progress
		done
	fi
done

if [ -n "$SVI" ]; then
	for vid in $SVI; do
		$BRIDGE vlan add dev $NAME vid $vid self && print_progress
	done
fi
