GSSAPI="BASE"  # This ensures that a full module is generated by Cython

from gssapi.raw.cython_types cimport *
from gssapi.raw.cython_converters cimport c_create_oid_set
from gssapi.raw.cython_converters cimport c_get_mech_oid_set
from gssapi.raw.cython_converters cimport c_py_ttl_to_c, c_c_ttl_to_py
from gssapi.raw.creds cimport Creds
from gssapi.raw.names cimport Name
from gssapi.raw.oids cimport OID

from gssapi.raw.misc import GSSError
from gssapi.raw.named_tuples import AcquireCredResult, AddCredResult


cdef extern from "python_gssapi_ext.h":
    OM_uint32 gss_export_cred(OM_uint32 *min_stat, gss_cred_id_t cred_handle,
                              gss_buffer_t token) nogil

    OM_uint32 gss_import_cred(OM_uint32 *min_stat, gss_buffer_t token,
                              gss_cred_id_t *cred_handle) nogil


def export_cred(Creds creds not None):
    # GSS_C_EMPTY_BUFFER
    cdef gss_buffer_desc exported_creds = gss_buffer_desc(0, NULL)

    cdef OM_uint32 maj_stat, min_stat

    with nogil:
        maj_stat = gss_export_cred(&min_stat, creds.raw_creds, &exported_creds)

    if maj_stat == GSS_S_COMPLETE:
        res = (<char*>exported_creds.value)[:exported_creds.length]
        gss_release_buffer(&min_stat, &exported_creds)
        return res
    else:
        raise GSSError(maj_stat, min_stat)


def import_cred(token not None):
    cdef gss_buffer_desc token_buffer = gss_buffer_desc(len(token), token)

    cdef gss_cred_id_t creds

    cdef OM_uint32 maj_stat, min_stat

    with nogil:
        maj_stat = gss_import_cred(&min_stat, &token_buffer, &creds)

    cdef Creds res
    if maj_stat == GSS_S_COMPLETE:
        res = Creds()
        res.raw_creds = creds
        return res
    else:
        raise GSSError(maj_stat, min_stat)
