# VLAN module for net-scripts
# Version 1.0.1
# Copyright (c) 2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License V2
# Contributed by Roy Marples (uberlord@gentoo.org)

# bool vlan_check_installed(void)
#
# Returns 1 if vconfig is installed, otherwise 0
vlan_check_installed() {
	[[ -x /sbin/vconfig ]] && return 0
	[[ ${1} == true ]] && eerror "For VLAN (802.1q) support, emerge net-misc/vconfig"
	return 1
}

# char* vlan_provides(void)
#
# Returns a string to change module definition for starting up
vlan_provides() {
	echo "vlan"
}

# void vlan_depend(void)
#
# Sets up the dependancies for the module
vlan_depend() {
	after interface
	before dhcp
	need interface
}


# bool vlan_check_depends(void)
#
# Checks to see if we have the needed functions
vlan_check_depends() {
	local f

	for f in get_device interface_get_vlans iface_start iface_stop; do
		[[ $(type -t ${f}) == function ]] && continue
		eerror "vlan: missing required function ${f}\n"
		return 1
	done

	return 0
}

# char* vlan_get_vars(char *interface)
#
# Returns a string spaced with possible user set
# configuration variables
vlan_get_vars() {
	echo "vlans_${1} iface_${1}_vlans"
}

# bool vlan_post_start(char *iface)
#
# Starts VLANs for a given interface
#
# Always returns 0 (true) 
vlan_post_start() {
	local iface="${1//./_}" vlan vlans vlans_old

	eval vlans=\"\$\{vlans_${iface}\}\"

	# BACKWARD COMPATIBILITY: check for old vlan variable name
	eval vlans_old=\"\$\{iface_${iface}_vlans\}\"
	[[ -n ${vlans_old} && -z ${vlans} ]] && vlans=${vlans_old}

	# Start vlans for this interface
	for vlan in ${vlans}; do
		einfo "Adding VLAN ${vlan} to ${iface}"
		/sbin/vconfig add ${iface} ${vlan} >${devnull}
		eend $? && iface_start ${iface}.${vlan}
	done

	return 0
}

# bool vlan_pre_stop(char *iface)
#
# Stops VLANs for a given interface
#
# Always returns 0 (true) 
vlan_pre_stop() {
	local iface=${1} vlan

	vlan_check_installed || return 0

	for vlan in $( interface_get_vlans ${iface} ); do
		einfo "Removing VLAN ${vlan##*.} from ${iface}"
		iface_stop ${vlan}
		/sbin/vconfig rem ${vlan} >${devnull}
	done

	return 0
}
