#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_verifysignature_ctx
{
    TC_HANDLE        handle;
    uint32_t         key_index;
    TC_BUFFER       *key_auth_msg;
    TC_ALG           alg_sign;
    TC_ALG           alg_hash;
    TC_BUFFER       *plain_text;
    TC_BUFFER       *sign_text;
    unsigned int    *verify;
};

TC_RC tpm2_verifysignature_init(struct api_ctx_st *api_ctx, int num, ...)
{
    TC_RC rc = TC_SUCCESS;
    struct tpm2_verifysignature_ctx* vctx = (struct tpm2_verifysignature_ctx*)malloc(sizeof(struct tpm2_verifysignature_ctx));

    va_list ap;
    va_start(ap, num);
    vctx->handle = va_arg(ap, TC_HANDLE);
    vctx->key_index = va_arg(ap, uint32_t);
    vctx->key_auth_msg = va_arg(ap, TC_BUFFER*);
    vctx->alg_sign = va_arg(ap, TC_ALG);
    vctx->alg_hash = va_arg(ap, TC_ALG);
    vctx->plain_text = va_arg(ap, TC_BUFFER*);
    vctx->sign_text = va_arg(ap, TC_BUFFER*);
    vctx->verify = va_arg(ap, unsigned int*);
    va_end(ap);

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

TC_RC tpm2_verifysignature_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_verifysignature(API_CTX *ctx)
{
    TC_RC rc = TC_SUCCESS;

    struct tpm2_verifysignature_ctx* vctx = (struct tpm2_verifysignature_ctx*)ctx->data;
    TC_HANDLE_CTX* tc_handle_ctx = (TC_HANDLE_CTX*)(vctx->handle);

    TPM2B_DIGEST digest = TPM2B_TYPE_INIT(TPM2B_DIGEST, buffer);
    TPMT_SIGNATURE signature;
    TPMT_TK_VERIFIED validation;
    TSS2L_SYS_AUTH_RESPONSE sessionsDataout;
    TSS2L_SYS_AUTH_COMMAND sessionsData = {
        .auths    = {{.sessionHandle = TPM2_RS_PW}},
        .count    = 1
    };
    
    if (vctx->key_auth_msg != NULL) {
        if (vctx->key_auth_msg->size > sizeof(TPMU_HA)) {
            log_error("The length of the key authorization authentication password exceeds the limit\n");
            return TC_AUTH_HMAC_OVERSIZE;
        }
        sessionsData.auths[0].hmac.size = vctx->key_auth_msg->size;
        memcpy(sessionsData.auths[0].hmac.buffer,
               vctx->key_auth_msg->buffer,
               vctx->key_auth_msg->size);
    }

    TPMI_ALG_HASH hash_Alg;

    switch (vctx->alg_hash)
    {
    case TC_SHA256:
        hash_Alg = TPM2_ALG_SHA256;
        break;
    case TC_SM3:
        hash_Alg = TPM2_ALG_SM3_256;
        break;
    case TC_SHA1:
        hash_Alg = TPM2_ALG_SHA1;
        break;    
    default:
        log_error("unrecogize the tpm2_hash algorithms, %d\n", vctx->alg_hash);
        return TC_UNDEFINE_ALGO;
    }

    if ((vctx->sign_text->size > TPM2_MAX_RSA_KEY_BYTES) || (vctx->plain_text->size > TPM2_MAX_DIGEST_BUFFER) ) {
        log_error("The length of the data to be verified exceeds the limit\n");
        return TC_VERIFY_BUFFER_OVERSIZE;
    }
    signature.signature.rsassa.hash = hash_Alg;
    signature.signature.rsapss.sig.size = vctx->sign_text->size;
    memcpy(signature.signature.rsapss.sig.buffer,
           vctx->sign_text->buffer,
           vctx->sign_text->size);

    switch (vctx->alg_sign)
    {
    case TC_RSA:
        signature.sigAlg = TPM2_ALG_RSASSA;
        break;
    case TC_SM2:
        signature.sigAlg = TPM2_ALG_SM2;
        break;    
    default:
        log_error("unrecogize the crypto algorithms, %d\n", vctx->alg_sign);
        return TC_UNDEFINE_ALGO;
    }

    rc = tpm_hash((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                   hash_Alg,
                   TPM2_RH_OWNER,
                   &digest,
                   vctx->plain_text->buffer,
                   vctx->plain_text->size);
    if (rc != TSS2_RC_SUCCESS) {
        log_error("Failed to hash message\n");
        goto end;
    }    

    if (vctx->key_index > MAX_OBJECT_NODE_COUNT) {
        rc = Tss2_Sys_VerifySignature((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                                       vctx->key_index,
                                       NULL,
                                       &digest,
                                       &signature,
                                       &validation,
                                       &sessionsDataout);
    }else{
        if (vctx->key_index > tc_handle_ctx->handle.tc_object->count) {
            log_error("Invalid object index\n");
            return TC_OBJECT_INDEX;
        }

        rc = Tss2_Sys_VerifySignature((TSS2_SYS_CONTEXT*)tc_handle_ctx->handle.tc_context,
                                       tc_handle_ctx->handle.tc_object->node_info[vctx->key_index]->obj_handle,
                                       NULL,
                                       &digest,
                                       &signature,
                                       &validation,
                                       &sessionsDataout);
    }
end:
    if (rc != TC_SUCCESS) {
        log_error("Failed to run api_verifysignature:0x%0x\n", rc);
        rc = TC_COMMAND_VERIFYSIGNATURE;
        *vctx->verify = 0;
    }else{
        *vctx->verify = 1;
    }

    return TC_SUCCESS;
}