#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
#
# Univention RADIUS 802.1X
#  authentication test program
#
# Copyright (C) 2012-2014 Univention GmbH
#
# http://www.univention.de/
#
# All rights reserved.
#
# The source code of the software contained in this package
# as well as the source package itself are made available
# under the terms of the GNU Affero General Public License version 3
# (GNU AGPL V3) as published by the Free Software Foundation.
#
# Binary versions of this package provided by Univention to you as
# well as other copyrighted, protected or trademarked materials like
# Logos, graphics, fonts, specific documentations and configurations,
# cryptographic keys etc. are subject to a license agreement between
# you and Univention and not subject to the GNU AGPL V3.
#
# In the case you use the software under the terms of the GNU AGPL V3,
# the program is provided in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public
# License with the Debian GNU/Linux or Univention distribution in file
# /usr/share/common-licenses/AGPL-3; if not, see
# <http://www.gnu.org/licenses/>.

from univention.networkaccess import traceNetworkAccess
from univention.networkaccess import traceStationWhitelist
import optparse
import sys
import univention.uldap

def main():
	usage = 'Usage: %prog [options]\n\nCheck network access for a user and/or MAC address'
	parser = optparse.OptionParser(usage=usage)
	parser.add_option('--username', dest='Username')
	parser.add_option('--station-id', dest='stationId')
	(options, args, ) = parser.parse_args()
	ldapConnection = univention.uldap.getMachineConnection()
	exitCode = 0
	if options.Username:
		result, message = traceNetworkAccess(ldapConnection, options.Username)
		sys.stdout.write(message)
		if not result:
			exitCode = 1
	if options.stationId:
		# safely decode station id (fails with exception on mis-formatted id, thus returning 1)
		stationId = options.stationId
		stationId = stationId[0:2] + stationId[3:5] + stationId[6:8] + stationId[9:11] + stationId[12:14] + stationId[15:17]
		stationId = stationId.decode('hex')
		result, message = traceStationWhitelist(ldapConnection, stationId)
		if options.Username:
			sys.stdout.write('\n')
		sys.stdout.write(message)
		if not result:
			exitCode = 1
	if options.Username and options.stationId:
		if exitCode:
			print '---\nThus access is DENIED.'
		else:
			print '---\nThus access is ALLOWED.'
	return exitCode

if __name__ == "__main__":
	sys.exit(main())
