#!/bin/bash2
# CreatMACMapping - routine to establish a context between MACs and the associated eth interfaces


# author: K. M. Gheri <k g heri at barra  cuda dot com>
#	  Barracuda Networks AG, Copyright 2011
#	  All rights reserved

IGNOREAPPLIANCE=0 ROLLOUTNEW=0 NOWRITE=0

getopts ":frn" opt
case $opt in
        f) 
		# ignore a set appliance model
		IGNOREAPPLIANCE=1
		;;
	r)
		# alway do a fresh rollout
		ROLLOUTNEW=1
		;;
	n)
		# do not write a local mapping file
		NOWRITE=1
		;;	
esac


function listofdevs {
	# args:
	# $1 type of query
	#
	
	local DEVLIST=	
	DEVLIST=$(cat /proc/net/dev |/usr/bin/cut -s -f1 -d:)

	#remove monitoring device mon.ath created by hostapd from list
	if [ $(echo $DEVLIST | grep -c mon.ath) -gt 0 ]; then
		DEVLIST=${DEVLIST/mon.ath[0-9]/};
	fi

	for i in $DEVLIST; do
		echo -n $(echo -n -e " $i\c")/
		
	done
	echo ""
	return 0
}


if [[ -f /etc/phion/functions.net ]]; then
	source /etc/phion/functions.net
else
	#TODO log error
	echo "Error: missing /etc/phion/functions.net, exiting"
	exit 1	
fi

IP=/sbin/ip
BOXINFOTOOL=/opb/boxinfo
# we determine the type of platform ourselves
[ -x ${BOXINFOTOOL} ] || {
	echo "Error: missing ${BOXINFOTOOL}, exiting"
	exit 1	
}

[[ ${IGNOREAPPLIANCE:-0} != 1 ]] && {

	APPLIANCE=$(${BOXINFOTOOL} appliance 2>/dev/null)

	[ "${APPLIANCE:-standard}" != standard ] && {
		echo "Info: appliance model setting ${APPLIANCE} found, exiting"
		exit 0
	}
}

M2IMAPLOCAL=/var/phion/preserve/boxnet/mac2if.map

[[ -s ${M2IMAPLOCAL} ]] && {
	echo "Warning: mapping file already exists will not overwrite"
	NOWRITE=1
}


THEROLLOUTFILE=/etc/phion/dynconf/boxnet.conf.rollout
MYROLLOUTFILE=/tmp/boxnet.conf.rollout



if [ -s ${THEROLLOUTFILE} -a ${ROLLOUTNEW:-0} != 1 ]; then
	 source ${THEROLLOUTFILE}
else
	/epb/boxconf_rollout.net1 /opt/phion/config/active/boxnet.conf ${MYROLLOUTFILE} &>/dev/null
	source ${MYROLLOUTFILE}
	rm -f  ${MYROLLOUTFILE}
fi

# reverse the mapping first (we now run in relabelled device mode post network activation)

MPATH=/opt/phion/appliances/modules/box/boxnet

[ ${box_DEVMAP:-"NONE"} != "NONE"  ] && {
	DEVMAP=${box_DEVMAP}
	[ ! -z "${box_DEVMAPSUB}" ] && DEVMAP=${box_DEVMAP}-${box_DEVMAPSUB}
	echo "Info: network configuration uses interface mapping scheme  ${DEVMAP}"
 }
 



if [ ${box_DEVMAP:-"NONE"} = "USER" ]; then
	kMAX=${#box_mapping_IDEV_1[@]}
	for ((k=0; kMAX-k; k++)); do
		IDEV=${box_mapping_IDEV_1[$k]}
		EDEV=${box_mapping_EDEV_1[$k]:-${IDEV}}
		[ _${IDEV} = _${EDEV} ] && continue
		case $IDEV in 
			pqd0|lo|tap1|tap2|tap3|ppp*|ippp*|dhcp*|bond*)
				echo "Error: network configuration maps reserved internal interface name $IDEV to ${EDEV}"
				continue
				;;
		esac
		case $EDEV in 
			pqd0|lo|tap1|tap2|tap3|ppp*|ippp*|dhcp*|bond*)
				echo "Error: network configuration uses reserved internal interface name $EDEV as external name of internal interface ${IDEV}"
				continue
				;;
		esac
		eval I2EMAP_${IDEV}=\${EDEV:-${IDEV}}
		eval E2IMAP_${EDEV}=\${IDEV}
	done

	
	set -- ${!I2EMAP_*}
	[ $# != $kMAX ] && {
		# issue error message due to incomplete 1:1 mapping
		echo "Error: network configuration uses ambiguous internal-to-external interface mapping ($# < $kMAX)"
	}
	
	set -- ${!E2IMAP_*}
	[ $# != $kMAX ] && {
		# issue error message due to incomplete 1:1 mapping
		echo "Error: network configuration uses ambiguous external-to-internal interface mapping ($# < $kMAX)"
	}
	
	
	
	
elif [ ${box_DEVMAP:-"NONE"} != "NONE" ]; then
# do this here or via inventory !!!
	DEVMAP=${box_DEVMAP}
	[ ! -z "${box_DEVMAPSUB}" ] && DEVMAP=${box_DEVMAP}-${box_DEVMAPSUB}
	[ -f ${MPATH}/${DEVMAP}.map ] && source ${MPATH}/${DEVMAP}.map
	
fi


# TODO still need to account for dhcp and pppoe interfaces - so we need an explicit mapping part here as well!

[ ${box_AADSL:-y} = y -a ${box_adsl_N:-0} -ge 1 ] && {
	N=${box_adsl_N}
	for ((n=1; N+1-n;n++)); do
		eval [ \${box_adsl_ACT_${n}:-y} =  y ] || continue
		eval _TYPE=\${box_adsl_TYPE_${n}:-PPTP}
		if  [ ${_TYPE} !=  PPTP ]; then
			if [ ${_TYPE} =  PPPOE ]; then
				eval TMP=\${box_adsl_MODEMDEV_$n}
				MODEMDEV=${TMP}
				eval pppoe${n}=${MODEMDEV}
			fi
		fi
	done
}

[ ${box_ADHCP:-y} = y -a ${box_dhcp_N:-0} -ge 1 ] && {
	N=${box_dhcp_N}
	for ((n=1; N+1-n;n++)); do
		eval [ \${box_dhcp_ACT_${n}:-y} =  y ] || continue		
		eval TMP=\${box_dhcp_DEVICE_$n}
		MODEMDEV=${TMP}
		if [[ ${n} = 1 ]]; then
			dhcp=${MODEMDEV}
		else
			eval dhcp${n}=${MODEMDEV}
		fi
	done
}


_ALLMAPPEDDEVS=$(listofdevs)				#presently available interfaces
ALLMAPPEDDEVS=(${_ALLMAPPEDDEVS//\// })
ALLEXISTDEVS=($(dot2underscore ${ALLMAPPEDDEVS[@]}))    #reverted all mapping, but this does not work for dhcp,pppoe as there is an extra mapping

j=0
BONDLIST=""
for i in ${ALLEXISTDEVS[@]}; do		
	case ${i} in
		
		dhcp|dhcp[0-9]|pppoe[0-9])
			mi=${i}
			[[ ${!i:-$i} = $i ]] && {
				let j++
				continue
			}
			i=$(dot2underscore ${!i})
			let j++
			;;
		
	
		eth[0-9]|eth[0-9][0-9])
			mi=${ALLMAPPEDDEVS[$j]}
			eval $mi=${i}
			let j++	
			;;
		
		bond[0-9])
			# TODO hier herinnen machen!!!
			BONDLIST="${BONDLIST} ${i}"
			let j++
			continue
			;;
		*)
			let j++	
			continue
			;;
	esac

	_OUT=$(${IP} -o link show ${mi} 2>/dev/null)
	_OUT1=${_OUT#*link/ether}
	[[ "${_OUT1}" = "${_OUT}" ]] && continue
	_OUT1=${_OUT1%brd*}  			# this contains the MAC now, 
						# we have thus an established MAC to IF name context
	eval M2I_$(echo -n ${_OUT1//:/_})=${i}
	eval I2M_${i}=$(echo -n ${_OUT1//:/_})
	
done

#REDO bonding

_DLIST=() _MLIST=()

for i in ${BONDLIST}; do

	[[ -f /proc/net/bonding/${i} ]] && {
	
		_OUT=$(grep "Slave Interface:" /proc/net/bonding/${i})
		_DLIST=($(echo ${_OUT//"Slave Interface:"/ }))
		_OUT=$(grep "Permanent HW addr:" /proc/net/bonding/${i})
		_MLIST=($(echo ${_OUT//"Permanent HW addr:"/ }))
		 	 
		 _NDLIST=${#_DLIST[@]}
		 j=0
		 for _IF in ${_DLIST[@]}; do
			_MAC=$(echo -n ${_MLIST[$j]//:/_})
			[[ "${_MAC:-0}" = 0  ]] && {
				echo "Error: missing MAC information for ${IF}[${!IF}]"
				NOWRITE=1
				let j++ 
				continue
			}
			_ETH=${!_IF}
		 	eval M2I_${_MAC}=\${_ETH}
			eval I2M_${_ETH}=\${_MAC}
		 	let j++
		 
		 done		 	
	}

done




if [[ ${NOWRITE:-0} != 1 ]]; then

	echo -n > ${M2IMAPLOCAL}
	for i in ${!M2I_*} ${!I2M_*}; do
		echo "C${i}=${!i}" >> ${M2IMAPLOCAL}
	done
	
	echo "Info: detected and wrote the following MAC to ethernet interface mapping"
	cat ${M2IMAPLOCAL}
else
	echo "Info: found existing MAC to ethernet interface mapping file"
	cat ${M2IMAPLOCAL}
	echo "Info: detected the following MAC to ethernet interface mapping"
	for i in ${!M2I_*} ${!I2M_*}; do
		echo "C${i}=${!i}"
	done
fi

exit 0


