#!/bin/bash

if [ $# -lt 1 ]
then
	exit 1
fi

slave_itf="$1"
slave_sys_flags="/sys/class/net/$slave_itf/flags"

if ! [ -f "$slave_sys_flags" ]
then
	exit 1
fi

count=0
is_slave=$((($(cat $slave_sys_flags 2>/dev/null) & 0x800) != 0))
while true;
do
	if [ $is_slave -eq 1 ] || [ $count -gt 60 ]
	then
		break
	fi
	sleep 1
	is_slave=$((($(cat $slave_sys_flags 2>/dev/null) & 0x800) != 0))
	count=$(($count+1))
done

# get master idx
idx=$(cat /sys/class/net/$slave_itf/master/ifindex 2>/dev/null)
if [ "_$idx" = "_" ]
then
	#of no master link yet in sysfs, fallback to our index
	idx=$(cat /sys/class/net/$slave_itf/ifindex 2>/dev/null)
fi

if [ $count -gt 60 ] || [ "_idx" = "_" ]
then
	exit 1
fi

# output to stdout so that the index is expanded by (slash)c in the udev rule
echo -n $idx


exit 0
