#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_nvdefine_ctx
{
    TC_HANDLE        handle;
    uint32_t         nv_index;
    uint32_t         hierarchy;
    uint32_t         size;
    TC_BUFFER       *hierarchy_auth_msg;
};

TC_RC tpm2_nvdefine_init(struct api_ctx_st *api_ctx, int num, ...)
{
    TC_RC rc = TC_SUCCESS;
    struct tpm2_nvdefine_ctx* nctx = (struct tpm2_nvdefine_ctx*)malloc(sizeof(struct tpm2_nvdefine_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->size = 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_nvdefine_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_nvdefine(API_CTX *ctx)
{
    TC_RC rc = TC_SUCCESS;

    struct tpm2_nvdefine_ctx* nctx = (struct tpm2_nvdefine_ctx*)ctx->data;
    TC_HANDLE_CTX* tc_handle_ctx = (TC_HANDLE_CTX*)(nctx->handle);
    
    TPM2B_NV_PUBLIC public_info = TPM2B_EMPTY_INIT;
    TSS2L_SYS_AUTH_RESPONSE sessionsDataout;
    TSS2L_SYS_AUTH_COMMAND sessionsData = {
        .auths    = {{.sessionHandle = TPM2_RS_PW}},
        .count    = 1
    };
    TPM2B_AUTH nvAuth = TPM2B_EMPTY_INIT;

    public_info.size = sizeof(TPMI_RH_NV_INDEX) + sizeof(TPMI_ALG_HASH) + sizeof(TPMA_NV) + sizeof(UINT16) + sizeof(UINT16);
    public_info.nvPublic.nvIndex = nctx->nv_index;
    public_info.nvPublic.nameAlg = TPM2_ALG_SHA256;
    public_info.nvPublic.attributes = 0x2000A;
    public_info.nvPublic.dataSize = nctx->size;

    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_DefineSpace((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                                  nctx->hierarchy,
                                  &sessionsData,
                                  &nvAuth,
                                  &public_info,
                                  &sessionsDataout);

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