#include <stdarg.h>

#include "tc_private/tc_handle.h"
#include "tc_private/tc_private.h"

#include "log/log.h"

#include "tc_tpm2.h"
#include "tpm2_common.h"

#include "tc_type.h"
#include "tc_errcode.h"

struct tpm2_nvrelease_ctx
{
    TC_HANDLE        handle;
    uint32_t         nv_index;
    uint32_t         hierarchy;
    TC_BUFFER       *hierarchy_auth_msg;
};

TC_RC tpm2_nvrelease_init(struct api_ctx_st *api_ctx, int num, ...)
{
    TC_RC rc = TC_SUCCESS;
    struct tpm2_nvrelease_ctx* nctx = (struct tpm2_nvrelease_ctx*)malloc(sizeof(struct tpm2_nvrelease_ctx));

    va_list ap;
    va_start(ap, num);
    nctx->handle = va_arg(ap, TC_HANDLE);
    nctx->nv_index = va_arg(ap, uint32_t);
    nctx->hierarchy = va_arg(ap, uint32_t);
    nctx->hierarchy_auth_msg = va_arg(ap, TC_BUFFER*);
    va_end(ap);

    api_ctx->data = (HANDLE_DATA*)nctx;
    return rc;
}

TC_RC tpm2_nvrelease_free(struct api_ctx_st *api_ctx)
{
    TC_RC rc = TC_SUCCESS;  
    free(api_ctx->data); 
    api_ctx->data = NULL;
    api_ctx->cmd_code = API_NULL;
    return rc;
}

TC_RC tpm2_nvrelease(API_CTX *ctx)
{
    TC_RC rc = TC_SUCCESS;

    struct tpm2_nvrelease_ctx* nctx = (struct tpm2_nvrelease_ctx*)ctx->data;
    TC_HANDLE_CTX* tc_handle_ctx = (TC_HANDLE_CTX*)(nctx->handle);

    TSS2L_SYS_AUTH_RESPONSE sessionsDataout;
    TSS2L_SYS_AUTH_COMMAND sessionsData = {
        .auths    = {{.sessionHandle = TPM2_RS_PW}},
        .count    = 1
    };
    TPM2B_AUTH nvAuth = TPM2B_EMPTY_INIT;

    if (nctx->hierarchy_auth_msg != NULL) {
        if (nctx->hierarchy_auth_msg->size > sizeof(TPMU_HA)) {
            log_error("The hierarchy authorization authentication password exceeds the limit\n");
            return TC_AUTH_HMAC_OVERSIZE;
        }
        sessionsData.auths[0].hmac.size = nctx->hierarchy_auth_msg->size;
        memcpy(sessionsData.auths[0].hmac.buffer,
               nctx->hierarchy_auth_msg->buffer,
               nctx->hierarchy_auth_msg->size);
    }

    rc = Tss2_Sys_NV_UndefineSpace((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                                    nctx->hierarchy,
                                    nctx->nv_index,
                                    &sessionsData,
                                    &sessionsDataout);

    if (rc != TSS2_RC_SUCCESS) {
        log_error("Failed to run api_nvrelease:0x%0x\n", rc);
        rc = TC_COMMAND_NVRELEASE;
    }
    return  rc;
}