#
#	Split User-Name in NAI format (RFC 7542) into components
#
#  This policy writes the Username and Domain portions of the
#  NAI into the Stripped-User-Name and Stripped-User-Domain
#  attributes.
#
#  The regular expression to do this is not strictly compliant
#  with the standard, but it is not possible to write a
#  compliant regexp without perl style regular expressions (or
#  at least not a legible one).
#
#  i.e. this regular expression will accept all valid NAIs,
#  and will not reject valid NAIs.  Unfortunately, it will also
#  accept invalid NAIs.
#
nai_regexp = '^([^@]*)(@([-[:alnum:]]+\.[-[:alnum:].]+))?$'

split_username_nai {
	if (&User-Name && (&User-Name =~ /${policy.nai_regexp}/)) {
		&request.Stripped-User-Name := "%{1}"


		# Only add the Stripped-User-Domain attribute if
		# we have a domain. This means presence checks
		# for Stripped-User-Domain work.
		if ("%{3}" != '') {
			&request.Stripped-User-Domain = "%{3}"
		}

		# If any of the expansions result in a null
		# string, the update section may return
		# something other than updated...
		updated
	}
	else {
		noop
	}
}

#
#  Normalize the MAC Addresses in the Calling/Called-Station-Id
#
mac-addr-regexp = '([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})[^0-9a-f]?([0-9a-f]{2})'

#
#  Add "rewrite_called_station_id" in the "recv Access-Request" and
#  "recv Accounting-Request" sections.
#
#  Makes Called-Station-ID conform to what RFC3580 says should
#  be provided by 802.1X authenticators.
#
rewrite_called_station_id {
	if (&Called-Station-Id && (&Called-Station-Id =~ /^${policy.mac-addr-regexp}([^0-9a-f](.+))?$/i)) {
		&request.Called-Station-Id := "%toupper(%{1}-%{2}-%{3}-%{4}-%{5}-%{6})"

		# SSID component?
		if ("%{8}") {
			&request.Called-Station-SSID := "%{8}"
		}
		updated
	}
	else {
		noop
	}
}

#
#  Add "rewrite_calling_station_id" in the "recv Access-Request" and
#  "recv Accounting-Request" sections.
#
#  Makes Calling-Station-ID conform to what RFC3580 says should
#  be provided by 802.1X authenticators.
#
rewrite_calling_station_id {
	if (&Calling-Station-Id && (&Calling-Station-Id =~ /^${policy.mac-addr-regexp}$/i)) {
		&request.Calling-Station-Id := "%toupper(%{1}-%{2}-%{3}-%{4}-%{5}-%{6})"

		updated
	}
	else {
		noop
	}
}
