#!/usr/bin/python3
"""
Univention Setup:
Setting primary network interface.
"""
# Like what you see? Join us!
# https://www.univention.com/about-us/careers/vacancies/
#
# Copyright 2018-2023 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 univention.config_registry.interfaces import Interfaces
from univention.management.console.modules.setup.setup_script import SetupScript, _, main


class NoConfiguredInterfaceError(Exception):
	pass


class PrimaryInterfaceSetup(SetupScript):
	name = _("Setting primary network interface")

	def up(self):
		self.interfaces = Interfaces()

	def inner_run(self):
		primary_interface = self.ucr.get("interfaces/primary")
		if primary_interface in [interface[0] for interface in self.interfaces.all_interfaces]:
			self.message("Primary interface already set")
			return True
		try:
			primary_interface = self._choose_primary_interface()
		except NoConfiguredInterfaceError:
			self.message("No configured interface found. No primary interface set.")
			return True
		self.message("Setting primary interface to: {}".format(primary_interface))
		self.ucr.set("interfaces/primary", primary_interface)
		return True

	def _choose_primary_interface(self):
		for interface in self.interfaces.all_interfaces:
			if "address" in interface[1] and interface[1]["address"]:
				return interface[0]
			if "ipv6/default/address" in interface[1] and interface[1]["ipv6/default/address"]:
				return interface[0]
		raise NoConfiguredInterfaceError


if __name__ == "__main__":
	main(PrimaryInterfaceSetup())
