#!/usr/bin/python3
#
# Univention Network Common
#  Save the ip address in LDAP
#
# SPDX-FileCopyrightText: 2012-2025 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only

import argparse
import sys
import time

import netifaces

import univention.config_registry
from univention.lib.umc import Client, ConnectionError, HTTPError, ServiceUnavailable  # noqa: A004


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)
