build: sync build scripts with ndn-cxx

Change-Id: Ic1c7df3f2cf475d301c4943b7e0ec57c75103613
diff --git a/.waf-tools/boost.py b/.waf-tools/boost.py
index d7e0107..4b2ede5 100644
--- a/.waf-tools/boost.py
+++ b/.waf-tools/boost.py
@@ -56,6 +56,7 @@
 
 BOOST_LIBS = ['/usr/lib', '/usr/local/lib', '/opt/local/lib', '/sw/lib', '/lib']
 BOOST_INCLUDES = ['/usr/include', '/usr/local/include', '/opt/local/include', '/sw/include']
+
 BOOST_VERSION_FILE = 'boost/version.hpp'
 BOOST_VERSION_CODE = '''
 #include <iostream>
@@ -90,13 +91,18 @@
 
 BOOST_LOG_CODE = '''
 #include <boost/log/trivial.hpp>
+int main() { BOOST_LOG_TRIVIAL(info) << "boost_log is working"; }
+'''
+
+BOOST_LOG_SETUP_CODE = '''
+#include <boost/log/trivial.hpp>
 #include <boost/log/utility/setup/console.hpp>
 #include <boost/log/utility/setup/common_attributes.hpp>
 int main() {
 	using namespace boost::log;
 	add_common_attributes();
 	add_console_log(std::clog, keywords::format = "%Message%");
-	BOOST_LOG_TRIVIAL(debug) << "log is working" << std::endl;
+	BOOST_LOG_TRIVIAL(info) << "boost_log_setup is working";
 }
 '''
 
@@ -145,7 +151,7 @@
 	opt.add_option('--boost-abi', type='string', default='', dest='boost_abi',
 				   help='''select libraries with tags (gd for debug, static is automatically added),
 				   see doc Boost, Getting Started, chapter 6.1''')
-	opt.add_option('--boost-linkage_autodetect', action="store_true", dest='boost_linkage_autodetect',
+	opt.add_option('--boost-linkage_autodetect', action='store_true', dest='boost_linkage_autodetect',
 				   help="auto-detect boost linkage options (don't get used to it / might break other stuff)")
 	opt.add_option('--boost-toolset', type='string',
 				   default='', dest='boost_toolset',
@@ -175,7 +181,7 @@
 		try:
 			txt = node.read()
 		except EnvironmentError:
-			Logs.error("Could not read the file %r" % node.abspath())
+			Logs.error('Could not read the file %r' % node.abspath())
 		else:
 			re_but1 = re.compile('^#define\\s+BOOST_LIB_VERSION\\s+"(.+)"', re.M)
 			m1 = re_but1.search(txt)
@@ -183,7 +189,7 @@
 			m2 = re_but2.search(txt)
 			if m1 and m2:
 				return (m1.group(1), m2.group(1))
-	return self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[d], execute=True, define_ret=True).split(":")
+	return self.check_cxx(fragment=BOOST_VERSION_CODE, includes=[d], execute=True, define_ret=True).split(':')
 
 @conf
 def boost_get_includes(self, *k, **kw):
@@ -194,10 +200,10 @@
 		if self.__boost_get_version_file(d):
 			return d
 	if includes:
-		self.end_msg('headers not found in %s' % includes)
+		self.end_msg('headers not found in %s' % includes, 'YELLOW')
 		self.fatal('The configuration failed')
 	else:
-		self.end_msg('headers not found, please provide a --boost-includes argument (see help)')
+		self.end_msg('headers not found, please provide a --boost-includes argument (see help)', 'YELLOW')
 		self.fatal('The configuration failed')
 
 
@@ -240,10 +246,10 @@
 					break
 	if not path:
 		if libs:
-			self.end_msg('libs not found in %s' % libs)
+			self.end_msg('libs not found in %s' % libs, 'YELLOW')
 			self.fatal('The configuration failed')
 		else:
-			self.end_msg('libs not found, please provide a --boost-libs argument (see help)')
+			self.end_msg('libs not found, please provide a --boost-libs argument (see help)', 'YELLOW')
 			self.fatal('The configuration failed')
 
 	self.to_log('Found the boost path in %r with the libraries:' % path)
@@ -313,7 +319,7 @@
 					libs.append(format_lib_name(file.name))
 					break
 			else:
-				self.end_msg('lib %s not found in %s' % (lib, path.abspath()))
+				self.end_msg('lib %s not found in %s' % (lib, path.abspath()), 'YELLOW')
 				self.fatal('The configuration failed')
 		return libs
 
@@ -354,7 +360,7 @@
 	#      ... -mt is also the pthreads flag for HP/aCC
 	# -lpthread: GNU Linux, etc.
 	# --thread-safe: KAI C++
-	if Utils.unversioned_sys_platform() == "sunos":
+	if Utils.unversioned_sys_platform() == 'sunos':
 		# On Solaris (at least, for some versions), libc contains stubbed
 		# (non-functional) versions of the pthreads routines, so link-based
 		# tests will erroneously succeed.  (We need to link with -pthreads/-mt/
@@ -362,23 +368,22 @@
 		# a function called by this macro, so we could check for that, but
 		# who knows whether they'll stub that too in a future libc.)  So,
 		# we'll just look for -pthreads and -lpthread first:
-		boost_pthread_flags = ["-pthreads", "-lpthread", "-mt", "-pthread"]
+		boost_pthread_flags = ['-pthreads', '-lpthread', '-mt', '-pthread']
 	else:
-		boost_pthread_flags = ["", "-lpthreads", "-Kthread", "-kthread", "-llthread", "-pthread",
-							   "-pthreads", "-mthreads", "-lpthread", "--thread-safe", "-mt"]
+		boost_pthread_flags = ['', '-lpthreads', '-Kthread', '-kthread', '-llthread', '-pthread',
+							   '-pthreads', '-mthreads', '-lpthread', '--thread-safe', '-mt']
 
 	for boost_pthread_flag in boost_pthread_flags:
 		try:
 			self.env.stash()
 			self.env['CXXFLAGS_%s' % var] += [boost_pthread_flag]
 			self.env['LINKFLAGS_%s' % var] += [boost_pthread_flag]
-			self.check_cxx(code=PTHREAD_CODE, msg=None, use=var, execute=False)
-
+			self.check_cxx(code=PTHREAD_CODE, msg=None, use=var, execute=False, quiet=True)
 			self.end_msg(boost_pthread_flag)
 			return
 		except self.errors.ConfigurationError:
 			self.env.revert()
-	self.end_msg('None')
+	self.end_msg('none')
 
 @conf
 def check_boost(self, *k, **kw):
@@ -403,21 +408,24 @@
 
 	var = kw.get('uselib_store', 'BOOST')
 
-	self.find_program('dpkg-architecture', var='DPKG_ARCHITECTURE', mandatory=False)
-	if self.env.DPKG_ARCHITECTURE:
-		deb_host_multiarch = self.cmd_and_log([self.env.DPKG_ARCHITECTURE[0], '-qDEB_HOST_MULTIARCH'])
-		BOOST_LIBS.insert(0, '/usr/lib/%s' % deb_host_multiarch.strip())
+	if not self.env.DONE_FIND_BOOST_COMMON:
+		self.find_program('dpkg-architecture', var='DPKG_ARCHITECTURE', mandatory=False)
+		if self.env.DPKG_ARCHITECTURE:
+			deb_host_multiarch = self.cmd_and_log([self.env.DPKG_ARCHITECTURE[0], '-qDEB_HOST_MULTIARCH'])
+			BOOST_LIBS.insert(0, '/usr/lib/%s' % deb_host_multiarch.strip())
 
-	self.start_msg('Checking boost includes')
-	self.env['INCLUDES_%s' % var] = inc = self.boost_get_includes(**params)
-	versions = self.boost_get_version(inc)
-	self.env.BOOST_VERSION = versions[0]
-	self.env.BOOST_VERSION_NUMBER = int(versions[1])
-	self.end_msg("%d.%d.%d" % (int(versions[1]) / 100000,
-							   int(versions[1]) / 100 % 1000,
-							   int(versions[1]) % 100))
-	if Logs.verbose:
-		Logs.pprint('CYAN', '	path : %s' % self.env['INCLUDES_%s' % var])
+		self.start_msg('Checking boost includes')
+		self.env['INCLUDES_%s' % var] = inc = self.boost_get_includes(**params)
+		versions = self.boost_get_version(inc)
+		self.env.BOOST_VERSION = versions[0]
+		self.env.BOOST_VERSION_NUMBER = int(versions[1])
+		self.end_msg('%d.%d.%d' % (int(versions[1]) / 100000,
+								   int(versions[1]) / 100 % 1000,
+								   int(versions[1]) % 100))
+		if Logs.verbose:
+			Logs.pprint('CYAN', '	path : %s' % self.env['INCLUDES_%s' % var])
+
+		self.env.DONE_FIND_BOOST_COMMON = True
 
 	if not params['lib'] and not params['stlib']:
 		return
@@ -429,7 +437,7 @@
 	self.env['STLIBPATH_%s' % var] = [path]
 	self.env['LIB_%s' % var] = libs
 	self.env['STLIB_%s' % var] = stlibs
-	self.end_msg('ok')
+	self.end_msg(' '.join(libs + stlibs))
 	if Logs.verbose:
 		Logs.pprint('CYAN', '	path : %s' % path)
 		Logs.pprint('CYAN', '	shared libs : %s' % libs)
@@ -450,15 +458,18 @@
 			self.check_cxx(fragment=BOOST_ERROR_CODE, use=var, execute=False)
 		if has_lib('thread'):
 			self.check_cxx(fragment=BOOST_THREAD_CODE, use=var, execute=False)
-		if has_lib('log'):
+		if has_lib('log') or has_lib('log_setup'):
 			if not has_lib('thread'):
 				self.env['DEFINES_%s' % var] += ['BOOST_LOG_NO_THREADS']
-			if has_shlib('log'):
+			if has_shlib('log') or has_shlib('log_setup'):
 				self.env['DEFINES_%s' % var] += ['BOOST_LOG_DYN_LINK']
-			self.check_cxx(fragment=BOOST_LOG_CODE, use=var, execute=False)
+			if has_lib('log_setup'):
+				self.check_cxx(fragment=BOOST_LOG_SETUP_CODE, use=var, execute=False)
+			else:
+				self.check_cxx(fragment=BOOST_LOG_CODE, use=var, execute=False)
 
 	if params.get('linkage_autodetect', False):
-		self.start_msg("Attempting to detect boost linkage flags")
+		self.start_msg('Attempting to detect boost linkage flags')
 		toolset = self.boost_get_toolset(kw.get('toolset', ''))
 		if toolset in ('vc',):
 			# disable auto-linking feature, causing error LNK1181
@@ -480,10 +491,10 @@
 			# we attempt to play with some known-to-work CXXFLAGS combinations
 			for cxxflags in (['/MD', '/EHsc'], []):
 				self.env.stash()
-				self.env["CXXFLAGS_%s" % var] += cxxflags
+				self.env['CXXFLAGS_%s' % var] += cxxflags
 				try:
 					try_link()
-					self.end_msg("ok: winning cxxflags combination: %s" % (self.env["CXXFLAGS_%s" % var]))
+					self.end_msg('ok: winning cxxflags combination: %s' % (self.env['CXXFLAGS_%s' % var]))
 					exc = None
 					break
 				except Errors.ConfigurationError as e:
@@ -491,17 +502,17 @@
 					exc = e
 
 			if exc is not None:
-				self.end_msg("Could not auto-detect boost linking flags combination, you may report it to boost.py author", ex=exc)
+				self.end_msg('Could not auto-detect boost linking flags combination, you may report it to boost.py author', ex=exc)
 				self.fatal('The configuration failed')
 		else:
-			self.end_msg("Boost linkage flags auto-detection not implemented (needed ?) for this toolchain")
+			self.end_msg('Boost linkage flags auto-detection not implemented (needed ?) for this toolchain')
 			self.fatal('The configuration failed')
 	else:
 		self.start_msg('Checking for boost linkage')
 		try:
 			try_link()
 		except Errors.ConfigurationError as e:
-			self.end_msg("Could not link against boost libraries using supplied options")
+			self.end_msg('Could not link against boost libraries using supplied options', 'YELLOW')
 			self.fatal('The configuration failed')
 		self.end_msg('ok')
 
diff --git a/.waf-tools/coverage.py b/.waf-tools/coverage.py
index ce92883..cc58165 100644
--- a/.waf-tools/coverage.py
+++ b/.waf-tools/coverage.py
@@ -1,15 +1,15 @@
 # -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
 
-from waflib import TaskGen, Logs
+from waflib import TaskGen
 
 def options(opt):
-    opt.add_option('--with-coverage', action='store_true', default=False, dest='with_coverage',
-                   help='''Set compiler flags for gcc to enable code coverage information''')
+    opt.add_option('--with-coverage', action='store_true', default=False,
+                   help='Add compiler flags to enable code coverage information')
 
 def configure(conf):
     if conf.options.with_coverage:
         if not conf.options.debug:
-            conf.fatal("Code coverage flags require debug mode compilation (add --debug)")
+            conf.fatal('Code coverage flags require debug mode compilation (add --debug)')
         conf.check_cxx(cxxflags=['-fprofile-arcs', '-ftest-coverage', '-fPIC'],
                        linkflags=['-fprofile-arcs'], uselib_store='GCOV', mandatory=True)
 
diff --git a/.waf-tools/default-compiler-flags.py b/.waf-tools/default-compiler-flags.py
index 2be9d90..b69ca79 100644
--- a/.waf-tools/default-compiler-flags.py
+++ b/.waf-tools/default-compiler-flags.py
@@ -129,6 +129,10 @@
     def getGeneralFlags(self, conf):
         flags = super(GccBasicFlags, self).getGeneralFlags(conf)
         flags['CXXFLAGS'] += ['-std=c++14']
+        if Utils.unversioned_sys_platform() == 'linux':
+            flags['LINKFLAGS'] += ['-fuse-ld=gold']
+        elif Utils.unversioned_sys_platform() == 'freebsd':
+            flags['LINKFLAGS'] += ['-fuse-ld=lld']
         return flags
 
     def getDebugFlags(self, conf):
@@ -145,7 +149,7 @@
                               '-Wno-error=maybe-uninitialized', # Bug #1615
                               '-Wno-unused-parameter',
                               ]
-        flags['LINKFLAGS'] += ['-fuse-ld=gold', '-Wl,-O1']
+        flags['LINKFLAGS'] += ['-Wl,-O1']
         return flags
 
     def getOptimizedFlags(self, conf):
@@ -158,7 +162,7 @@
                               '-Wnon-virtual-dtor',
                               '-Wno-unused-parameter',
                               ]
-        flags['LINKFLAGS'] += ['-fuse-ld=gold', '-Wl,-O1']
+        flags['LINKFLAGS'] += ['-Wl,-O1']
         return flags
 
 class GccFlags(GccBasicFlags):
@@ -179,6 +183,8 @@
             # Bug #4296
             flags['CXXFLAGS'] += [['-isystem', '/usr/local/include'], # for Homebrew
                                   ['-isystem', '/opt/local/include']] # for MacPorts
+        if Utils.unversioned_sys_platform() == 'freebsd':
+            flags['CXXFLAGS'] += [['-isystem', '/usr/local/include']] # Bug #4790
         return flags
 
     def getDebugFlags(self, conf):
@@ -186,10 +192,6 @@
         flags['CXXFLAGS'] += ['-fcolor-diagnostics',
                               '-Wextra-semi',
                               '-Wundefined-func-template',
-                              '-Wno-error=deprecated-register',
-                              '-Wno-error=infinite-recursion', # Bug #3358
-                              '-Wno-error=keyword-macro', # Bug #3235
-                              '-Wno-error=unneeded-internal-declaration', # Bug #1588
                               '-Wno-unused-local-typedef', # Bugs #2657 and #3209
                               ]
         version = self.getCompilerVersion(conf)
diff --git a/.waf-tools/openssl.py b/.waf-tools/openssl.py
index de0f9dc..b35795f 100644
--- a/.waf-tools/openssl.py
+++ b/.waf-tools/openssl.py
@@ -19,23 +19,20 @@
 '''
 
 import re
-from waflib import Utils, Logs
+from waflib import Utils
 from waflib.Configure import conf
 
-OPENSSL_VERSION_FILE = 'opensslv.h'
 OPENSSL_DIR_OSX = ['/usr/local', '/opt/local', '/usr/local/opt/openssl']
 OPENSSL_DIR = ['/usr', '/usr/local', '/opt/local', '/sw']
 
 def options(opt):
     opt.add_option('--with-openssl', type='string', default=None, dest='openssl_dir',
-                   help='''Path to where OpenSSL is installed, e.g., /usr/local''')
-
+                   help='directory where OpenSSL is installed, e.g., /usr/local')
 
 @conf
 def __openssl_get_version_file(self, dir):
     try:
-        return self.root.find_dir(dir).find_node('%s/%s' % ('include/openssl',
-                                                            OPENSSL_VERSION_FILE))
+        return self.root.find_dir(dir).find_node('include/openssl/opensslv.h')
     except:
         return None
 
@@ -47,8 +44,8 @@
     if root and file:
         return (root, file)
 
-    openssl_dir = [];
-    if Utils.unversioned_sys_platform() == "darwin":
+    openssl_dir = []
+    if Utils.unversioned_sys_platform() == 'darwin':
         openssl_dir = OPENSSL_DIR_OSX
     else:
         openssl_dir = OPENSSL_DIR
@@ -66,10 +63,7 @@
 
 @conf
 def check_openssl(self, *k, **kw):
-    atleast_version = kw.get('atleast_version', 0)
-    var = kw.get('uselib_store', 'OPENSSL')
-
-    self.start_msg('Checking for OpenSSL lib')
+    self.start_msg('Checking for OpenSSL version')
     (root, file) = self.__openssl_find_root_and_version_file(*k, **kw)
 
     try:
@@ -88,18 +82,21 @@
     except:
         self.fatal('OpenSSL version file is not found or is not usable')
 
+    atleast_version = kw.get('atleast_version', 0)
     if int(version, 16) < atleast_version:
-        self.fatal("The version of OpenSSL is too old\n" +
-                   "Please upgrade your distribution or install newer version of OpenSSL library")
+        self.fatal('The version of OpenSSL is too old\n'
+                   'Please upgrade your distribution or manually install a newer version of OpenSSL')
 
-    kwargs = {}
+    if 'msg' not in kw:
+        kw['msg'] = 'Checking if OpenSSL library works'
+    if 'lib' not in kw:
+        kw['lib'] = ['ssl', 'crypto']
+    if 'uselib_store' not in kw:
+        kw['uselib_store'] = 'OPENSSL'
+    if 'define_name' not in kw:
+        kw['define_name'] = 'HAVE_%s' % kw['uselib_store']
     if root:
-        kwargs['includes'] = "%s/include" % root
-        kwargs['libpath'] = "%s/lib" % root
+        kw['includes'] = '%s/include' % root
+        kw['libpath'] = '%s/lib' % root
 
-    libcrypto = self.check_cxx(lib=['ssl', 'crypto'],
-                               msg='Checking if OpenSSL library works',
-                               define_name='HAVE_%s' % var,
-                               uselib_store=var,
-                               mandatory=True,
-                               **kwargs)
+    self.check_cxx(**kw)
diff --git a/.waf-tools/sphinx_build.py b/.waf-tools/sphinx_build.py
index e61da6e..b44a54f 100644
--- a/.waf-tools/sphinx_build.py
+++ b/.waf-tools/sphinx_build.py
@@ -44,28 +44,28 @@
     task.inputs.append(conf)
 
     confdir = conf.parent.abspath()
-    buildername = getattr(self, "builder", "html")
-    srcdir = getattr(self, "srcdir", confdir)
-    outdir = self.path.find_or_declare(getattr(self, "outdir", buildername)).get_bld()
-    doctreedir = getattr(self, "doctreedir", os.path.join(outdir.abspath(), ".doctrees"))
+    buildername = getattr(self, 'builder', 'html')
+    srcdir = getattr(self, 'srcdir', confdir)
+    outdir = self.path.find_or_declare(getattr(self, 'outdir', buildername)).get_bld()
+    doctreedir = getattr(self, 'doctreedir', os.path.join(outdir.abspath(), '.doctrees'))
 
     task.env['BUILDERNAME'] = buildername
     task.env['SRCDIR'] = srcdir
     task.env['DOCTREEDIR'] = doctreedir
     task.env['OUTDIR'] = outdir.abspath()
-    task.env['VERSION'] = "version=%s" % self.VERSION
-    task.env['RELEASE'] = "release=%s" % self.VERSION
+    task.env['VERSION'] = 'version=%s' % self.version
+    task.env['RELEASE'] = 'release=%s' % getattr(self, 'release', self.version)
 
     import imp
     confData = imp.load_source('sphinx_conf', conf.abspath())
 
-    if buildername == "man":
+    if buildername == 'man':
         for i in confData.man_pages:
             target = outdir.find_or_declare('%s.%d' % (i[1], i[4]))
             task.outputs.append(target)
 
             if self.install_path:
-                self.bld.install_files("%s/man%d/" % (self.install_path, i[4]), target)
+                self.bld.install_files('%s/man%d/' % (self.install_path, i[4]), target)
     else:
         task.outputs.append(outdir)
 
diff --git a/.waf-tools/sqlite3.py b/.waf-tools/sqlite3.py
index 3d4e46e..4f2c016 100644
--- a/.waf-tools/sqlite3.py
+++ b/.waf-tools/sqlite3.py
@@ -1,16 +1,15 @@
 #! /usr/bin/env python
 # encoding: utf-8
 
-from waflib import Options, Logs
 from waflib.Configure import conf
 
 def options(opt):
-    opt.add_option('--with-sqlite3', type='string', default=None,
-                   dest='with_sqlite3', help='''Path to SQLite3, e.g., /usr/local''')
+    opt.add_option('--with-sqlite3', type='string', default=None, dest='sqlite3_dir',
+                   help='directory where SQLite3 is installed, e.g., /usr/local')
 
 @conf
 def check_sqlite3(self, *k, **kw):
-    root = k and k[0] or kw.get('path', None) or Options.options.with_sqlite3
+    root = k and k[0] or kw.get('path', self.options.sqlite3_dir)
     mandatory = kw.get('mandatory', True)
     var = kw.get('uselib_store', 'SQLITE3')
 
@@ -20,8 +19,8 @@
                        define_name='HAVE_%s' % var,
                        uselib_store=var,
                        mandatory=mandatory,
-                       includes="%s/include" % root,
-                       libpath="%s/lib" % root)
+                       includes='%s/include' % root,
+                       libpath='%s/lib' % root)
     else:
         try:
             self.check_cfg(package='sqlite3',
diff --git a/tests/wscript b/tests/wscript
index a366fe6..f5a0875 100644
--- a/tests/wscript
+++ b/tests/wscript
@@ -1,27 +1,16 @@
 # -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
-from waflib import Utils
-
 top = '..'
 
 def build(bld):
-    if not bld.env["WITH_TESTS"]:
+    if not bld.env.WITH_TESTS:
         return
 
-    tests_main = bld(
-        target='tests-main',
-        name='tests-main',
-        features='cxx',
-        source="main.cpp",
+    tmp_path = 'TMP_TESTS_PATH="%s"' % bld.bldnode.make_node('tmp-tests')
+    bld.program(
+        target='../unit-tests',
+        name='unit-tests',
+        source=bld.path.ant_glob(['*.cpp', 'unit-tests/**/*.cpp']),
         use='ndn-cert BOOST',
-        )
-
-    unit_test = bld.program(
-        target="../unit-tests",
-        source=bld.path.ant_glob(['*.cpp', 'unit-tests/**/*.cpp'],
-                                 excl=['main.cpp']),
-        features=['cxx', 'cxxprogram'],
-        use='ndn-cert tests-main',
-        includes=['.'],
-        install_path=None,
-        defines='TMP_TESTS_PATH=\"%s/tmp-tests\"' % bld.bldnode,
-        )
+        includes='.',
+        defines=[tmp_path],
+        install_path=None)
diff --git a/wscript b/wscript
index 85fe3d5..d1f7740 100644
--- a/wscript
+++ b/wscript
@@ -1,63 +1,65 @@
 # -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
 
-VERSION = "0.1.0"
-APPNAME = "ndncert"
-BUGREPORT = "https://redmine.named-data.net/projects/ndncert"
-GIT_TAG_PREFIX = "ndncert-"
-
 from waflib import Context, Utils
 import os
 
+VERSION = '0.1.0'
+APPNAME = 'ndncert'
+GIT_TAG_PREFIX = 'ndncert-'
+
 def options(opt):
     opt.load(['compiler_cxx', 'gnu_dirs'])
-    opt.load(['boost', 'default-compiler-flags', 'sqlite3', 'openssl',
-              'coverage', 'sanitizers',
+    opt.load(['default-compiler-flags', 'coverage', 'sanitizers',
+              'boost', 'openssl', 'sqlite3',
               'doxygen', 'sphinx_build'],
              tooldir=['.waf-tools'])
 
-    certopt = opt.add_option_group("ndncert options")
-    certopt.add_option('--with-tests', action='store_true', default=False,
-                       help='Build unit tests')
+    opt_group = opt.add_option_group('ndncert Options')
+    opt_group.add_option('--with-tests', action='store_true', default=False,
+                         help='Build unit tests')
 
 def configure(conf):
     conf.load(['compiler_cxx', 'gnu_dirs',
-               'boost', 'default-compiler-flags', 'sqlite3', 'openssl',
+               'default-compiler-flags',
+               'boost', 'openssl', 'sqlite3',
                'doxygen', 'sphinx_build'])
 
+    conf.env.WITH_TESTS = conf.options.with_tests
+
     if 'PKG_CONFIG_PATH' not in os.environ:
         os.environ['PKG_CONFIG_PATH'] = Utils.subst_vars('${LIBDIR}/pkgconfig', conf.env)
-    conf.check_cfg(package='libndn-cxx', args=['--cflags', '--libs'],
-                   uselib_store='NDN_CXX', mandatory=True)
+    conf.check_cfg(package='libndn-cxx', args=['--cflags', '--libs'], uselib_store='NDN_CXX')
 
-    USED_BOOST_LIBS = ['system', 'filesystem', 'iostreams',
-                       'program_options', 'thread', 'log', 'log_setup']
+    conf.check_sqlite3()
+    conf.check_openssl(lib='crypto', atleast_version=0x1000200f) # 1.0.2
 
-    conf.env['WITH_TESTS'] = conf.options.with_tests
-    if conf.env['WITH_TESTS']:
-        USED_BOOST_LIBS += ['unit_test_framework']
-        conf.define('HAVE_TESTS', 1)
+    boost_libs = ['system', 'program_options', 'filesystem']
+    if conf.env.WITH_TESTS:
+        boost_libs.append('unit_test_framework')
 
-    conf.check_boost(lib=USED_BOOST_LIBS, mt=True)
+    conf.check_boost(lib=boost_libs, mt=True)
     if conf.env.BOOST_VERSION_NUMBER < 105800:
         conf.fatal('Minimum required Boost version is 1.58.0\n'
                    'Please upgrade your distribution or manually install a newer version of Boost'
                    ' (https://redmine.named-data.net/projects/nfd/wiki/Boost_FAQ)')
 
     conf.check_compiler_flags()
-    conf.check_openssl(mandatory=True, atleast_version=0x1000200f) # 1.1.1b
 
     # Loading "late" to prevent tests from being compiled with profiling flags
     conf.load('coverage')
-
     conf.load('sanitizers')
 
-    conf.define('SYSCONFDIR', conf.env['SYSCONFDIR'])
-
     # If there happens to be a static library, waf will put the corresponding -L flags
     # before dynamic library flags.  This can result in compilation failure when the
     # system has a different version of the ndncert library installed.
-    conf.env['STLIBPATH'] = ['.'] + conf.env['STLIBPATH']
+    conf.env.prepend_value('STLIBPATH', ['.'])
 
+    conf.define_cond('HAVE_TESTS', conf.env.WITH_TESTS)
+    conf.define('SYSCONFDIR', conf.env.SYSCONFDIR)
+    # The config header will contain all defines that were added using conf.define()
+    # or conf.define_cond().  Everything that was added directly to conf.env.DEFINES
+    # will not appear in the config header, but will instead be passed directly to the
+    # compiler on the command line.
     conf.write_config_header('src/ndncert-config.hpp')
 
 def build(bld):
@@ -65,7 +67,7 @@
               source=bld.path.ant_glob('src/**/*.cpp'),
               vnum=VERSION,
               cnum=VERSION,
-              use='NDN_CXX BOOST',
+              use='NDN_CXX BOOST OPENSSL SQLITE3',
               includes='src',
               export_includes='src',
               install_path='${LIBDIR}')
@@ -83,19 +85,19 @@
 
     bld.install_files(
         dest='${INCLUDEDIR}/ndncert',
-        files=bld.path.ant_glob(['src/**/*.hpp', 'src/**/*.h']),
+        files=bld.path.ant_glob('src/**/*.hpp'),
         cwd=bld.path.find_dir('src'),
         relative_trick=True)
 
     bld.install_files(
         dest='${INCLUDEDIR}/ndncert',
-        files=bld.path.get_bld().ant_glob(['src/**/*.hpp']),
+        files=bld.path.get_bld().ant_glob('src/**/*.hpp'),
         cwd=bld.path.get_bld().find_dir('src'),
         relative_trick=False)
 
-    bld.install_files("${SYSCONFDIR}/ndncert", "ca.conf.sample")
-    bld.install_files("${SYSCONFDIR}/ndncert", "client.conf.sample")
-    bld.install_files("${SYSCONFDIR}/ndncert", "ndncert-mail.conf.sample")
+    bld.install_files('${SYSCONFDIR}/ndncert', ['ca.conf.sample',
+                                                'client.conf.sample',
+                                                'ndncert-mail.conf.sample'])
 
     bld(features='subst',
         name='ndncert-send-email-challenge',