#!/usr/bin/python3
#
# Univention Network Common
#  Save the ip address in LDAP
#
# Copyright (C) 2012-2021 Univention GmbH
#
# https://www.univention.de/
#
# All rights reserved.
#
# The source code of this program is 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 program 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 this program 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
# <https://www.gnu.org/licenses/>.

from __future__ import print_function
import sys
import argparse

import netifaces
import time

import univention.config_registry
import univention.uldap
from univention.lib.umc import Client, HTTPError, ConnectionError, ServiceUnavailable

ATTEMPTS = 5
RETRY_DELAY = 5


def register_iface(configRegistry, iface, verbose):
	# is fallback different from current address?
	for retry in range(ATTEMPTS):
		try:
			client = Client(configRegistry['ldap/master'])
			client.authenticate_with_machine_account()
			client.umc_command('ip/change', {
				'ip': configRegistry.get('interfaces/%s/address' % iface),
				'oldip': configRegistry.get('interfaces/%s/fallback/address' % iface),
				'netmask': configRegistry.get('interfaces/%s/netmask' % iface),
				'role': configRegistry.get('server/role'),
			})
			return True
		except ServiceUnavailable as exc:
			if verbose:
				print('%s: %s' % (type(exc).__name__, exc), file=sys.stderr)
			if retry + 1 < ATTEMPTS:
				print('INFO: Retry (%s/%s) in %s seconds.' % (retry + 1, ATTEMPTS - 1, RETRY_DELAY))
				time.sleep(RETRY_DELAY)
		except (HTTPError, ConnectionError) as exc:
			if verbose:
				print('%s: %s' % (type(exc).__name__, exc), file=sys.stderr)
			return False
	return True


if __name__ == '__main__':
	parser = argparse.ArgumentParser()
	parser.add_argument("--interface", default='all', help="network interface to use")
	parser.add_argument("--verbose", default=False, action="store_true", help="verbose output")
	parser.add_argument("--force", default=False, action="store_true", help="register interface even if it is configured static")
	options = parser.parse_args()

	configRegistry = univention.config_registry.ConfigRegistry()
	configRegistry.load()

	retcode = 0

	if options.interface == 'all':
		ifaces = netifaces.interfaces()
	else:
		ifaces = [options.interface]

	for ignore in ['lo', 'docker0']:
		if ignore in ifaces:
			ifaces.remove(ignore)
	if not ifaces:
		print('ERROR: no valid interface was given. Try --interface')
		sys.exit(1)

	for iface in ifaces:
		if configRegistry.get('interfaces/%s/type' % iface) == 'dhcp' or options.force:
			if not register_iface(configRegistry, iface, options.verbose):
				retcode += 1
		elif options.verbose:
			print('INFO: %s is not configured as dhcp device.' % iface)

	sys.exit(retcode)
