build FEATURE enable code coverage (#273)

diff --git a/CMakeLists.txt b/CMakeLists.txt
index 6b8521d..bd4f3f6 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -124,6 +124,35 @@
     option(ENABLE_BUILD_TESTS "Build tests" OFF)
     option(ENABLE_VALGRIND_TESTS "Build tests with valgrind" OFF)
 endif()
+option(ENABLE_COVERAGE "Build code coverage report from tests" OFF)
+
+if(ENABLE_COVERAGE)
+    find_program(PATH_GCOV NAMES gcov)
+    if(NOT PATH_GCOV)
+        message(WARNING "'gcov' executable not found! Disabling building code coverage report.")
+        set(ENABLE_COVERAGE OFF)
+    endif()
+
+    find_program(PATH_LCOV NAMES lcov)
+    if(NOT PATH_LCOV)
+        message(WARNING "'lcov' executable not found! Disabling building code coverage report.")
+        set(ENABLE_COVERAGE OFF)
+    endif()
+
+    find_program(PATH_GENHTML NAMES genhtml)
+    if(NOT PATH_GENHTML)
+        message(WARNING "'genhtml' executable not found! Disabling building code coverage report.")
+        set(ENABLE_COVERAGE OFF)
+    endif()
+
+    if(NOT CMAKE_COMPILER_IS_GNUCC)
+        message(WARNING "Compiler is not gcc! Coverage may break the tests!")
+    endif()
+
+    if(ENABLE_COVERAGE)
+        set(CMAKE_C_FLAGS_COVERAGE "${CMAKE_C_FLAGS} --coverage -fprofile-arcs -ftest-coverage")
+    endif()
+endif()
 
 # dependencies - pthread
 set(CMAKE_THREAD_PREFER_PTHREAD TRUE)
@@ -141,7 +170,7 @@
     find_package(OpenSSL REQUIRED)
     if(ENABLE_TLS)
         message(STATUS "OPENSSL found, required for TLS")
-        set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DNC_ENABLED_TLS")
+        set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_COVERAGE} -DNC_ENABLED_TLS")
     endif()
 
     target_link_libraries(netconf2 ${OPENSSL_LIBRARIES})
@@ -158,7 +187,7 @@
     target_link_libraries(netconf2 ${LIBSSH_LIBRARIES})
     list(APPEND CMAKE_REQUIRED_LIBRARIES ${LIBSSH_LIBRARIES})
     include_directories(${LIBSSH_INCLUDE_DIRS})
-    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DNC_ENABLED_SSH")
+    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_COVERAGE} -DNC_ENABLED_SSH")
 
     # crypt
     if(NOT ${CMAKE_SYSTEM_NAME} MATCHES "QNX")
@@ -173,7 +202,7 @@
 # dependencies - libval
 if(ENABLE_DNSSEC)
     find_package(LibVAL REQUIRED)
-    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -DENABLE_DNSSEC")
+    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${CMAKE_C_FLAGS_COVERAGE} -DENABLE_DNSSEC")
     target_link_libraries(netconf2 ${LIBVAL_LIBRARIES})
     include_directories(${LIBVAL_INCLUDE_DIRS})
 endif()