#!/usr/bin/python3
#
# Univention RADIUS
#  update clients.univention.conf
#
# SPDX-FileCopyrightText: 2014-2025 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only


import os
import pwd
import shutil
import tempfile
from argparse import ArgumentParser

from univention.uldap import getMachineConnection


BASE_DIR = '/etc/freeradius/3.0'
BASE_NAME = 'clients.univention.conf'


def main() -> None:
    parser = ArgumentParser()
    parser.parse_args()

    with tempfile.NamedTemporaryFile(mode='w', prefix=f'{BASE_NAME}.tmp.', dir=BASE_DIR, delete=False) as fd:
        print('Updating clients.univention.conf')
        fd.write('''# -*- text -*-
#
# clients.univention.conf -- client configuration directives
#
# Warning: This file is auto-generated and might be overwritten
#          triggered by modifications in LDAP directory.
# Warnung: Diese Datei wurde automatisch generiert und kann,
#          angestoßen durch Änderungen im LDAP-Verzeichnis,
#          überschrieben werden.
#

''')

        lo = getMachineConnection(ldap_master=False)
        for _dn, attrs in lo.search(filter='(objectClass=univentionRadiusClient)'):
            hostname = attrs.get('cn', [b'None'])[0].decode('UTF-8')
            shared_secret = attrs.get('univentionRadiusClientSharedSecret', [b'None'])[0].decode('UTF-8')
            ipaddr = attrs.get('aRecord', [b''])[0].decode('UTF-8') or attrs.get('aAAARecord', [b'None'])[0].decode('UTF-8')
            nas_type = attrs.get('univentionRadiusClientType', [b'other'])[0].decode('UTF-8')
            virtual_server = attrs.get('univentionRadiusClientVirtualServer', [b''])[0].decode('UTF-8')
            if hostname and ipaddr and shared_secret:
                print(f'Adding client {hostname} ({ipaddr})')
                fd.write('''client {} {{
\tipaddr\t\t= {}
\tsecret\t\t= {}
\tnas_type\t= {}
{}\tvirtual_server\t= {}
}}

'''.format(
                    hostname,
                    ipaddr,
                    shared_secret,
                    nas_type,
                    '' if virtual_server else '# ',
                    virtual_server or '...not specified...'),
                )

    shutil.move(fd.name, os.path.join(BASE_DIR, BASE_NAME))
    os.chmod('/etc/freeradius/3.0/clients.univention.conf', 0o600)
    os.chown('/etc/freeradius/3.0/clients.univention.conf', pwd.getpwnam('freerad').pw_uid, 0)


if __name__ == '__main__':
    main()
