#!/usr/bin/python3
# SPDX-FileCopyrightText: 2015-2026 Univention GmbH
# SPDX-License-Identifier: AGPL-3.0-only


from __future__ import annotations

import datetime
import sys
from argparse import ArgumentParser, RawDescriptionHelpFormatter

import univention.uldap


class LicenseCheckError(Exception):
    """Generic error during license check"""


class LicenseExpired(LicenseCheckError):
    """The license is expired"""


class LicenseNotFound(LicenseCheckError):
    """The license cannot be found in LDAP"""


def is_CSP_license(lo: univention.uldap.access | None = None) -> bool:
    """
    Function to detect if installed license is a cloud service provider license (CSP).

    :param univention.uldap.access lo: Optional |LDAP| connection to re-use. Otherwise a new |LDAP| connection with machine credentials is created.
    :returns: `True` if a valid CSP license has been found or `False` if a valid non-CSP license has been found.
    :raises LicenseNotFound: if no license was found.
    :raises LicenseExpired: if the license has expired.
    """
    if not lo:
        lo = univention.uldap.getMachineConnection()

    result = lo.search(filter='(&(objectClass=univentionLicense)(cn=admin))', attr=['univentionLicenseEndDate', 'univentionLicenseOEMProduct'])
    if not result:
        raise LicenseNotFound()
    attrs = result[0][1]

    now = datetime.date.today()
    enddate = attrs.get('univentionLicenseEndDate', [b'01.01.1970'])[0].decode('ASCII', 'replace')
    if enddate != "unlimited":
        (day, month, year) = enddate.split('.', 2)
        then = datetime.date(int(year), int(month), int(day))
        if now > then:
            raise LicenseExpired('endDate = %s' % (enddate,))

    return b'CSP' in attrs.get('univentionLicenseOEMProduct', [])


if __name__ == '__main__':
    description = '''Checks the installed UCS license and returns an appropriate
exitcode depending on the license status and license type.

Possible exitcodes:
0:  UCS license is valid and contains 'CSP' in the list of OEM products
10: UCS license is valid and does not contain 'CSP' in the list of OEM products
11: UCS license is expired
12: UCS license is invalid or not found'''

    parser = ArgumentParser(
        description=description,
        formatter_class=RawDescriptionHelpFormatter,
    )
    parser.parse_args()

    try:
        result = is_CSP_license()
    except LicenseExpired:
        print('License expired')
        sys.exit(11)
    except LicenseNotFound:
        print('License not found')
        sys.exit(12)
    except LicenseCheckError:
        print('License verification error')
        sys.exit(12)

    print('CSP=%s' % (result,))
    if not result:
        sys.exit(10)

    sys.exit(0)
