#!/usr/share/ucs-test/runner python
## desc: Check if UMC is able to return correct IP address
## exposure: dangerous
## packages:
##    - univention-management-console-web-server (>= 3.0.152)

from univention.lib.umc_connection import UMCConnection
import univention.testing.utils as utils
import univention.testing.network as network
from json import loads


def get_ip_address(host, username, password):
	connection = UMCConnection(host)
	connection.auth(username, password)
	rawcon = connection.get_connection()
	rawcon.request('POST', '/umcp/get/ipaddress', connection.build_data({}))
	return loads(rawcon.getresponse().read())


def main():
	username = 'Administrator'  # FIXME: currently there is no UCR variable containing the admin username
	password = 'univention'  # FIXME: if username is fixed, then use the UCR variable tests/domainadmin/{pwd,pwdfile} here

	with network.NetworkRedirector() as nethelper:
		print '*** Check with different remote addresses'
		for addr2 in ('4.3.2.1', '1.1.1.1', '2.2.2.2'):
			nethelper.add_loop('1.2.3.4', addr2)

			result = get_ip_address('1.2.3.4', username, password)
			print 'Result: %r' % result
			if not addr2 in result:
				utils.fail('UMC webserver is unable to determine correct UMCP client address (expected=%r result=%r)' % (addr2, result))

			nethelper.remove_loop('1.2.3.4', addr2)

		print '*** Check with localhost'
		result = get_ip_address('localhost', username, password)
		if result:
			utils.fails('Response is expected to be empty')

if __name__ == '__main__':
	main()
