#!/usr/bin/python3
#
# Univention Network Common
#  Save the ip address in LDAP
#
# SPDX-FileCopyrightText: 2012-2026 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only
"""Save the IP address (from DHCP) in LDAP."""

import argparse
import sys
import time

import netifaces

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


ATTEMPTS = 5
RETRY_DELAY = 5


def register_iface(iface: str, verbose: bool) -> bool:
    # is fallback different from current address?
    for retry in range(ATTEMPTS):
        try:
            client = Client(ucr['ldap/master'])
            client.authenticate_with_machine_account()
            client.umc_command('ip/change', {
                'ip': ucr.get('interfaces/%s/address' % iface),
                'oldip': ucr.get('interfaces/%s/fallback/address' % iface),
                'netmask': ucr.get('interfaces/%s/netmask' % iface),
                'role': ucr.get('server/role'),
            })
            return True
        except (HTTPError, ConnectionError) as exc:
            # UMC may not be reachable/ready yet while starting up at boot, retry
            if verbose:
                print('%s: %s' % (type(exc).__name__, exc), file=sys.stderr)
            if isinstance(exc, HTTPError) and exc.status < 500:
                return False
            if retry + 1 < ATTEMPTS:
                print('INFO: Retry (%s/%s) in %s seconds.' % (retry + 1, ATTEMPTS - 1, RETRY_DELAY))
                time.sleep(RETRY_DELAY)
    return False


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--interface", action='append', help="network interface to use")
    parser.add_argument("--verbose", action="store_true", help="verbose output")
    parser.add_argument("--force", action="store_true", help="register interface even if it is configured static")
    return parser.parse_args()


def main() -> None:
    options = parse_args()

    ifaces = set(options.interface or netifaces.interfaces())
    ifaces -= {"lo", "docker0"}
    if not ifaces:
        print('ERROR: no valid interface was given. Try --interface')
        sys.exit(1)

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

    sys.exit(retcode)


if __name__ == '__main__':
    main()
