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

from gssapi.raw.cython_types cimport *
from gssapi.raw.ext_buffer_sets cimport *
from gssapi.raw.misc import GSSError
from gssapi.raw.oids cimport OID
from gssapi.raw.creds cimport Creds

cdef extern from "python_gssapi_ext.h":

    OM_uint32 gss_set_cred_option(OM_uint32 *minor_status,
                                  gss_cred_id_t *cred,
                                  const gss_OID desired_object,
                                  const gss_buffer_t value) nogil


def set_cred_option(OID desired_aspect not None, Creds creds=None, value=None):
    cdef gss_buffer_desc value_buffer
    if value is not None:
        value_buffer = gss_buffer_desc(len(value), value)
    else:
        # GSS_C_EMPTY_BUFFER
        value_buffer = gss_buffer_desc(0, NULL)

    cdef Creds output_creds = creds
    if output_creds is None:
        output_creds = Creds()

    cdef OM_uint32 maj_stat, min_stat

    with nogil:
        maj_stat = gss_set_cred_option(&min_stat,
                                       &output_creds.raw_creds,
                                       &desired_aspect.raw_oid,
                                       &value_buffer)

    if maj_stat == GSS_S_COMPLETE:
        return output_creds
    else:
        raise GSSError(maj_stat, min_stat)
