/*
 * Copyright (C) 2016-2018, Samsung Electronics Co., Ltd.
 * */

/*
 * To enable logs in BoringSSL:
 *  - define ENABLE_SSL_LOG macros at compile time, e.g. uncomment corresponding
 *    line in boringssl_defaults section of Android.bp.sec.bldpp file
 *  - include <openssl/log.h>
 *
 * To enable logs outside BoringSSL:
 *  - define ENABLE_SSL_LOG macros at compile time to enable logs
 *  - for Android builds define ANDROID_LOG macros at compile time to use
 *    Android logging subsystem
 *  - include <openssl/log.h>
 *
 * Example:
 *
 * #include <openssl/log.h>
 * ...
 * LOGE("this is an example of ERROR message");
 * LOGW("this is an example of WARNING message");
 * LOGI("this is an example of INFORMATIONAL message");
 * LOGD("this is an example of DEBUG message");
 * ...
 *
 * */

#ifndef OPENSSL_HEADER_SSL_DEBUG_H
#define OPENSSL_HEADER_SSL_DEBUG_H

#ifdef ENABLE_SSL_LOG

#include <string.h>
#define _GET_FILENAME(x) (strrchr(x, '/') ? strrchr(x, '/') + 1 : x)

#if ((__SIZEOF_INT__) == 8) || ((__SIZEOF_POINTER__) == 8)
#define SSL_TAG "BoringSSL_64"
#else
#define SSL_TAG "BoringSSL_32"
#endif //((__SIZEOF_INT__) == 8) || ((__SIZEOF_POINTER__) == 8)

/* For Android build */
#ifdef ANDROID_LOG

#include <android/log.h>

#define LOGE(format,...) __android_log_print(ANDROID_LOG_ERROR, SSL_TAG, "%s() [%s:%d]: " format, __FUNCTION__, _GET_FILENAME(__FILENAME__), __LINE__, ##__VA_ARGS__)
#define LOGW(format,...) __android_log_print(ANDROID_LOG_WARN,  SSL_TAG, "%s() [%s:%d]: " format, __FUNCTION__, _GET_FILENAME(__FILENAME__), __LINE__, ##__VA_ARGS__)
#define LOGI(format,...) __android_log_print(ANDROID_LOG_INFO,  SSL_TAG, "%s() [%s:%d]: " format, __FUNCTION__, _GET_FILENAME(__FILENAME__), __LINE__, ##__VA_ARGS__)
#define LOGD(format,...) __android_log_print(ANDROID_LOG_DEBUG, SSL_TAG, "%s() [%s:%d]: " format, __FUNCTION__, _GET_FILENAME(__FILENAME__), __LINE__, ##__VA_ARGS__)

#else  //ANDROID_LOG

// #include <stdio.h> //BoringAdd

#define LOGE(format, ...) fprintf(stderr, "%s: %s() [%s:%d]: " format "\n", SSL_TAG, __FUNCTION__, _GET_FILENAME(__FILENAME__), __LINE__, ##__VA_ARGS__)
#define LOGW(format, ...) fprintf(stdout, "%s: %s() [%s:%d]: " format "\n", SSL_TAG, __FUNCTION__, _GET_FILENAME(__FILENAME__), __LINE__, ##__VA_ARGS__)
#define LOGI(format, ...) fprintf(stdout, "%s: %s() [%s:%d]: " format "\n", SSL_TAG, __FUNCTION__, _GET_FILENAME(__FILENAME__), __LINE__, ##__VA_ARGS__)
#define LOGD(format, ...) fprintf(stdout, "%s: %s() [%s:%d]: " format "\n", SSL_TAG, __FUNCTION__, _GET_FILENAME(__FILENAME__), __LINE__, ##__VA_ARGS__)

#endif //ANDROID_LOG

#else  //ENABLE_SSL_LOG

#define LOGE(...)
#define LOGW(...)
#define LOGI(...)
#define LOGD(...)

#endif //ENABLE_SSL_LOG


#endif /* OPENSSL_HEADER_SSL_DEBUG_H */
