#!/bin/bash
# Monitors for multicast groups that have been added, and
# sets up the appropriate flow.

BRIDGE=bridge

parse_mdb_entries() {
	local lan_dev="br0"
    while IFS= read -r line || [[ -n "$line" ]]; do
            echo "$line"

            PORT=$(echo "$line" | awk '/dev'" $lan_dev/"' {print $4}')
            GRP=$(echo "$line" | awk '/dev'" $lan_dev/"' {print $6}')
            ACTION=$(echo "$line" | awk '/dev'" $lan_dev/"' {print $8}')
            ADDR=$(echo "$GRP" | cut -d'.' -f1)
            if [[ $GRP =~ ^[0-9]{1,3}\. && $ADDR -gt 223 && $ADDR -lt 240 ]]; then
                    echo "$ACTION multicast flow for port $PORT group $GRP"
                    echo mdb_$ACTION $1 $PORT $GRP > /proc/driver/flowmgr/cmd
            fi

    done
}

parse_mdb_entries_init() {
	local lan_dev="br0"
    while IFS= read -r line || [[ -n "$line" ]]; do
            echo "$line"

            PORT=$(echo "$line" | awk '/dev'" $lan_dev/"' {print $4}')
            GRP=$(echo "$line" | awk '/dev'" $lan_dev/"' {print $6}')
            ADDR=$(echo "$GRP" | cut -d'.' -f1)
            if [[ $GRP =~ ^[0-9]{1,3}\. && $ADDR -gt 223 && $ADDR -lt 240 ]]; then
                    echo "Add multicast flow for port $PORT group $GRP"
                    echo mdb_add $1 $PORT $GRP > /proc/driver/flowmgr/cmd
            fi

    done
}

ps -C $BRIDGE &> /dev/null
if [ $? -eq 0 ]; then
    exit 0
fi

# if GFAP driver is present, this is a 3384 and uses an external
# switch.  Tell ethsw that bridge is running and multicast
# destinations are learned so IPv6 multicast will not
# be flooded to all ports
[ -d /proc/driver/gfap ] && echo m 1 > /proc/driver/ethsw/vlan

echo > /dev/console "Start Multicast Monitoring"



echo > /dev/console "mcast_mon: Reading MDB entries"

bridge mdb show |
        parse_mdb_entries_init $1

echo > /dev/console "mcast_mon: Begin MDB state monitoring"

ifconfig cm0 |grep "inet addr:"
while [ $? -ne 0 ]; do
	sleep 3
	ifconfig cm0 |grep "inet addr:"
done

mcproxy -d -v -f /usr/local/etc/mcproxy.conf  &


cd /var && script -f -c "bridge mon mdb"  |
        parse_mdb_entries $1

echo > /dev/console "End Multicast Monitoring"
