#include "process_cmd_TA.h"

hdm_return_code_t HDM_KG_generateNonce(uint32_t operation, uint32_t *nonce) {

        hdm_return_code_t ret = HDM_STATUS_SUCCESS;
        uint32_t tentative_nonce = HDM_TATA_ERROR;
        uint8_t hash[SHA256_DIGEST_LENGTH] = {0};
        uint32_t len = 0;

        HDM_LOG_DEBUG("Case: HDM_KG_generateNonce");

        *nonce = 0; // Default

        // Generate nonce
        while (tentative_nonce == HDM_TATA_ERROR) {
                ret = qsee_get_random_bytes(&tentative_nonce, sizeof(uint32_t));
        }
        if ( ret != 0 ){
                HDM_LOG("Error on generate nonce");
                HDM_LOG_DEBUG("Error on generate nonce ret = %d", ret);
                ret = HDM_INVALID_NONCE;
                goto exit;
        }
        HDM_LOG("Generated nonce");
        HDM_LOG_DEBUG("Generated tentative_nonce = 0x%x", tentative_nonce);

        // Store nonce
        KGNonce = tentative_nonce;
        KGOperation = operation;
        *nonce = tentative_nonce;
exit:

        return ret;
}

hdm_return_code_t HDM_KG_get_status(uint32_t *device_block, uint32_t *compromise_block) {
        HDM_LOG("Starting %s", __func__);

        hdm_return_code_t ret = HDM_STATUS_FAIL;
        tz_hdm_rpmb_t rpmb_data;

        uint8_t kg_service_name[JWS_HEADER_SERVICE_NAME_LEN] = {0,};
        TEE_MemMove(kg_service_name, KG_SERVICE_NAME, strlen((char *) KG_SERVICE_NAME));

        ret = read_policy_rpmb(&rpmb_data);
        if (ret != HDM_STATUS_SUCCESS) {
                HDM_LOG_DEBUG("read_policy_rpmb FAIL ret = %d", ret);
                goto exit;
        }

        ret = get_curr_service_index(rpmb_data, (uint8_t *) kg_service_name);
        if (ret != HDM_STATUS_SUCCESS) {
                HDM_LOG_DEBUG("get_curr_service_index FAIL ret = %d", ret);
                goto exit;
        }

        HDM_LOG_DEBUG("KG device block = 0x%X", rpmb_data.data[current_service_index].device_block);
        HDM_LOG_DEBUG("KG compromise block = 0x%X", rpmb_data.data[current_service_index].compromise_block);

        *device_block = rpmb_data.data[current_service_index].device_block;
        *compromise_block = rpmb_data.data[current_service_index].compromise_block;
        ret = HDM_STATUS_SUCCESS;
exit:
        return ret;
}
