/*
 * Copyright (c) 2016 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Created in Samsung Ukraine R&D Center (SRK) under a contract between
 * LLC "Samsung Electronics Ukraine Company" (Kiev, Ukraine)
 * and "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
 *
 * Created on: Mar 17, 2016
 * Author: Oleksii Kachkan <o.kachkan@samsung.com>
 * Brief: Log functions whitch print to kernel log
 */

#include "TigerLogging.h"
#include "TigerTci.h"
#include "TzwMemory.h"
#include "TzwString.h"

#include <mbedtls/error.h>
#include <mbedtls/base64.h>
#include <mbedtls/pk.h>

#include <stdio.h>

#define MBEDTLS_ERROR_MSG_LENGTH 128

void logObject(TzwSfsObject_t object) {
    (void) object;

#if !defined(TIGER_RELEASE)
    TEE_ObjectInfo info;
    tzwMemFill(&info, 0, sizeof(info));

    TEE_Result status = tzwGetSfsObjectInfo(object, &info);
    if (TEE_SUCCESS != status) {
        LOG_E("Failed to tzwGetSfsObjectInfo status = %x", status);
        return;
    }

    LOG_D("Object [%d/%d]", info.dataPosition, info.dataSize);
#endif
}

void logMbedtlsError(int errorCode, const char* const extraMessage) {
    (void) errorCode;
    (void) extraMessage;

#if !defined(TIGER_RELEASE)
    char buf[MBEDTLS_ERROR_MSG_LENGTH];

    // get text error
    mbedtls_strerror(errorCode, buf, MBEDTLS_ERROR_MSG_LENGTH);

    LOG_E("%s; mbedtls error: %s", extraMessage, buf);
#endif
}

void logByteArrayBase64(const uint8_t* ba, size_t length, const char* label) {
    (void) ba;
    (void) length;
    (void) label;

#if !defined(TIGERFP_RELEASE)
    uint8_t* buf = NULL;

    do {
        int ret = 0;
        size_t bufLen = 0;

        ret = mbedtls_base64_encode(NULL, 0, &bufLen, ba, length);
        if (0 == bufLen) {
            LOG_E("Cannot get buffer length.");
            break;
        }

        buf = tzwMalloc(bufLen);
        if (NULL == buf) {
            LOG_E("Failed to allocate buffer!");
            break;
        }

        ret = mbedtls_base64_encode(buf, bufLen, &bufLen, ba, length);
        if (0 != ret) {
            LOG_E("Encode Base64 failed.");
            logMbedtlsError(ret, "mbedtls_base64_encode");
            break;
        }
        logByteArrayString(buf, bufLen, label);
    } while (0);

    tzwFree(buf);
#endif
}

void logRsaKeyPair(TigerKeyPair_t* keyPair, const char* alias) {
    const size_t pemBufSize = 1024;
    unsigned char* pemBuf = tzwMalloc(pemBufSize);
    if (pemBuf == NULL) {
        return;
    }

    int ret = mbedtls_pk_write_pubkey_pem(tigerGetKeyPairContext(keyPair), pemBuf, pemBufSize);
    if (0 != ret) {
        logMbedtlsError(ret, "Could not write pem.");
    } else {
        logByteArrayString(pemBuf, strlen((const char*) pemBuf), alias);
    }
    tzwFree(pemBuf);
}
