dnl +------------------------------------------------------------------+
dnl | Network UPS Tools: configure.ac                                  |
dnl +------------------------------------------------------------------+

dnl NUT version number is defined here, with a Git suffixed macro like
dnl    NUT_VERSION_MACRO "2.7.4-2838-gdfc3ac08"
dnl in include/nut_version.h (generated by make)
AC_INIT([nut],[2.8.0],[https://github.com/networkupstools/nut/issues])
AC_CONFIG_AUX_DIR([.])
AC_CONFIG_SRCDIR(server/upsd.c)
AC_CONFIG_MACRO_DIR([m4])
echo "Network UPS Tools version ${PACKAGE_VERSION}"
AC_CANONICAL_TARGET
NUT_CHECK_OS
NUT_STASH_WARNINGS
AC_CONFIG_HEADERS([include/config.h])
AC_PREFIX_DEFAULT(/usr/local/ups)
AM_INIT_AUTOMAKE([subdir-objects])

dnl we need Autoconf 2.61 or better to enable features of Posix that are extensions to C
dnl (and actually 2.64 or better for m4/ax_check_compile_flag.m4 when it is sourced)
AC_MSG_CHECKING(for autoconf macro to enable system extensions)
m4_version_prereq(2.61, [
	AC_MSG_RESULT(yes)
	AC_USE_SYSTEM_EXTENSIONS
], [
	AC_MSG_RESULT(no)
])

AC_PREREQ([2.64])

dnl Use "./configure --enable-maintainer-mode" to keep Makefile.in and Makefile
dnl in sync after Git updates.
AM_MAINTAINER_MODE

dnl Some systems have older autotools without direct macro support for PKG_CONF*
NUT_CHECK_PKGCONFIG


dnl Various version related processing
dnl ----------------------------------

dnl # the following is commented out, because the UPS_VERSION macro now
dnl # resides in include/nut_version.h, which is generated by Makefile.am,
dnl # rather than in include/config.h, which is generated by configure.  The
dnl # reason is that the SVN revision should be computed at compile time,
dnl # not configure time.
dnl AC_DEFINE_UNQUOTED(UPS_VERSION, "${PACKAGE_VERSION}", [NUT version])

dnl However, automatically define the tree version (mostly for AC_SUBST)
TREE_VERSION="`echo ${PACKAGE_VERSION} | awk '{ print substr($0,1,3) }'`"
AC_DEFINE_UNQUOTED(TREE_VERSION, "${TREE_VERSION}", [NUT tree version])

dnl Should not be necessary, since old servers have well-defined errors for
dnl unsupported commands:
NUT_NETVERSION="1.3"
AC_DEFINE_UNQUOTED(NUT_NETVERSION, "${NUT_NETVERSION}", [NUT network protocol version])


dnl Fix this early so we can expand with eval later
test "${prefix}" = "NONE" && prefix="${ac_default_prefix}"
test "${exec_prefix}" = "NONE" && exec_prefix='${prefix}'

CFLAGS=${CFLAGS-"-O"}

dnl NOTE: for definition of NUT_* autoconf macros, see m4/ directory
dnl and docs/macros.txt

dnl +------------------------------------------------------------------+
dnl | default values for things later on (can be overridden)           |

STATEPATH="/var/state/ups"

cgiexecdir='${exec_prefix}/cgi-bin'
driverexecdir='${exec_prefix}/bin'
htmldir='${prefix}/html'
pkgconfigdir='${libdir}/pkgconfig'
auglensdir='/usr/share/augeas/lenses/dist'
if test ! -d "${auglensdir}"; then
   auglensdir='/usr/share/augeas/lenses'
   if test ! -d "${auglensdir}"; then
      auglensdir=''
   fi
fi
hotplugdir='/etc/hotplug'
if test ! -d "${hotplugdir}"; then
   hotplugdir=''
fi
udevdir='/lib/udev'
if test ! -d "${udevdir}"; then
   udevdir='/etc/udev'
   if test ! -d "${udevdir}"; then
      udevdir=''
   fi
fi

devddir='/usr/local/etc/devd'
if test ! -d "${devddir}"; then
   devddir='/etc/devd'
   if test ! -d "${devddir}"; then
      devddir=''
   fi
fi

RUN_AS_USER="nobody"
RUN_AS_GROUP="nobody"
AS_IF([test -n "`getent group nogroup`" && ! test -n "`getent group "${RUN_AS_GROUP}"`"],
	[RUN_AS_GROUP="nogroup"]
)
PIDPATH="/var/run"

dnl Define directory where LIBOBJS replacement functions are
AC_CONFIG_LIBOBJ_DIR([common])

dnl +-------------------------------------------------------------------

dnl AC_PROG_CC
dnl Macro AC_PROG_CC_C99 is obsolete; use AC_PROG_CC
dnl Note that NUT does not support building with C89 anyway
dnl AC_PROG_CC_C99
dnl Needed for per-target flags
AM_PROG_CC_C_O
AC_PROG_CPP
AC_PROG_CXX
AC_PROG_CXX_C_O
AC_PROG_INSTALL
AC_PROG_MKDIR_P
AC_PROG_LN_S
AC_PROG_EGREP
AC_PATH_PROG(AR, ar)
AC_CHECK_TOOL(RANLIB, ranlib, :)
dnl Postpone call to LT_INIT/AC_CONFIG_FILES to allow disabling static lib
AC_C_BIGENDIAN
AC_C_INLINE
AC_C_FLEXIBLE_ARRAY_MEMBER
AC_C_VARARRAYS
dnl Note: the compiler/pragma/attr methods below are custom for NUT codebase:
NUT_COMPILER_FAMILY
dnl Help find warning/error details in a wall of text (must be processed before NUT_COMPILER_FAMILY_FLAGS):
NUT_ARG_ENABLE([Wcolor],
    [Request that compiler output is colorized (no = leave it up to compiler defaults)],
    [no])
NUT_COMPILER_FAMILY_FLAGS
AX_C_PRAGMAS
AX_C___ATTRIBUTE__
AX_C_PRINTF_STRING_NULL
AC_CHECK_FUNCS(flock lockf fcvt fcvtl pow10 round abs_val abs)

AC_CHECK_HEADER([float.h],
    [AC_DEFINE([HAVE_FLOAT_H], [1],
        [Define to 1 if you have <float.h>.])])
AC_CHECK_HEADER([math.h],
    [AC_DEFINE([HAVE_MATH_H], [1],
        [Define to 1 if you have <math.h>.])])
AC_CHECK_FUNCS(fabs fabsf fabsl, [], [],
[#ifdef HAVE_MATH_H
# include <math.h>
#endif
#ifdef HAVE_FLOAT_H
# include <float.h>
#endif])

AC_CHECK_HEADER([limits.h],
    [AC_DEFINE([HAVE_LIMITS_H], [1],
        [Define to 1 if you have <limits.h>.])])

AC_CHECK_HEADER([signal.h],
    [AC_DEFINE([HAVE_SIGNAL_H], [1],
        [Define to 1 if you have <signal.h>.])])

AC_CHECK_HEADER([sys/signal.h],
    [AC_DEFINE([HAVE_SYS_SIGNAL_H], [1],
        [Define to 1 if you have <sys/signal.h>.])])

AC_CHECK_HEADER([sys/resource.h],
    [AC_MSG_CHECKING([for struct rlimit and getrlimit()])
     AC_LANG_PUSH([C])
     AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#include <sys/resource.h>
],
[struct rlimit limit;
getrlimit(RLIMIT_NOFILE, &limit);
/* Do not care about actual return value in this test,
 * normally check for non-zero meaning to look in errno */
]
        )],
        [AC_DEFINE([HAVE_SYS_RESOURCE_H], [1],
            [Define to 1 if you have <sys/resource.h> with usable struct rlimit and getrlimit().])
         AC_MSG_RESULT([ok])
        ],
        [AC_MSG_RESULT([no])]
     )
     AC_LANG_POP([C])
    ]
)

AC_CHECK_HEADER([semaphore.h],
    [AC_DEFINE([HAVE_SEMAPHORE_H], [1],
        [Define to 1 if you have <sys/semaphore.h>.])
     AC_MSG_CHECKING([for sem_t, sem_init() and sem_destroy()])
     AC_LANG_PUSH([C])
     AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#include <semaphore.h>
],
[sem_t semaphore;
sem_init(&semaphore, 0, 4);
sem_destroy(&semaphore);
/* Do not care about actual return value in this test,
 * normally check for non-zero meaning to look in errno */
]
        )],
        [AC_DEFINE([HAVE_SEMAPHORE], [1],
            [Define to 1 if you have <sys/semaphore.h> with usable sem_t sem_init() and sem_destroy().])
         AC_MSG_RESULT([ok])
        ],
        [AC_MSG_RESULT([no])]
     )
     AC_LANG_POP([C])
    ]
)

AC_CHECK_FUNCS(cfsetispeed tcsendbreak)
AC_CHECK_FUNCS(seteuid setsid getpassphrase)
AC_CHECK_FUNCS(on_exit strptime setlogmask)
AC_CHECK_DECLS(LOG_UPTO, [], [], [#include <syslog.h>])

dnl These common routines are not available in strict C standard library
dnl compilation modes (not part of ANSI or later standard), only in GNU,
dnl POSIX or other extension modes. Note that on modern systems they are
dnl available, just hidden in headers - so AC_CHECK_FUNCS() finds them
dnl by adding a declaration, while the "real" codebase can't use them.
AC_MSG_NOTICE(
[-----------------------------------------------------------------------
The next few tests look for required C library routines; if something is
not found, you may need to enable a different C standard or extension macro
version. You may also have to configure without extreme warning levels
since autotools tests fail those on their own and assume system lacks
stuff (although note we try to not involve standard -W* flags here).
-----------------------------------------------------------------------])
dnl# AC_CHECK_FUNCS(strcasecmp strncasecmp,
dnl# 	[], [AC_MSG_WARN([Required C library routine not found; try adding __EXTENSIONS__])])
dnl These appear with CFLAGS="-std=c99 -D_POSIX_C_SOURCE=200112L":
dnl# Methods below currently do not cause build errors for C99+ modes so are
dnl# not tested as thoroughly as those further below:
 AC_CHECK_FUNCS(strtok_r fileno localtime_r sigemptyset sigaction,
	[], [AC_MSG_WARN([Required C library routine not found; try adding -D_POSIX_C_SOURCE=200112L])])

AC_LANG_PUSH([C])

AC_CHECK_HEADER([string.h],
    [AC_DEFINE([HAVE_STRING_H], [1],
        [Define to 1 if you have <string.h>.])])

AC_CHECK_HEADER([strings.h],
    [AC_DEFINE([HAVE_STRINGS_H], [1],
        [Define to 1 if you have <strings.h>.])])

CODE_STRINGINCL='#ifdef HAVE_STRING_H
#include <string.h>
#endif
#ifdef HAVE_STRINGS_H
#include <strings.h>
#endif'

AC_CACHE_CHECK([for strcasecmp(s1,s2)],
    [ac_cv_func_strcasecmp],
    [AX_RUN_OR_LINK_IFELSE(
        [AC_LANG_PROGRAM([$CODE_STRINGINCL],
            [if (strcasecmp("STR1", "str1") != 0) return 1])],
        [ac_cv_func_strcasecmp=yes], [ac_cv_func_strcasecmp=no]
    )])
AS_IF([test x"${ac_cv_func_strcasecmp}" = xyes],
    [AC_DEFINE([HAVE_STRCASECMP], 1, [defined if standard library has, and C standard allows, the strcasecmp(s1,s2) method])],
    [AC_MSG_WARN([Required C library routine strcasecmp not found; try adding __EXTENSIONS__])]
    )

AC_CACHE_CHECK([for strncasecmp(s1,s2,n)],
    [ac_cv_func_strncasecmp],
    [AX_RUN_OR_LINK_IFELSE(
        [AC_LANG_PROGRAM([$CODE_STRINGINCL],
            [if (strncasecmp("STR1", "strX", 2) != 0) return 1])],
        [ac_cv_func_strncasecmp=yes], [ac_cv_func_strncasecmp=no]
    )])
AS_IF([test x"${ac_cv_func_strncasecmp}" = xyes],
    [AC_DEFINE([HAVE_STRNCASECMP], 1, [defined if standard library has, and C standard allows, the strncasecmp(s1,s2,n) method])],
    [AC_MSG_WARN([Required C library routine strncasecmp not found; try adding __EXTENSIONS__])]
    )

AC_CACHE_CHECK([for strdup(s)],
    [ac_cv_func_strdup],
    [AX_RUN_OR_LINK_IFELSE(
        [AC_LANG_PROGRAM([$CODE_STRINGINCL],
            [[int res = 0;
char *t = "Test";
char *s = strdup(t);
if (!s || !(s[0]=='T'&&s[1]=='e'&&s[2]=='s'&&s[3]=='t'&&s[4]=='\0') || s == t) res = 1;
if (s) free (s);
if (res != 0) return res
/* autoconf adds ";return 0;" */
]])],
        [ac_cv_func_strdup=yes], [ac_cv_func_strdup=no]
    )])
AS_IF([test x"${ac_cv_func_strdup}" = xyes],
    [AC_DEFINE([HAVE_STRDUP], 1, [defined if standard library has, and C standard allows, the strdup(s) method])],
    [AC_MSG_WARN([Required C library routine strdup not found; try adding -D_POSIX_C_SOURCE=200112L])]
    )

AC_CACHE_CHECK([for usleep(us)],
    [ac_cv_func_usleep],
    [AC_COMPILE_IFELSE(
        [AC_LANG_PROGRAM([[#include <unistd.h>
        ]],
            [[useconds_t us = 1000;
if (usleep(us) != 0) return 1 /* per doc, no erros are returned actually*/
/* autoconf adds ";return 0;" */
]])],
        [ac_cv_func_usleep=yes], [ac_cv_func_usleep=no]
    )])
AS_IF([test x"${ac_cv_func_usleep}" = xyes],
    [AC_DEFINE([HAVE_USLEEP], 1, [defined if standard library has, and C standard allows, the usleep(us) method])],
    [AC_MSG_WARN([Required C library routine usleep not found; try adding -D_POSIX_C_SOURCE=200112L])]
    )

AC_LANG_POP([C])

dnl These routines' arg types differ in strict C standard mode
dnl from what they use in the modes expected by NUT codebase:
dnl   bind() :     /usr/include/x86_64-linux-gnu/sys/socket.h:123:12: note: expected '__CONST_SOCKADDR_ARG {aka union <anonymous>}' but argument is of type 'struct sockaddr *'
dnl   accept() :   /usr/include/x86_64-linux-gnu/sys/socket.h:243:12: note: expected '__SOCKADDR_ARG {aka union <anonymous>}' but argument is of type 'struct sockaddr *'
dnl   connect() :  /usr/include/x86_64-linux-gnu/sys/socket.h:137:12: note: expected '__CONST_SOCKADDR_ARG {aka union <anonymous>}' but argument is of type 'const struct sockaddr *'
dnl   sendto() :   /usr/include/x86_64-linux-gnu/sys/socket.h:163:16: note: expected '__CONST_SOCKADDR_ARG {aka union <anonymous>}' but argument is of type 'struct sockaddr *'
dnl   recvfrom() : /usr/include/x86_64-linux-gnu/bits/socket2.h:64:1: note: expected '__SOCKADDR_ARG {aka union <anonymous>}' but argument is of type 'struct sockaddr *'

AC_MSG_CHECKING([whether ln -sr works])
dnl We need to relative-symlink some files. Or hardlink. Or copy...
LN_S_R="cp -pR"
if test "$as_ln_s" = "ln -s" ; then
    LN_S_R="ln"
    DIR1="$(mktemp -d "dir1.XXXXXXX")" && \
    DIR2="$(mktemp -d "dir2.XXXXXXX")" && \
    touch "${DIR1}/a" && \
    $as_ln_s -r "${DIR1}/a" "${DIR2}/b" && \
    ls -la "${DIR2}/b" | grep '\.\./' > /dev/null && \
    LN_S_R="$as_ln_s -r"
    rm -rf "${DIR1}" "${DIR2}"
fi
AC_SUBST([LN_S_R], [${LN_S_R}])
if test "$LN_S_R" = "ln -s -r" ; then
  AC_MSG_RESULT([yes])
else
  AC_MSG_RESULT([no, using $LN_S_R])
fi

dnl the following may add stuff to LIBOBJS (is this still needed?)
AC_CHECK_FUNCS(vsnprintf snprintf, [], [
	AC_LIBOBJ(snprintf)
	AC_TYPE_LONG_DOUBLE
	AC_TYPE_LONG_LONG_INT
])

AC_REPLACE_FUNCS(setenv strerror atexit)

case ${target_os} in
   solaris2* )
      dnl On Solaris, this allows errno to use thread local storage
      CFLAGS="${CFLAGS} -D_REENTRANT"
      ;;
   aix* )
      dnl On AIX, this allows errno to use thread local storage
      CFLAGS="${CFLAGS} -D_REENTRANT"
      ;;
   hpux11* )
      dnl It seems like the thread safe string functions will not be included
      dnl on 64 bit HP-UX unless we define _REENTRANT
      CFLAGS="${CFLAGS} -D_REENTRANT"
      ;;
esac

dnl optind handling:
dnl need to check if unistd.h is enough, else try getopt.h, else need decls
AC_CHECK_DECLS(optind, [], [
	AC_CHECK_HEADERS(getopt.h, [
		AC_DEFINE(NEED_GETOPT_H, 1, [Define if getopt.h is needed])
	], [
		AC_DEFINE(NEED_GETOPT_DECLS, 1, [Define to use explicit getopt declarations])
	], [AC_INCLUDES_DEFAULT])
], [AC_INCLUDES_DEFAULT])

dnl do a 2nd check to ensure inclusion of getopt.h, in case optind is known
AC_CHECK_HEADERS(getopt.h, [
	AC_DEFINE(NEED_GETOPT_H, 1, [Define if getopt.h is needed])
], [
	AC_DEFINE(NEED_GETOPT_DECLS, 1, [Define to use explicit getopt declarations])
], [AC_INCLUDES_DEFAULT])

dnl also check for getopt_long
AC_CHECK_FUNCS(getopt_long)

dnl FreeBSD serial locking compatibility - look for uu_lock in libutil.h
AC_CHECK_DECLS(uu_lock, [
	AC_DEFINE(HAVE_UU_LOCK, 1, [Use uu_lock for locking (FreeBSD)])
	SERLIBS="-lutil"
	dnl put in some better defaults for FreeBSD
	RUN_AS_USER="uucp"
], [
	SERLIBS=""
], [
#include <sys/types.h>
#include <libutil.h>
])

AC_CHECK_DECLS(__func__, [], [
	AC_CHECK_DECLS(__FUNCTION__, [
		AC_DEFINE(__func__, __FUNCTION__, [Replace missing __func__ declaration])
	], [
		AC_DEFINE(__func__, __LINE__, [Replace missing  __func__ declaration])
	], [AC_INCLUDES_DEFAULT])
], [AC_INCLUDES_DEFAULT])

dnl Solaris compatibility - check for -lnsl and -lsocket
AC_SEARCH_LIBS(gethostbyname, nsl)
AC_SEARCH_LIBS(connect, socket)

dnl All current systems provide time.h; it need not be checked for.
dnl Not all systems provide sys/time.h, but those that do, all allow
dnl you to include it and time.h simultaneously.
dnl NUT codebase provides the include/timehead.h to wrap these nuances.
AC_CHECK_HEADERS_ONCE([sys/time.h time.h sys/types.h sys/socket.h netdb.h])
AS_IF([test "$ac_cv_header_sys_time_h" = yes],
    [AC_DEFINE([TIME_WITH_SYS_TIME],[1],[Define to 1 if you can safely include both <sys/time.h>
	     and <time.h>.  This macro is deemed obsolete by autotools.])
    ], [])

AC_CHECK_HEADERS(sys/modem.h stdarg.h varargs.h, [], [], [AC_INCLUDES_DEFAULT])


dnl pthread related checks
dnl Note: pthread_tryjoin_np() should be available since glibc 2.3.3, according
dnl to https://man7.org/linux/man-pages/man3/pthread_tryjoin_np.3.html
AC_SEARCH_LIBS([pthread_create], [pthread],
       [AC_DEFINE(HAVE_PTHREAD, 1, [Define to enable pthread support code])
        AC_SEARCH_LIBS([pthread_tryjoin_np], [pthread],
               [AC_DEFINE(HAVE_PTHREAD_TRYJOIN, 1, [Define to enable pthread_tryjoin support code])],
               [])
       ],
       [])

dnl ----------------------------------------------------------------------
dnl Check for types and define possible replacements
NUT_TYPE_SOCKLEN_T
NUT_FUNC_GETNAMEINFO_ARGTYPES

dnl ----------------------------------------------------------------------
dnl Check for python binary program names per language version
dnl to embed into scripts and Make rules
NUT_CHECK_PYTHON
NUT_CHECK_PYTHON2
NUT_CHECK_PYTHON3

dnl ----------------------------------------------------------------------
dnl check for --with-drivers=all (or --with-drivers=name[,name...]) flag

dnl Autoconf versions before 2.62 do not allow consecutive quadrigraphs
dnl (square brackets), so the help string depends on the version used
AC_MSG_CHECKING(which drivers to build)
AC_ARG_WITH(drivers,
	AS_HELP_STRING([m4_version_prereq(2.62,
		[@<:@--with-drivers=driver@<:@,driver@:>@@:>@],
		[[[[--with-drivers=driver@<:@,driver@:>@]]]])],
	[Only build specific drivers (all)]),
[
	case "${withval}" in
	yes|no|'')
		AC_MSG_ERROR(invalid option --with(out)-drivers - see docs/configure.txt)
		;;
	all)
		dnl Explicit request to build all drivers (unless specified), or fail
		DRIVER_BUILD_LIST="all"
		if test -z "${with_serial}"; then with_serial="yes"; fi
		if test -z "${with_usb}"; then with_usb="yes"; fi
		if test -z "${with_snmp}"; then with_snmp="yes"; fi
		if test -z "${with_neon}"; then with_neon="yes"; fi
		if test -z "${with_powerman}"; then with_powerman="yes"; fi
		if test -z "${with_modbus}"; then with_modbus="yes"; fi
		if test -z "${with_ipmi}"; then with_ipmi="yes"; fi

		dnl Platform-dependent snowflakes that are required or auto:
		if test -z "${with_linux_i2c}"; then
			case ${target_os} in
				linux*) with_linux_i2c="yes";;
				*) with_linux_i2c="auto";;
			esac
		fi
		if test -z "${with_macosx_ups}"; then
			if test -d /System/Library/Frameworks/IOKit.framework/ ; then
				with_macosx_ups="yes"
			else
				with_macosx_ups="auto"
			fi
		fi
		AC_MSG_RESULT(${DRIVER_BUILD_LIST})
		;;
	auto)
		dnl Explicit request to build all drivers that we can
		DRIVER_BUILD_LIST="all"
		if test -z "${with_serial}"; then with_serial="${withval}"; fi
		if test -z "${with_usb}"; then with_usb="${withval}"; fi
		if test -z "${with_snmp}"; then with_snmp="${withval}"; fi
		if test -z "${with_neon}"; then with_neon="${withval}"; fi
		if test -z "${with_powerman}"; then with_powerman="${withval}"; fi
		if test -z "${with_modbus}"; then with_modbus="${withval}"; fi
		if test -z "${with_ipmi}"; then with_ipmi="${withval}"; fi
		if test -z "${with_linux_i2c}"; then with_linux_i2c="${withval}"; fi
		if test -z "${with_macosx_ups}"; then with_macosx_ups="${withval}"; fi
		AC_MSG_RESULT(${DRIVER_BUILD_LIST})
		;;
	*)
		DRIVER_BUILD_LIST="`echo ${withval} | sed 's/,/ /g'`"
		AC_MSG_RESULT(${DRIVER_BUILD_LIST})

		AS_IF([test -n "$DRIVER_BUILD_LIST"],
			[dnl DRVLIST is occasionally synced with drivers/Makefile.am
			 dnl NOTE: Currently "USB_DRIVERLIST" is not used standalone:
			DRVLIST_NAMES="
				SERIAL_DRIVERLIST USB_LIBUSB_DRIVERLIST SERIAL_USB_DRIVERLIST
				SNMP_DRIVERLIST NEONXML_DRIVERLIST
				MACOSX_DRIVERLIST MODBUS_DRIVERLIST LINUX_I2C_DRIVERLIST
				POWERMAN_DRIVERLIST IPMI_DRIVERLIST"

			get_drvlist() (
				dnl Note escaped brackets - "against" m4 parser
				m4_version_prereq(2.62,
					[LB="@<:@"; RB="@:>@"],
					[LB="[["; RB="]]"]
				)
				SPACE="`printf "$LB"' \t'"$RB"`"
				SPACES="${SPACE}*"
				sed -e "s/${SPACES}""$LB"'+'"$RB"'*='"${SPACES}/=/" \
				    -e "s/^${SPACES}//" < drivers/Makefile.am \
				| {
					C=false; V=false
					while read LINE ; do
						case "$LINE" in
							*'\') C=true; if $V ; then echo "$LINE" ; fi ;;
							*) C=false; V=false ;;
						esac
						case "$LINE" in
							"$1"=*)
								echo "$LINE" | sed -e 's,^'"$LB"'^='"$RB"'*=,,' -e 's,\$,,'
								V=$C
								;;
						esac
					done
				} | tr '\n' ' ' | sed -e "s,${SPACE}${SPACES}, ," -e "s,${SPACES}\$,,"
			)

			for DRVLIST_NAME in $DRVLIST_NAMES; do
				OUT="`get_drvlist "$DRVLIST_NAME"`" \
				&& test -n "$OUT" || OUT=""
				eval $DRVLIST_NAME="\$OUT"
				AC_MSG_NOTICE([Will check custom driver selection against $DRVLIST_NAME="$OUT"])
			done

			dnl Note: do not quote the expansion below to keep it multi-token:
			for DRV in $DRIVER_BUILD_LIST ; do

				DRV_HITS=""
				dnl #DEVEL-DEBUG# AC_MSG_NOTICE([= Checking DRV="$DRV"])
				for DRVLIST_NAME in $DRVLIST_NAMES; do
					dnl #DEVEL-DEBUG# AC_MSG_NOTICE([== Checking DRVLIST_NAME="$DRVLIST_NAME"])
					eval DRVLIST="\${$DRVLIST_NAME}"
					dnl #DEVEL-DEBUG# AC_MSG_NOTICE([== Contents DRVLIST="$DRVLIST"])

					for DN in $DRVLIST ; do
						dnl #DEVEL-DEBUG# AC_MSG_NOTICE([=== Checking DN="$DN"])
						AS_IF([test x"$DN" = x"$DRV"], [
							DRV_HITS="$DRV_HITS $DRVLIST_NAME"
							AS_CASE(["$DRVLIST_NAME"],

								[SERIAL_DRIVERLIST], [
									AS_IF([test -z "${with_serial}"],
										[AC_MSG_NOTICE([Requiring --with-serial=yes for driver "$DRV"])
										with_serial=yes]
									)],
								[USB_LIBUSB_DRIVERLIST], [
									AS_IF([test -z "${with_usb}"],
										[AC_MSG_NOTICE([Requiring --with-usb=yes for driver "$DRV"])
										with_usb=yes]
									)],
								[SERIAL_USB_DRIVERLIST], [
									dnl e.g. nutdrv_qx that can do both
									AS_IF([test -z "${with_usb}"],
										[AC_MSG_NOTICE([Requiring --with-usb=yes for driver "$DRV"])
										with_usb=yes]
									)
									AS_IF([test -z "${with_serial}"],
										[AC_MSG_NOTICE([Requiring --with-serial=yes for driver "$DRV"])
										with_serial=yes]
									)],
								[SNMP_DRIVERLIST], [
									AS_IF([test -z "${with_snmp}"],
										[AC_MSG_NOTICE([Requiring --with-snmp=yes for driver "$DRV"])
										with_snmp=yes]
									)],
								[NEONXML_DRIVERLIST], [
									AS_IF([test -z "${with_neon}"],
										[AC_MSG_NOTICE([Requiring --with-neon=yes for driver "$DRV"])
										with_neon=yes]
									)],
								[MACOSX_DRIVERLIST], [
									dnl NOTE: This one is a bit special,
									dnl just one certain driver so far
									AS_IF([test -z "${with_macosx_ups}"],
										[AC_MSG_NOTICE([Requiring --with-macosx-ups=yes for driver "$DRV"])
										with_macosx_ups=yes]
									)],
								[MODBUS_DRIVERLIST], [
									AS_IF([test -z "${with_modbus}"],
										[AC_MSG_NOTICE([Requiring --with-modbus=yes for driver "$DRV"])
										with_modbus=yes]
									)],
								[LINUX_I2C_DRIVERLIST], [
									AS_IF([test -z "${with_linux_i2c}"],
										[AC_MSG_NOTICE([Requiring --with-linux-i2c=yes for driver "$DRV"])
										with_linux_i2c=yes]
									)],
								[POWERMAN_DRIVERLIST], [
									AS_IF([test -z "${with_powerman}"],
										[AC_MSG_NOTICE([Requiring --with-powerman=yes for driver "$DRV"])
										with_powerman=yes]
									)],
								[IPMI_DRIVERLIST], [
									AS_IF([test -z "${with_ipmi}"],
										[AC_MSG_NOTICE([Requiring --with-ipmi=yes for driver "$DRV"])
										with_ipmi=yes]
									)],

								[AC_MSG_WARN([Unhandled DRVLIST_NAME=$DRVLIST_NAME])]
							)
							break
							dnl Break once, maybe a driver hits several categories
						])
					done
				done
				AS_IF([test -z "${DRV_HITS}"],
					[AC_MSG_ERROR([Requested driver '$DRV' is not defined in drivers/Makefile.am (or configure.ac has a bug/lag detecting driver lists)])])

			done
			])

		;;
	esac
], [
	dnl Implicit request to build whatever is enabled;
	dnl do not force --with-all here:
	DRIVER_BUILD_LIST="all"
	AC_MSG_RESULT(all available)
])
AM_CONDITIONAL(SOME_DRIVERS, test "${DRIVER_BUILD_LIST}" != "all")

if test "${DRIVER_BUILD_LIST}" != "all"; then
	NUT_REPORT([only build specific drivers], [${DRIVER_BUILD_LIST}])
fi

dnl ----------------------------------------------------------------------
dnl check for --with-all (or --without-all, or --with-all=auto) flag

AC_MSG_CHECKING(for --with-all)
AC_ARG_WITH(all,
	AS_HELP_STRING([--with-all], [enable serial, usb, snmp, neon, ipmi, powerman, modbus, cgi, dev, avahi, linux_i2c]),
[
	if test -n "${withval}"; then
		dnl Note: we allow "no" as a positive value, because
		dnl this is what the user expects from --without-all
		dnl Note: these settings do not touch generation of
		dnl "--with-docs=...", that is handled separately
		if test -z "${with_serial}"; then with_serial="${withval}"; fi
		if test -z "${with_usb}"; then with_usb="${withval}"; fi
		if test -z "${with_snmp}"; then with_snmp="${withval}"; fi
		if test -z "${with_neon}"; then with_neon="${withval}"; fi
		if test -z "${with_powerman}"; then with_powerman="${withval}"; fi
		if test -z "${with_modbus}"; then with_modbus="${withval}"; fi
		if test -z "${with_ipmi}"; then with_ipmi="${withval}"; fi

		dnl Platform-dependent snowflakes that are required or auto:
		if test -z "${with_linux_i2c}"; then
			with_linux_i2c="${withval}"
			case ${target_os} in
				linux*) ;;
				*) test x"${withval}" = xno || with_linux_i2c="auto" ;;
			esac
		fi
		if test -z "${with_macosx_ups}"; then
			with_macosx_ups="${withval}"
			if ! test -d /System/Library/Frameworks/IOKit.framework/ ; then
				test x"${withval}" = xno || with_macosx_ups="auto"
			fi
		fi

		dnl These are not driver families, but other features:
		if test -z "${with_cgi}"; then with_cgi="${withval}"; fi
		if test -z "${with_dev}"; then with_dev="${withval}"; fi
		if test -z "${with_avahi}"; then with_avahi="${withval}"; fi

		AC_MSG_RESULT("${withval}")
	else
		AC_MSG_RESULT(not given)
	fi
], [
	AC_MSG_RESULT(not given)
])

dnl ----------------------------------------------------------------------
dnl declare a number of --with-FEATURE options. Do this early, so that
dnl they are listed near the top by "./configure --help"; however,
dnl note that options with further investigation methods are listed
dnl a bit below to be grouped with their additional with/enable help.

NUT_ARG_WITH([dev], [build and install the development files], [no])

dnl The NUT legacy option was --with-doc; however to simplify configuration
dnl in some common packaging frameworks, we also allow --with-docs as
dnl a second-class citizen (if both are set, the old option name wins).
dnl Also note that the legacy default was "man=yes" due to requirements
dnl of the "make distcheck", but it was reduced to "man=auto" so that
dnl the usual builds can pass by default on systems without asciidoc.
NUT_ARG_WITH([docs], [build and install documentation (alias to --with-doc)], [man=auto])
NUT_ARG_WITH([doc], [build and install documentation (see docs/configure.txt for many variants of the option)], [${nut_with_docs}])

dnl NOTE: Until X-Mas 2021, the default was "legacy" (now "medium")
NUT_ARG_ENABLE([warnings],
    [enable warning presets that were picked as useful in maintainership and CI practice (variants include gcc-minimal, gcc-medium, gcc-hard, clang-minimal, clang-medium, clang-hard, all; auto-choosers: hard, medium, minimal, yes=auto='gcc or clang or all at hardcoded default difficulty')],
    [auto])
NUT_ARG_ENABLE([Werror],
    [fail the build if compiler emits any warnings (treat them as errors)],
    [no])
dnl To help find warning/error details in a wall of text, see --enable-Wcolor handled above

dnl ----------------------------------------------------------------------
dnl Check for presence and compiler flags of various libraries

NUT_ARG_WITH([serial], [build and install serial drivers], [yes])

dnl These checks are performed unconditionally, even if the corresponding
dnl --with-* options are not given. This is because we cannot predict
dnl what will be in the --with-drivers argument.

NUT_ARG_WITH([usb], [build and install USB drivers, optionally require build with specified version of libusb library and API: (auto|libusb-0.1|libusb-1.0)], [auto])
nut_usb_lib=""
NUT_CHECK_LIBUSB

NUT_ARG_WITH([snmp], [build and install SNMP drivers], [auto])
NUT_CHECK_LIBNETSNMP

NUT_ARG_WITH([neon], [build and install neon based XML/HTTP driver], [auto])
NUT_CHECK_LIBNEON

NUT_ARG_WITH([powerman], [build and install Powerman PDU client driver], [auto])
NUT_CHECK_LIBPOWERMAN

NUT_ARG_WITH([modbus], [build and install modbus drivers], [auto])
NUT_CHECK_LIBMODBUS

NUT_ARG_WITH([avahi], [build and install Avahi support], [auto])
NUT_CHECK_LIBAVAHI

dnl ----------------------------------------------------------------------
dnl checks related to --with-serial

dnl ${nut_with_serial}: any value except "yes" or "no" is treated as "auto".
dnl Below we try to detect if we can build serial drivers, and if we must?
AS_IF([test "${nut_with_serial}" != "no"],
    [AS_IF([test "${nut_with_serial}" != "yes"],[nut_with_serial="auto"])

    CFLAGS_SAVED_SERIAL="${CFLAGS}"
    AS_IF([test "${GCC}" = yes],
        [CFLAGS_SAVED_WERROR="${CFLAGS} -Wall -Werror"
         CFLAGS_SAVED_WNOERROR="${CFLAGS} -Wno-error"
        ],
        [CFLAGS_SAVED_WERROR="${CFLAGS}"
         CFLAGS_SAVED_WNOERROR="${CFLAGS}"
        ])

    dnl At least recent *BSD distros have deprecated sys/termios.h and spew
    dnl warnings that termios.h should be used instead. This is redundantly
    dnl fatal for pedantic builds where we aim to have no warnings in code.
    dnl So there AC_CHECK_HEADERS does find the header, but we don't really
    dnl want to use it unless we have no choice: if there is a warning while
    dnl trying sys/ version, try the plain header path (without fatal warnings),
    dnl and only if that is missing - retry with the sys/ version again (and
    dnl no warnings still).

    CFLAGS="${CFLAGS_SAVED_WERROR}"
    AC_CHECK_HEADERS(sys/termios.h, [], [
        CFLAGS="${CFLAGS_SAVED_WNOERROR}"
        AC_CHECK_HEADERS(termios.h, [], [
            AC_CHECK_HEADERS(sys/termios.h, [], [], [AC_INCLUDES_DEFAULT])
            ], [AC_INCLUDES_DEFAULT])
        ], [AC_INCLUDES_DEFAULT])

    dnl CFLAGS at this point suffice for surviving a compilation with termios.h

    dnl Don't mind the stupid code below, it just probes the tokens and
    dnl sails around compiler warnings
    AC_MSG_CHECKING([for struct termios and speed_t])
    AC_LANG_PUSH([C])
    AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#if defined(HAVE_SYS_TERMIOS_H)
#  include <sys/termios.h>      /* for speed_t */
#else
# if defined(HAVE_TERMIOS_H)
#  include <termios.h>
# endif /* HAVE_TERMIOS_H */
#endif /* HAVE_SYS_TERMIOS_H */
void getspeed(speed_t* b) { *b = B19200; }
],
[struct termios tio;
if (!tcgetattr(0, &tio)) { return 1; }
speed_t baudrate;
getspeed(&baudrate);
]
        )],
        [AC_MSG_RESULT([ok])
         nut_have_serial_types=yes
        ],
        [AC_MSG_RESULT([no, struct termios and/or speed_t not found in discovered headers])
         nut_have_serial_types=no
        ]
     )
     AC_LANG_POP([C])

     dnl Restore common set-or-discovered CFLAGS
     CFLAGS="${CFLAGS_SAVED_SERIAL}"

     AC_MSG_CHECKING([whether we can build serial drivers])
     AS_IF([test "${nut_have_serial_types}" = yes],
        [AS_IF([test "${nut_with_serial}" = "auto"],[nut_with_serial="yes"])],
        [AS_IF([test "${nut_with_serial}" = "auto"],[nut_with_serial="no"])
         AS_IF([test "${nut_with_serial}" = "yes"],[AC_MSG_ERROR([no, and were required to])])
        ])
     AS_IF([test "${nut_with_serial}" = "yes"],
        [AC_MSG_RESULT([yes])],
        [AC_MSG_RESULT([no])])
])

NUT_REPORT_FEATURE([build serial drivers], [${nut_with_serial}], [],
					[WITH_SERIAL], [Define to enable serial support])

dnl ----------------------------------------------------------------------
dnl checks related to --with-usb are in its m4 file and NUT_CHECK_LIBUSB() called above

dnl Note: there is no libusb-config script (and variable) for libusb-1.0
AM_CONDITIONAL(WITH_LIBUSB_1_0, test "${nut_usb_lib}" = "(libusb-1.0)")
AM_CONDITIONAL(WITH_LIBUSB_0_1, test "${nut_usb_lib}" = "(libusb-0.1)" -o "${nut_usb_lib}" = "(libusb-0.1-config)")

NUT_REPORT_FEATURE([build USB drivers], [${nut_with_usb}], [${nut_usb_lib}],
					[WITH_USB], [Define to enable USB support])

dnl ----------------------------------------------------------------------
dnl checks related to --with-neon

dnl ${nut_with_neon}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_neon}" = "yes" -a "${nut_have_neon}" != "yes"; then
   AC_MSG_ERROR([neon libraries not found, required for neon based XML/HTTP driver])
fi

if test "${nut_with_neon}" != "no"; then
   nut_with_neon="${nut_have_neon}"
fi

NUT_REPORT_FEATURE([build neon based XML driver], [${nut_with_neon}], [],
					[WITH_NEON], [Define to enable Neon HTTP support])
AM_CONDITIONAL([HAVE_NEON], [test "${nut_have_neon}" = "yes"])

dnl ----------------------------------------------------------------------
dnl checks related to --with-avahi

dnl ${nut_with_avahi}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_avahi}" = "yes" -a "${nut_have_avahi}" != "yes"; then
   AC_MSG_ERROR([avahi libraries not found])
fi

if test "${nut_with_avahi}" != "no"; then
   nut_with_avahi="${nut_have_avahi}"
fi

NUT_REPORT_FEATURE([enable Avahi support], [${nut_with_avahi}], [],
					[WITH_AVAHI], [Define to enable Avahi support])

dnl ----------------------------------------------------------------------

dnl checks related to --with-powerman

dnl ${nut_with_powerman}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_powerman}" = "yes" -a "${nut_have_libpowerman}" != "yes"; then
   AC_MSG_ERROR([Powerman client libraries not found, required for Powerman PDU client driver])
fi

if test "${nut_with_powerman}" != "no"; then
   nut_with_powerman="${nut_have_libpowerman}"
fi

NUT_REPORT_FEATURE([build Powerman PDU client driver], [${nut_with_powerman}], [],
					[WITH_LIBPOWERMAN], [Define to enable Powerman PDU support])

dnl ----------------------------------------------------------------------
dnl checks related to --with-modbus

dnl ${nut_with_modbus}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_modbus}" = "yes" -a "${nut_have_libmodbus}" != "yes"; then
   AC_MSG_ERROR([modbus library not found, required for Modbus driver])
fi

if test "${nut_with_modbus}" != "no"; then
   nut_with_modbus="${nut_have_libmodbus}"
fi

NUT_REPORT_FEATURE([build Modbus driver], [${nut_with_modbus}], [],
                                       [WITH_MODBUS], [Define to enable Modbus support])
dnl ----------------------------------------------------------------------
dnl Check for with-ipmi, and --with-freeipmi (or --with-openipmi)
dnl Only one can be enabled at a time, with a preference for FreeIPMI
dnl if both are available (since it is the only one supported ATM!!)

nut_ipmi_lib=""

NUT_ARG_WITH([ipmi], [build and install IPMI PSU driver], [auto])
NUT_ARG_WITH([freeipmi], [enable IPMI support using FreeIPMI], [auto])
dnl NUT_ARG_WITH([openipmi], [enable IPMI support using OpenIPMI], [auto])

dnl ${nut_with_ipmi}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_ipmi}" != "no"; then
   dnl check if FreeIPMI (and maybe later OpenIPMI) was explicitly requested
   if test "${nut_with_freeipmi}" = "yes"; then
      NUT_CHECK_LIBFREEIPMI
      if test "${nut_have_freeipmi}" != "yes"; then
         AC_MSG_ERROR([FreeIPMI not found, required for IPMI support])
      fi
      dnl Implies --with-ipmi
      nut_with_ipmi="yes"
   dnl elif test "${nut_with_openipmi}" = "yes"; then
      dnl AC_MSG_ERROR([OpenIPMI is not yet supported])
      dnl NUT_CHECK_LIBOPENIPMI
      dnl if test "${nut_have_openipmi}" != "yes"; then
      dnl    AC_MSG_ERROR([OpenIPMI not found, required for IPMI support])
      dnl fi
      dnl    Implies --with-ipmi
      dnl    nut_with_ipmi="yes"
      dnl    AC_DEFINE(WITH_OPENIPMI, 1, [Define to enable IPMI support using OpenIPMI])
   else
      dnl Prefer FreeIPMI over OpenIPMI otherwise
      NUT_CHECK_LIBFREEIPMI
      if test "${nut_have_freeipmi}" != "yes"; then
         if test "${nut_with_ipmi}" = "yes"; then
            AC_MSG_ERROR([FreeIPMI not found, required for IPMI support])
         fi
         nut_with_ipmi="no"
         dnl NUT_CHECK_OPENIPMI
         dnl if test "${nut_have_openipmi}" != "yes"; then
         dnl    if test "${nut_with_ipmi}" = "yes"; then
         dnl       AC_MSG_ERROR([Neither GNU FreeIPMI nor OpenIPMI was found (required for IPMI support)])
         dnl    fi
         dnl    nut_with_ipmi="no"
         dnl else
         dnl    Implies --with-ipmi
         dnl    nut_with_ipmi="yes"
         dnl    nut_with_openipmi="yes"
         dnl fi
      else
         dnl Implies --with-ipmi
         nut_with_ipmi="yes"
         nut_with_freeipmi="yes"
         AC_DEFINE(WITH_FREEIPMI, 1, [Define to enable IPMI support using FreeIPMI])
      fi
   fi
fi


NUT_REPORT_FEATURE([build IPMI driver], [${nut_with_ipmi}], [${nut_ipmi_lib}],
					[WITH_IPMI], [Define to enable IPMI support])

dnl Note: we still have to manually enable complementary AC_DEFINEs (see above)
dnl and AM_CONDITIONALs (see below)...
AM_CONDITIONAL(WITH_FREEIPMI, test "${nut_with_freeipmi}" = "yes")
dnl AM_CONDITIONAL(WITH_OPENIPMI, test "${nut_with_openipmi}" = "yes")


dnl ----------------------------------------------------------------------
dnl The Mac OS X meta-driver looks at IOKit Power Sources keys managed by
dnl the internal USB UPS driver.
dnl
dnl FIXME: be slightly more clever here:

NUT_ARG_WITH([macosx_ups], [build and install Mac OS X Power Sources meta-driver], [auto])
if test "${nut_with_macosx_ups}" != no; then
   if test -d /System/Library/Frameworks/IOKit.framework/ ; then
      nut_with_macosx_ups="yes"
   else
      if test "${nut_with_macosx_ups}" = yes; then
          AC_MSG_ERROR([macosx-ups was required but can not be fulfilled for this build: not MacOS])
      fi
      nut_with_macosx_ups="no"
   fi
fi

NUT_REPORT_FEATURE([build Mac OS X meta-driver],
			[${nut_with_macosx_ups}], [${nut_macosx_ups_lib}],
			[WITH_MACOSX], [Define to enable Mac OS X meta-driver])

dnl ----------------------------------------------------------------------
dnl checks related to --with_linux_i2c
dnl Check for i2c header on Linux, used for ASEM UPS driver
NUT_ARG_WITH([linux_i2c], [build and install i2c drivers], [auto])
if test "${nut_with_linux_i2c}" != no; then
    case ${target_os} in
        linux* )
            AC_CHECK_HEADER(
                [linux/i2c-dev.h],
                [AC_DEFINE([HAVE_LINUX_I2C_DEV_H], [1],
                    [Define to 1 if you have <linux/i2c-dev.h>.])]
            )
            AC_CHECK_HEADER(
                [i2c/smbus.h],
                [AC_DEFINE([HAVE_LINUX_SMBUS_H], [1],
                    [Define to 1 if you have <i2c/smbus.h>.])]
            )
            AC_CHECK_DECLS(
                [i2c_smbus_access, i2c_smbus_read_byte_data, i2c_smbus_write_byte_data, i2c_smbus_read_word_data, i2c_smbus_write_word_data, i2c_smbus_read_block_data],
                [], dnl # nut_with_linux_i2c="yes"
                [AS_IF([test "${nut_with_linux_i2c}" = "yes"],
                    [AC_MSG_ERROR(i2c was required but can not be fulfilled for this build)],
                    [nut_with_linux_i2c="no"])],
                [#include <stdio.h>
                 #ifdef HAVE_LINUX_I2C_DEV_H
                 #include <linux/i2c-dev.h>
                 #endif
                 #ifdef HAVE_LINUX_SMBUS_H
                 #include <i2c/smbus.h>
                 #endif
                ]
            )
            dnl Builds for bitness/arch other than system default can be
            dnl "compromised" by lack of respective binary library, so
            dnl even if we have the right headers, ultimate link fails.
            dnl Note: here we keep the verdict from above, or make it worse.
            AC_SEARCH_LIBS([i2c_smbus_read_byte, i2c_smbus_access, i2c_smbus_read_byte_data, i2c_smbus_write_byte_datai2c_smbus_write_byte_data, i2c_smbus_read_word_data, i2c_smbus_write_word_data, i2c_smbus_read_block_data],
                [i2c],
                [nut_with_linux_i2c="yes"],
                [AS_IF([test "${nut_with_linux_i2c}" = "yes"],
                    [AC_MSG_ERROR(i2c was required but can not be fulfilled for this build)],
                    [nut_with_linux_i2c="no"])
                ])
            ;;
        * )
            if test "${nut_with_linux_i2c}" = yes; then
                AC_MSG_ERROR([i2c was required but can not be fulfilled for this build: not linux])
            fi
            nut_with_linux_i2c="no"
            ;;
    esac
fi
NUT_REPORT_FEATURE(
    [build i2c based drivers],
    [${nut_with_linux_i2c}],
    [],
    [WITH_LINUX_I2C],
    [Define to enable I2C support]
)

dnl ----------------------------------------------------------------------
dnl Check for with-ssl, and --with-nss or --with-openssl
dnl Only one can be enabled at a time, with a preference for OpenSSL
dnl if both are available

nut_ssl_lib=""

NUT_ARG_WITH([ssl], [enable SSL support (either NSS or OpenSSL)], [auto])
NUT_ARG_WITH([nss], [enable SSL support using Mozilla NSS], [auto])
NUT_ARG_WITH([openssl], [enable SSL support using OpenSSL], [auto])

dnl ${nut_with_ssl}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_ssl}" != "no"; then
   dnl check if either NSS or OpenSSL was explicitly requested
   if test "${nut_with_nss}" = "yes"; then
      NUT_CHECK_LIBNSS
      if test "${nut_have_libnss}" != "yes"; then
         AC_MSG_ERROR([Mozilla NSS not found (required for SSL support)])
      fi
   elif test "${nut_with_openssl}" = "yes"; then
      NUT_CHECK_LIBOPENSSL
      if test "${nut_have_openssl}" != "yes"; then
         AC_MSG_ERROR([OpenSSL not found (required for SSL support)])
      fi
   else
      dnl Prefer OpenSSL over NSS otherwise
      NUT_CHECK_LIBOPENSSL
      if test "${nut_have_openssl}" != "yes"; then
         NUT_CHECK_LIBNSS
         if test "${nut_have_libnss}" != "yes"; then
            dnl Only abort if SSL has been explicitly requested by the user
            if test "${nut_with_ssl}" = "yes"; then
               AC_MSG_ERROR([Neither Mozilla NSS nor OpenSSL was found, but one is needed for the requested SSL support.])
            else
               AC_MSG_WARN([Neither Mozilla NSS nor OpenSSL was found (required for SSL support)])
            fi
            nut_with_ssl="no"
         else
            nut_with_nss="${nut_have_libnss}"
         fi
      else
         nut_with_openssl="${nut_have_openssl}"
      fi
   fi
fi

AM_CONDITIONAL(WITH_NSS, test "${nut_with_nss}" = "yes")
AM_CONDITIONAL(WITH_OPENSSL, test "${nut_with_openssl}" = "yes")

NUT_REPORT_FEATURE([enable SSL support], [${nut_with_ssl}], [${nut_ssl_lib}],
					[WITH_SSL], [Define to enable SSL])

dnl ----------------------------------------------------------------------
dnl Check for --with-wrap

NUT_ARG_WITH([wrap], [enable libwrap (tcp-wrappers) support], [auto])

dnl ${nut_with_wrap}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_wrap}" != "no"; then
   dnl check for libwrap compiler flags
   NUT_CHECK_LIBWRAP
fi

if test "${nut_with_wrap}" = "yes" -a "${nut_have_libwrap}" != "yes"; then
   AC_MSG_ERROR([libwrap not found])
fi

if test "${nut_with_wrap}" != "no"; then
   nut_with_wrap="${nut_have_libwrap}"
fi

NUT_REPORT_FEATURE([enable libwrap (tcp-wrappers) support], [${nut_with_wrap}], [],
					[WITH_WRAP], [Define to enable libwrap (tcp-wrappers) support])


dnl ----------------------------------------------------------------------
dnl Check for --with-libltdl

NUT_ARG_WITH([libltdl], [enable libltdl (Libtool dlopen abstraction) support], [auto])

dnl ${nut_with_libltdl}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_libltdl}" != "no"; then
   dnl check for libltdl compiler flags
   NUT_CHECK_LIBLTDL
fi

if test "${nut_with_libltdl}" = "yes" -a "${nut_have_libltdl}" != "yes"; then
   AC_MSG_ERROR([libltdl not found])
fi

if test "${nut_with_libltdl}" != "no"; then
   nut_with_libltdl="${nut_have_libltdl}"
fi

NUT_REPORT_FEATURE([enable libltdl (Libtool dlopen abstraction) support], [${nut_with_libltdl}], [],
					[WITH_LIBLTDL], [Define to enable libltdl (Libtool dlopen abstraction) support])

dnl Explicitly report if we are building nut-scanner or not
dnl since it requires libltdl
NUT_REPORT([build nut-scanner], [${nut_with_libltdl}])

dnl ----------------------------------------------------------------------
dnl checks related to --with-cgi

NUT_ARG_WITH([cgi], [build and install the CGI programs], [no])

dnl ${nut_with_cgi}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_cgi}" != "no"; then
   dnl check for libgd compiler flags
   NUT_CHECK_LIBGD
fi

if test "${nut_with_cgi}" = "yes" -a "${nut_have_libgd}" != "yes"; then
   AC_MSG_ERROR([libgd not found, required for CGI build])
fi

if test "${nut_with_cgi}" != "no"; then
   nut_with_cgi="${nut_have_libgd}"
fi

NUT_REPORT_FEATURE([build CGI programs], [${nut_with_cgi}], [],
					[WITH_CGI], [Define to enable CGI (HTTP) support])


dnl ----------------------------------------------------------------------
dnl checks related to --enable-cppcheck

dnl Currently this is experimental; maybe change default to auto in the future
dnl At that point, see also defaults in ci_build.sh then (to avoid the workload
dnl unless desired).
NUT_ARG_ENABLE([cppcheck], [Run a cppcheck on the codebase among checks], [no])
NUT_CHECK_CPPCHECK

case "${nut_enable_cppcheck}" in
	yes) if test "${nut_have_cppcheck}" = "no" ; then
	        AC_MSG_ERROR([Requested to --enable-cppcheck but did not find a good one])
	     fi
	     WITH_CPPCHECK=yes
	     ;;
	no)  WITH_CPPCHECK=no ;;
	auto) if test "${nut_have_cppcheck}" = "yes" ; then
	        WITH_CPPCHECK=no
	    else
	        WITH_CPPCHECK=no
	    fi
	    ;;
esac

AM_CONDITIONAL(WITH_CPPCHECK, test "${WITH_CPPCHECK}" = "yes")

dnl ----------------------------------------------------------------------
dnl checks related to --enable-check-NIT

AC_MSG_CHECKING(whether to run NIT among default make check target)
nut_enable_check_NIT="no"
AC_ARG_ENABLE([check-NIT],
	AS_HELP_STRING([--enable-check-NIT], [Run check-NIT among default checks (no)]),
[
	case "${enableval}" in
	no)
		AC_MSG_RESULT(no)
		;;
	*)
		AC_MSG_RESULT(yes)
		nut_enable_check_NIT="yes"
		;;
	esac
], [
	AC_MSG_RESULT(no)
])

AM_CONDITIONAL(WITH_CHECK_NIT, test "${nut_enable_check_NIT}" = "yes")

dnl ----------------------------------------------------------------------
dnl checks related to --with-doc

dnl Always check for AsciiDoc prerequisites, since even if --with-doc
dnl is set to 'no', we may still want to build some doc targets manually
dnl (so enable the Makefile recipes for those targets if tools are available)
NUT_CHECK_ASCIIDOC

NUT_REPORT_FEATURE([build and install documentation], [${nut_with_doc}], [],
					[WITH_ASCIIDOC], [Define to enable Asciidoc support])

DOC_INSTALL_DISTED_MANS=no

case "${nut_with_doc}" in
	yes|all|all=yes)
		nut_doc_build_list="man html-single html-chunked pdf"
		;;
	auto|all=auto)
		nut_doc_build_list="man=auto html-single=auto html-chunked=auto pdf=auto"
		;;
	skip|all=skip)
		nut_doc_build_list="man=skip html-single=skip html-chunked=skip pdf=skip"
		;;
	no|all=no)
		nut_doc_build_list=""
		;;
dnl If user passed --with-doc='' they they want nothing, right?
	"")
		nut_doc_build_list=""
		AC_MSG_NOTICE([Got explicit empty list of document formats to build; nothing will be generated])
		;;
	*)
		nut_doc_build_list="`echo ${nut_with_doc} | sed 's/,/ /g'`"
		AC_MSG_NOTICE([Got explicit list of document formats to build or not: ${nut_doc_build_list}; formats not listed will be silently skipped])
		;;
esac

if test -z "${abs_srcdir}" ; then
	case "${srcdir}" in
		/*) abs_srcdir="${srcdir}";;
		"") AC_MSG_ERROR([Can not detect 'srcdir']) ;;
		*)  abs_srcdir="$(cd "${srcdir}" && pwd)" || AC_MSG_ERROR([Can not detect 'srcdir']) ;;
	esac
fi
DOCTESTDIR="$(mktemp -d configure-test.docbuild.$$.XXXXXXX)" && \
DOCTESTDIR="$(cd "$DOCTESTDIR" && pwd)"

dnl Note: Do not cover ${nut_doc_build_list} in braces or quotes here,
dnl to ensure that it is processed as several space-separated tokens
for nut_doc_build_target in $nut_doc_build_list; do
	case "${nut_doc_build_target}" in
	*=*=*)	rm -rf "${DOCTESTDIR}"
		AC_MSG_ERROR([Invalid documentation format option: ${nut_doc_build_target}]) ;;
	*=*)
		nut_doc_build_target_base="`echo "${nut_doc_build_target}" | sed 's,=.*$,,'`"
		nut_doc_build_target_flag="`echo "${nut_doc_build_target}" | sed 's,^.*=,,'`"
		;;
	*)
		nut_doc_build_target_base="${nut_doc_build_target}"
		nut_doc_build_target_flag="yes"
		;;
	esac
	case "${nut_doc_build_target_flag}" in
	yes|no|auto|skip) ;;
	"") nut_doc_build_target_flag="yes" ;;
	*)	rm -rf "${DOCTESTDIR}"
		AC_MSG_ERROR([Invalid documentation format option: ${nut_doc_build_target}]) ;;
	esac
	AC_MSG_CHECKING([desire and ability to build ${nut_doc_build_target_base} documentation])
	AC_MSG_RESULT([${nut_doc_build_target_flag}])

	case "${nut_doc_build_target}" in
	*=no|*=skip)
		DOC_SKIPBUILD_LIST="${DOC_SKIPBUILD_LIST} ${nut_doc_build_target_base}"
		;;

dnl Notes: Document options below assume either no flag value (which
dnl by default means "yes"), "yes" which is a requirement, or "auto"
dnl to detect if we can build the wanted documentation format and yet
dnl not fail if we have no tools to generate it (so add to SKIP list).

	html-single*)
		AC_MSG_CHECKING([if asciidoc version can build ${nut_doc_build_target_base} (minimum required ${ASCIIDOC_MIN_VERSION})])
		can_build_doc_html_single=no
		AX_COMPARE_VERSION([${ASCIIDOC_VERSION}], [ge], [${ASCIIDOC_MIN_VERSION}], [
			( cd "$DOCTESTDIR" && ${A2X} --attribute=xhtml11_format --format=xhtml --xsl-file="${abs_srcdir}"/docs/xhtml.xsl --destination-dir=. "${abs_srcdir}"/docs/asciidoc.txt && test -s asciidoc.html ) && can_build_doc_html_single=yes
			rm -f "$DOCTESTDIR"/asciidoc*.htm*
		], [])
		if test "${can_build_doc_html_single}" = yes ; then
			AC_MSG_RESULT(yes)
			DOC_BUILD_LIST="${DOC_BUILD_LIST} ${nut_doc_build_target_base}"
		else
			AC_MSG_RESULT(no)
			if test "${nut_doc_build_target_flag}" = "yes" ; then
				DOC_CANNOTBUILD_LIST="${DOC_CANNOTBUILD_LIST} ${nut_doc_build_target_base}"
				AC_MSG_WARN([Unable to build ${nut_doc_build_target_base} documentation which you requested])
			else
				DOC_SKIPBUILD_LIST="${DOC_SKIPBUILD_LIST} ${nut_doc_build_target_base}"
			fi
		fi
		;;

	html-chunked*)
		AC_MSG_CHECKING([if a2x version can build ${nut_doc_build_target_base} (minimum required ${ASCIIDOC_MIN_VERSION})])
		can_build_doc_html_chunked=no
		AX_COMPARE_VERSION([${A2X_VERSION}], [ge], [${ASCIIDOC_MIN_VERSION}], [
			( cd "$DOCTESTDIR" && ${A2X} --attribute=chunked_format --format=chunked --xsl-file="${abs_srcdir}"/docs/chunked.xsl --destination-dir=. "${abs_srcdir}"/docs/FAQ.txt && test -s FAQ.chunked/index.html ) && can_build_doc_html_chunked=yes
			rm -rf "${DOCTESTDIR}"/FAQ*.chunked*
		], [])
		if test "${can_build_doc_html_chunked}" = yes ; then
			AC_MSG_RESULT(yes)
			DOC_BUILD_LIST="${DOC_BUILD_LIST} ${nut_doc_build_target_base}"
		else
			AC_MSG_RESULT(no)
			if test "${nut_doc_build_target_flag}" = "yes" ; then
				DOC_CANNOTBUILD_LIST="${DOC_CANNOTBUILD_LIST} ${nut_doc_build_target_base}"
				AC_MSG_WARN([Unable to build ${nut_doc_build_target_base} documentation which you requested])
			else
				DOC_SKIPBUILD_LIST="${DOC_SKIPBUILD_LIST} ${nut_doc_build_target_base}"
			fi
		fi
		;;

	pdf*)
		AC_MSG_CHECKING([if dblatex version can build ${nut_doc_build_target_base} (minimum required ${DBLATEX_MIN_VERSION})])
		can_build_doc_pdf=no
		AX_COMPARE_VERSION([${DBLATEX_VERSION}], [ge], [${DBLATEX_MIN_VERSION}], [
			( cd "$DOCTESTDIR" && ${A2X} --format=pdf --destination-dir=. "${abs_srcdir}"/docs/asciidoc.txt && test -s asciidoc.pdf ) && can_build_doc_pdf=yes
			rm -f "${DOCTESTDIR}"/asciidoc.pdf
		], [])
		if test "${can_build_doc_pdf}" = yes ; then
			AC_MSG_RESULT(yes)
			DOC_BUILD_LIST="${DOC_BUILD_LIST} ${nut_doc_build_target_base}"
		else
			AC_MSG_RESULT(no)
			if test "${nut_doc_build_target_flag}" = "yes" ; then
				DOC_CANNOTBUILD_LIST="${DOC_CANNOTBUILD_LIST} ${nut_doc_build_target_base}"
				AC_MSG_WARN([Unable to build ${nut_doc_build_target_base} documentation which you requested])
			else
				DOC_SKIPBUILD_LIST="${DOC_SKIPBUILD_LIST} ${nut_doc_build_target_base}"
			fi
		fi
		;;

	man*)
		AC_MSG_CHECKING([if we can build ${nut_doc_build_target_base}])
		can_build_doc_man=no
		if test "${nut_have_asciidoc}" = yes ; then
			( cd "$DOCTESTDIR" && ${A2X} --format manpage --destination-dir=. --xsltproc-opts="--nonet" "${abs_srcdir}"/docs/man/snmp-ups.txt && test -s snmp-ups.8 ) && can_build_doc_man=yes
			rm -f "${DOCTESTDIR}"/snmp-ups.8
		fi
		if test "${can_build_doc_man}" = yes ; then
			AC_MSG_RESULT(yes)
			DOC_BUILD_LIST="${DOC_BUILD_LIST} ${nut_doc_build_target_base}"
		else
			AC_MSG_RESULT(no)
			if test "${nut_doc_build_target_flag}" = "yes" ; then
				DOC_CANNOTBUILD_LIST="${DOC_CANNOTBUILD_LIST} ${nut_doc_build_target_base}"
				AC_MSG_WARN([Unable to build ${nut_doc_build_target_base} documentation which you requested])
			else
				DOC_SKIPBUILD_LIST="${DOC_SKIPBUILD_LIST} ${nut_doc_build_target_base}"
				if test "${nut_doc_build_target_flag}" = "auto" ; then
dnl Test that groff files exist (building from distributed tarball, not git repo)
					if test -s "${abs_srcdir}"/docs/man/snmp-ups.8 ; then
						AC_MSG_WARN([Unable to build ${nut_doc_build_target_base} documentation, but can install pre-built distributed copies])
						DOC_INSTALL_DISTED_MANS="yes"
					else
						AC_MSG_WARN([Unable to build ${nut_doc_build_target_base} documentation, and unable to install pre-built distributed copies because they are absent])
					fi
				fi  # Other variants include "no", "skip"...
			fi
		fi
		;;

	*)	rm -rf "${DOCTESTDIR}"
		AC_MSG_ERROR([--with-doc option refers to unknown documentation format: $nut_doc_build_target]) ;;

	esac
done
rm -rf "${DOCTESTDIR}"

case "${nut_with_doc}" in
auto)
	if test -n "${DOC_BUILD_LIST}"; then
		nut_with_doc="yes"
	else
		nut_with_doc="no"
	fi
	;;
no)
	;;
*)
	if test -n "${DOC_CANNOTBUILD_LIST}"; then
		AC_MSG_ERROR([Unable to build${DOC_CANNOTBUILD_LIST} documentation (check for 'no' results above)])
	fi

	if test -n "${DOC_SKIPBUILD_LIST}"; then
		AC_MSG_NOTICE([Skipping build of${DOC_SKIPBUILD_LIST} documentation (check for 'skip' results above)])
	fi

	if test -n "${DOC_BUILD_LIST}"; then
		nut_with_doc="yes"
	else
		nut_with_doc="no"
	fi
	;;
esac

NUT_REPORT_FEATURE([build specific documentation format(s)], [${nut_with_doc}], [${DOC_BUILD_LIST}],
					[WITH_DOCS], [Define to enable overall documentation generation])

# To cater for less portable make's, precalculate the target list
# for "make check" in "docs/" here...
DOC_CHECK_LIST=""
if test "${nut_with_doc}" = yes ; then
    for V in $DOC_BUILD_LIST ; do
        DOC_CHECK_LIST="$DOC_CHECK_LIST check-$V"
    done
fi

WITH_MANS=no
SKIP_MANS=no
if echo "${DOC_BUILD_LIST}" | grep -w "man" >/dev/null || test "${DOC_INSTALL_DISTED_MANS}" = "yes" ; then
	WITH_MANS=yes
fi
if echo "${DOC_SKIPBUILD_LIST}" | grep -w "man" >/dev/null ; then
	SKIP_MANS=yes
fi
dnl Generally WITH_MANS=no is intentionally fatal for "make distcheck"
dnl But some larger distcheck suites check mans once and then focus on
dnl other aspects of the project, so they can explicitly skip docs (or
dnl just mans) instead. Note that for WITH_MANS=yes the SKIP_MANS value
dnl is effectively ignored by docs/man/Makefile.am at this time.
AM_CONDITIONAL(WITH_MANS, test "${WITH_MANS}" = "yes")
AM_CONDITIONAL(SKIP_MANS, test "${SKIP_MANS}" = "yes")
AM_CONDITIONAL(DOC_INSTALL_DISTED_MANS, test "${DOC_INSTALL_DISTED_MANS}" = "yes")

dnl ----------------------------------------------------------------------
dnl checks related to --with-dev

dnl We only init libtool there to allow AC_DISABLE_STATIC
if ( test "${GCC}" = "yes" )
then
	dnl # Avoid new compilers' warnings/errors about libtool distro flaws in this test like:
	dnl #   error: ISO C forbids conversion of function pointer to object pointer type [-Werror=pedantic]
	dnl #   {"nm_test_func", (void *) &nm_test_func},
	dnl # or ones about LTO (-flto -fno-common) as discussed and suggested
	dnl # in https://www.mail-archive.com/libtool@gnu.org/msg14037.html -
	dnl # all leading to undefined "global_symbol_pipe" in the generated
	dnl # libtool script, and resulting in errors like `... | | ...` below :
	dnl # libtool: link: /usr/bin/nm -B .libs/upsclient.o \
	dnl #   ../common/.libs/libcommonclient.a |  | /usr/bin/sed 's/.* //' \
	dnl #   | sort | uniq > .libs/libupsclient.exp
	dnl # ../libtool: syntax error: `|' unexpected

	CFLAGS_SAVED_NOPEDANTIC="$CFLAGS"
	AS_CASE(["${CFLAGS}"],[*"-pedantic"*],[CFLAGS="${CFLAGS} -Wno-pedantic"])
	AS_CASE(["${CFLAGS}"],[*"-Werror"*],[CFLAGS="${CFLAGS} -Wno-error"])
	AS_CASE(["${CFLAGS}"],[*"-flto"*],[CFLAGS="${CFLAGS} -ffat-lto-objects"])
fi

dnl See https://www.gnu.org/software/libtool/manual/html_node/LT_005fINIT.html
dnl #OBSOLETED:# LT_INIT and AC_PROG_LIBTOOL

dnl # Hack around the libtool script: as of version 58 (current in 2021),
dnl # they use code like below to detect library paths:
dnl #   if test yes = "$GCC"; then ... lt_search_path_spec=`$CC -print-search-dirs | ...
dnl # which explodes when non-default architecture is used for the build,
dnl # where e.g. "CC=gcc" and "CFLAGS=-m32" on a 64-bit capable system.
dnl # And similarly for compilation-checks to link third-party libraries.
SAVED_GCC="$GCC"
SAVED_CC="$CC"
if ( test "${GCC}" = "yes" )
then
    case "$CFLAGS$LDFLAGS" in
        *-m32*) CC="$CC -m32" ;;
        *-m64*) CC="$CC -m64" ;;
    esac
fi
LT_INIT
AC_SUBST([LIBTOOL_DEPS])
GCC="$SAVED_GCC"
CC="$SAVED_CC"

if ( test "${GCC}" = "yes" )
then
	CFLAGS="$CFLAGS_SAVED_NOPEDANTIC"
fi

dnl ${nut_with_dev}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_dev}" != "no"; then
  nut_with_dev="yes"
else
  AC_DISABLE_STATIC
fi
AM_CONDITIONAL(WITH_DEV, test "${nut_with_dev}" = "yes")
NUT_REPORT_FEATURE([build and install the development files], [${nut_with_dev}], [],
					[WITH_DEV], [Define to enable development files support])

dnl ----------------------------------------------------------------------


AC_MSG_CHECKING(state path)
AC_ARG_WITH(statepath,
	AS_HELP_STRING([--with-statepath=PATH], [path for ups state files (/var/state/ups)]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-statepath - see docs/configure.txt)
		;;
	*)
		STATEPATH="${withval}"
		;;
	esac
], [])
AC_DEFINE_UNQUOTED(STATEPATH, "${STATEPATH}", [Path for UPS driver state files])
AC_MSG_RESULT(${STATEPATH})

dnl ---------------------------------------------------------------------
dnl The 'alt pid path' is used by the drivers (via main.c) and upsd, since
dnl ideally they do not run as root and will not be able to write to the usual
dnl /var/run path.  This defaults to the STATEPATH since they should be
dnl able to write there.
dnl

AC_MSG_CHECKING(alt pid path)
AC_ARG_WITH(altpidpath,
	AS_HELP_STRING([--with-altpidpath=PATH], [path for driver/upsd .pid files (<statepath>)]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-altpidpath - see docs/configure.txt)
		;;
	*)
		ALTPIDPATH="${withval}"
		;;
	esac
], [
	ALTPIDPATH="${STATEPATH}"
])
AC_DEFINE_UNQUOTED(ALTPIDPATH, "${ALTPIDPATH}", [Path for pid files of drivers and upsd (usually STATEPATH)])
AC_MSG_RESULT(${ALTPIDPATH})

AC_MSG_CHECKING(driver path)
AC_ARG_WITH(drvpath,
	AS_HELP_STRING([--with-drvpath=PATH], [where to install UPS drivers (EPREFIX/bin)]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-drvpath - see docs/configure.txt)
		;;
	*)
		driverexecdir="${withval}"
		;;
	esac
], [])
conftemp="${driverexecdir}"
eval conftemp=\"${conftemp}\"
eval conftemp=\"${conftemp}\"
AC_DEFINE_UNQUOTED(DRVPATH, "${conftemp}", [Default path for UPS drivers])
AC_MSG_RESULT(${driverexecdir})

AC_MSG_CHECKING(cgi path)
AC_ARG_WITH(cgipath,
	AS_HELP_STRING([--with-cgipath=PATH], [where to install CGI programs (EPREFIX/cgi-bin)]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-cgipath - see docs/configure.txt)
		;;
	*)
		cgiexecdir="${withval}"
		;;
	esac
], [])
conftemp="${cgiexecdir}"
eval conftemp=\"${conftemp}\"
eval conftemp=\"${conftemp}\"
AC_DEFINE_UNQUOTED(CGIPATH, "${conftemp}", [Default path for CGI programs])
AC_MSG_RESULT(${cgiexecdir})

AC_MSG_CHECKING(html path)
AC_ARG_WITH(htmlpath,
	AS_HELP_STRING([--with-htmlpath=PATH], [where to install HTML files (PREFIX/html)]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-htmlpath - see docs/configure.txt)
		;;
	*)
		htmldir="${withval}"
		;;
	esac
], [])
conftemp="${htmldir}"
eval conftemp=\"${conftemp}\"
eval conftemp=\"${conftemp}\"
AC_DEFINE_UNQUOTED(HTMLPATH, "${conftemp}", [Default path for HTML files])
AC_MSG_RESULT(${htmldir})

AC_MSG_CHECKING(pidpath)
AC_ARG_WITH(pidpath,
	AS_HELP_STRING([--with-pidpath=PATH], [path for .pid files (/var/run)]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-pidpath - see docs/configure.txt)
		;;
	*)
		PIDPATH="${withval}"
		;;
	esac
], [])
AC_DEFINE_UNQUOTED(PIDPATH, "${PIDPATH}", [Path where the pid files should go])
AC_MSG_RESULT(${PIDPATH})

AC_MSG_CHECKING(network port number)
AC_ARG_WITH(port,
	AS_HELP_STRING([--with-port=PORT], [port for network communications (3493)]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-port - see docs/configure.txt)
		;;
	*)
		PORT="${withval}"
		;;
	esac
], [
	PORT="3493"
])
AC_DEFINE_UNQUOTED(PORT, ${PORT}, [Port for network communications])
AC_MSG_RESULT(${PORT})

AC_MSG_CHECKING(user to run as)
AC_ARG_WITH(user,
	AS_HELP_STRING([--with-user=username], [user for programs started as root (${RUN_AS_USER})]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-user - see docs/configure.txt)
		;;
	*)
		RUN_AS_USER="${withval}"
		nut_user_given=yes
		;;
	esac
], [
	nut_user_given=no
])
AC_DEFINE_UNQUOTED(RUN_AS_USER, "${RUN_AS_USER}", [User to switch to if started as root])
AC_MSG_RESULT(${RUN_AS_USER})

AC_MSG_CHECKING(group membership of user to run as)
AC_ARG_WITH(group,
	AS_HELP_STRING([--with-group=groupname], [group membership of user for programs started as root (${RUN_AS_GROUP})]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-group - see docs/configure.txt)
		;;
	*)
		RUN_AS_GROUP="${withval}"
		nut_group_given=yes
		;;
	esac
], [
	nut_group_given=no
])
AC_DEFINE_UNQUOTED(RUN_AS_GROUP, "${RUN_AS_GROUP}", [Group membership of user to switch to if started as root])
AC_MSG_RESULT(${RUN_AS_GROUP})

dnl check that --with-user is given if --with-group is given.
if test "${nut_user_given}" = "yes" -a "${nut_group_given}" = "no"; then
	AC_MSG_ERROR([If you specify --with-user, you also must specify --with-group])
elif test "${nut_user_given}" = "no" -a "${nut_group_given}" = "yes"; then
	AC_MSG_ERROR([If you specify --with-group, you also must specify --with-user])
fi

AC_MSG_CHECKING(facility for syslog)
AC_ARG_WITH(logfacility,
	AS_HELP_STRING([--with-logfacility=FACILITY], [facility for log messages (LOG_DAEMON)]),
[
	case "${withval}" in
	yes|no)
		AC_MSG_ERROR(invalid option --with(out)-logfacility - see docs/configure.txt)
		;;
	*)
		LOGFACILITY="${withval}"
		;;
	esac
], [
	LOGFACILITY="LOG_DAEMON"
])
AC_DEFINE_UNQUOTED(LOG_FACILITY, ${LOGFACILITY}, [Desired syslog facility - see syslog(3)])
AC_MSG_RESULT(${LOGFACILITY})

AC_MSG_CHECKING(which driver man pages to install)
if test "${WITH_MANS}" = "yes"; then
	if test "${DRIVER_BUILD_LIST}" = "all"; then
		DRIVER_MAN_LIST=all
		AC_MSG_RESULT(all available)
	else
		DRIVER_MAN_LIST=""
		for i in ${DRIVER_BUILD_LIST}; do
			if test -f ${srcdir}/docs/man/$i.8; then
				DRIVER_MAN_LIST="${DRIVER_MAN_LIST} $i.8"
			fi
		done
		AC_MSG_RESULT(${DRIVER_MAN_LIST})
	fi
else
	DRIVER_MAN_LIST=""
	AC_MSG_RESULT([none (manpages disabled)])
fi

AC_MSG_CHECKING(whether to strip debug symbols)
AC_ARG_ENABLE(strip,
	AS_HELP_STRING([--enable-strip], [Strip debugging symbols from binaries (no)]),
[
	case "${enableval}" in
	no)
		AC_MSG_RESULT(no)
		;;
	*)
		AC_MSG_RESULT(yes)
		CFLAGS="${CFLAGS} -s"
		;;
	esac
], [
	AC_MSG_RESULT(no)
])

AC_MSG_CHECKING(whether to install pkg-config *.pc files)
AC_ARG_WITH(pkgconfig-dir,
	AS_HELP_STRING([--with-pkgconfig-dir=PATH], [where to install pkg-config *.pc files (EPREFIX/lib/pkgconfig)]),
[
	case "${withval}" in
	yes|auto)
		;;
	no)
		pkgconfigdir=""
		;;
	*)
		pkgconfigdir="${withval}"
		;;
	esac
], [])
if test -n "${pkgconfigdir}"; then
	AC_MSG_RESULT(using ${pkgconfigdir})
else
	AC_MSG_RESULT(no)
fi
AM_CONDITIONAL(WITH_PKG_CONFIG, test -n "${pkgconfigdir}")

AC_MSG_CHECKING(whether to install Solaris SMF files)
solarissmf="auto"
AC_ARG_WITH([solaris-smf],
	AS_HELP_STRING([--with-solaris-smf=(yes|auto|no)], [Enable installation of NUT scripts and manifests for Solaris Service Management Framework (auto)]),
[
	case "${withval}" in
	auto|"")
		solarissmf="auto"
		;;
	yes|no)
		solarissmf="${withval}"
		;;
	*)
		AC_MSG_ERROR([Unexpected argument for --with-solaris-smf=${withval}])
		;;
	esac
], [])

if test x"$solarissmf" = xauto ; then
	if test -x /usr/sbin/svcadm && test -x /usr/sbin/svccfg && test -x /usr/bin/svcs ; then
		solarissmf="yes"
	else
		solarissmf="no"
	fi
fi
AC_MSG_RESULT([${solarissmf}])
AM_CONDITIONAL(WITH_SOLARIS_SMF, test x"$solarissmf" = x"yes")

AC_MSG_CHECKING(whether to make Solaris SVR4 packages)
solarispkg_svr4="auto"
AC_ARG_WITH([solaris-pkg-svr4],
	AS_HELP_STRING([--with-solaris-pkg-svr4=(yes|auto|no)], [Enable construction of Solaris SVR4 packages (auto)]),
[
	case "${withval}" in
	auto|"")
		solarispkg_svr4="auto"
		;;
	yes|no)
		solarispkg_svr4="${withval}"
		;;
	*)
		AC_MSG_ERROR([Unexpected argument for --with-solaris-pkg-svr4=${withval}])
		;;
	esac
], [])

if test x"$solarispkg_svr4" = xauto ; then
	if test -x /usr/bin/pkgtrans && test -x /usr/bin/pkgmk && test -x /usr/bin/pkgproto ; then
		solarispkg_svr4="yes"
	else
		solarispkg_svr4="no"
	fi
fi
AC_MSG_RESULT([${solarispkg_svr4}])
AM_CONDITIONAL(WITH_SOLARIS_PKG_SVR4, test x"$solarispkg_svr4" = x"yes")

AC_MSG_CHECKING(whether to make Solaris IPS packages)
solarispkg_ips="auto"
AC_ARG_WITH([solaris-pkg-ips],
	AS_HELP_STRING([--with-solaris-pkg-ips=(yes|auto|no)], [Enable construction of Solaris IPS packages (auto)]),
[
	case "${withval}" in
	auto|"")
		solarispkg_ips="auto"
		;;
	yes|no)
		solarispkg_ips="${withval}"
		;;
	*)
		AC_MSG_ERROR([Unexpected argument for --with-solaris-pkg-ips=${withval}])
		;;
	esac
], [])

if test x"$solarispkg_ips" = xauto ; then
	if test -x /usr/bin/pkg && test -x /usr/bin/pkgmogrify && test -x /usr/bin/pkgdepend ; then
		solarispkg_ips="yes"
	else
		solarispkg_ips="no"
	fi
fi
AC_MSG_RESULT([${solarispkg_ips}])
AM_CONDITIONAL(WITH_SOLARIS_PKG_IPS, test x"$solarispkg_ips" = x"yes")

dnl Note: Currently there is no reliable automatic detection -
dnl users have to ask they want systemd units installed, or
dnl risk auto-detection like seen below.
AC_MSG_CHECKING(whether to install systemd unit files)
AC_ARG_WITH([systemdsystemunitdir],
	AS_HELP_STRING([--with-systemdsystemunitdir=DIR], [Directory for systemd service files (auto)]),
	[systemdsystemunitdir="${withval}"],
	[systemdsystemunitdir="auto"])
case "${systemdsystemunitdir}" in
	yes|auto|"")
		AS_IF([test x"$have_PKG_CONFIG" = xyes],
			[systemdsystemunitdir="`$PKG_CONFIG --variable=systemdsystemunitdir systemd 2>/dev/null`" && test -n "$systemdsystemunitdir" || systemdsystemunitdir="`$PKG_CONFIG --variable=systemdsystemunitdir libsystemd 2>/dev/null`"],
			[AS_IF([test "${withval}" = yes],
				[AC_MSG_ERROR([--with-systemdsystemunitdir=${withval} was requested, but PKG_CONFIG could not be queried for the system settings])])
			 systemdsystemunitdir=""
			])
		;;
	no)
		systemdsystemunitdir=""
		;;
	*)
		systemdsystemunitdir="${withval}"
		;;
esac
if test "${systemdsystemunitdir}" = "auto" ; then systemdsystemunitdir=""; fi
if test -n "${systemdsystemunitdir}"; then
	AC_MSG_RESULT(using ${systemdsystemunitdir})
else
	AC_MSG_RESULT(no)
fi
AM_CONDITIONAL(HAVE_SYSTEMD, test "$systemdsystemunitdir" != "")
dnl This option is only provided so that make distcheck can override it,
dnl otherwise we ask pkg-config whenever --with-systemdsystemunitdir is
dnl given

AC_MSG_CHECKING(whether to install systemd shutdown files)
AC_ARG_WITH([systemdshutdowndir],
	AS_HELP_STRING([--with-systemdshutdowndir=DIR], [Directory for systemd shutdown scripts (auto)]),
	[systemdshutdowndir="${withval}"],
	[systemdshutdowndir="auto"])
dnl Note: this option is enabled only if systemdsystemunitdir is not trivial
if test -n "${systemdsystemunitdir}"; then
	case "${systemdshutdowndir}" in
	yes|auto|"")
		AS_IF([test x"$have_PKG_CONFIG" = xyes],
			[systemdshutdowndir="`$PKG_CONFIG --variable=systemdshutdowndir systemd 2>/dev/null`" && test -n "$systemdshutdowndir" || systemdshutdowndir="`$PKG_CONFIG --variable=systemdshutdowndir libsystemd 2>/dev/null`"],
			[AS_IF([test "${systemdshutdowndir}" = yes],
				[AC_MSG_ERROR([--with-systemdshutdowndir=${systemdshutdowndir} was requested, but PKG_CONFIG could not be queried for the system settings])])
			 systemdshutdowndir=""
			])
		;;
	no)
		systemdshutdowndir=""
		;;
	*)
		systemdshutdowndir="${withval}"
		;;
	esac
fi
if test "${systemdshutdowndir}" = "auto" ; then systemdshutdowndir=""; fi
if test -n "${systemdshutdowndir}"; then
	AC_MSG_RESULT(using ${systemdshutdowndir})
else
	AC_MSG_RESULT(no)
fi

dnl Note: if (systemd-)tmpfiles tech is present, it can be useful even for
dnl daemons starting not as systemd units, to pre-create /var/run/nut etc.
AC_MSG_CHECKING([whether to install systemd tmpfiles files])
AC_ARG_WITH([systemdtmpfilesdir],
	AS_HELP_STRING([--with-systemdtmpfilesdir=DIR], [Directory for systemd tmpfiles scripts (auto)]),
	[systemdtmpfilesdir="${withval}"],
	[systemdtmpfilesdir="auto"])
case "${systemdtmpfilesdir}" in
	yes|auto|"")
		AS_IF([test x"$have_PKG_CONFIG" = xyes],
			[systemdtmpfilesdir="`$PKG_CONFIG --variable=tmpfilesdir systemd 2>/dev/null`" && test -n "$systemdtmpfilesdir" || systemdtmpfilesdir="`$PKG_CONFIG --variable=tmpfilesdir libsystemd 2>/dev/null`"],
			[AS_IF([test "${systemdtmpfilesdir}" = yes],
				[AC_MSG_ERROR([--with-systemdtmpfilesdir=${systemdtmpfilesdir} was requested, but PKG_CONFIG could not be queried for the system settings])])
			 systemdtmpfilesdir=""
			])
		;;
	no)
		systemdtmpfilesdir=""
		;;
	*)
		systemdtmpfilesdir="${withval}"
		;;
esac
if test "${systemdtmpfilesdir}" = "auto" ; then systemdtmpfilesdir=""; fi
if test -n "${systemdtmpfilesdir}"; then
	AC_MSG_RESULT(using ${systemdtmpfilesdir})
else
	AC_MSG_RESULT(no)
fi

dnl
dnl Tests for CppUnit availability and usability (will be built if we can,
dnl and if valgrind is enabled for this configuration - reported below).
dnl Using CppUnit implies C++ support!
dnl Theoretically, libcppunit-dev will pull up to g++, through libstdc++...
dnl AM_PATH_CPPUNIT(1.9.6)

dnl # Tests with gcc-4.8 require this C++11 option to be provided explicitly
dnl # gcc-4.6 does not support this yet; newer gcc's should be ok by default.
dnl # Could use `AX_CXX_COMPILE_STDCXX_11([noext], [optional])` if it were
dnl # available everywhere. Or AX_CHECK_COMPILE_FLAG if it was ubiquitous:
dnl ###AX_CHECK_COMPILE_FLAG([-std=c++11],
dnl ###    [CXXFLAGS="$CXXFLAGS -std=c++11"
dnl ###     have_cxx11=yes],
dnl ###    [have_cxx11=no])

AC_MSG_CHECKING(for C++11 support in current compiler)
have_cxx11=unknown
my_CXXFLAGS="$CXXFLAGS"
AC_LANG_PUSH([C++])

CPLUSPLUS_DECL='
#include <stdio.h>
#if __cplusplus < 201103L
  #error This library needs at least a C++11 compliant compiler
#endif
'
CPLUSPLUS_MAIN='printf("%ld\n", __cplusplus);'

AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[${CPLUSPLUS_DECL}]], [[${CPLUSPLUS_MAIN}]])],
    [AC_MSG_RESULT([yes, out of the box])
     have_cxx11=yes],
    [AS_CASE(["${CXXFLAGS}"],
        [*"-std="*], [
            AC_MSG_RESULT([no, not with the standard already set in CXXFLAGS='${CXXFLAGS}'])
            have_cxx11=no,
        ],[
            CXXFLAGS="$CXXFLAGS -std=c++11"
            AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[${CPLUSPLUS_DECL}]], [[${CPLUSPLUS_MAIN}]])],
                [AC_MSG_RESULT([yes, GCC-style (as C++11)])
                 have_cxx11=yes],
                [CXXFLAGS="$CXXFLAGS -std=c++0x"
                 AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[${CPLUSPLUS_DECL}]], [[${CPLUSPLUS_MAIN}]])],
                    [AC_MSG_RESULT([yes, GCC-style (as C++0X)])
                     have_cxx11=yes],
                    [AC_MSG_RESULT([no])
                     CXXFLAGS="$my_CXXFLAGS"
                     have_cxx11=no])])])])
AM_CONDITIONAL(HAVE_CXX11, test "${have_cxx11}" = "yes")
AC_LANG_POP([C++])
unset CPLUSPLUS_MAIN
unset CPLUSPLUS_DECL

AC_MSG_CHECKING(for have_cppunit)
have_cppunit="no"
CPPUNIT_NUT_CXXFLAGS=""
AS_IF([test x"$have_PKG_CONFIG" = xyes],
    [AS_IF([test x"${have_cxx11}" = xyes],
        [ifdef([PKG_CHECK_MODULES], [PKG_CHECK_MODULES(CPPUNIT, cppunit, have_cppunit=yes, have_cppunit=no)], [have_cppunit=no])
         AS_IF([test "${have_cppunit}" != "yes"],
            [AC_MSG_WARN([libcppunit not found - those C++ tests will not be built.])
             have_cppunit=no],
            [AS_IF([test -n "$CXX"],
                [AS_IF([$CXX --version 2>&1 | grep 'Free Software Foundation' > /dev/null],
                    [CPPUNIT_NUT_CXXFLAGS="-g -O0"])])
            ])
        ])
    ], [AC_MSG_WARN([pkg-config not found, can not look properly for libcppunit - those C++ tests will not be built.])
        have_cppunit=no]
)
AC_MSG_RESULT(${have_cppunit})

dnl On some systems, CppUnit inexplicably fails with trivial assertions
dnl so it should not be enabled with those environments, corrupting the
dnl test results with misleading errors.
dnl Tracked in https://github.com/networkupstools/nut/issues/1126
dnl One such situation was e.g. "clang++ + arm64(QEMU) + -m64" while
dnl this was not seen with other compilers or bitness on same system.
AS_IF([test "${have_cppunit}" = "yes"],
    [AC_MSG_CHECKING([if current toolkit can build and run cppunit tests (e.g. no ABI issues, related segfaults, etc.)])
     dnl Code below is largely a stripped variant of our tests/example.cpp and cpputest.cpp
     CPLUSPLUS_DECL='
#include <stdexcept>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/TestFactoryRegistry.h>
#include <cppunit/ui/text/TestRunner.h>

class ExampleTest : public CppUnit::TestFixture
{
  CPPUNIT_TEST_SUITE( ExampleTest );
    CPPUNIT_TEST( testOne );
  CPPUNIT_TEST_SUITE_END();
public:
  void setUp() {};
  void tearDown() {};
  void testOne();
};
CPPUNIT_TEST_SUITE_REGISTRATION( ExampleTest );
void ExampleTest::testOne()
{
  int i = 1;
  float f = 1.0;
  int cast = static_cast<int>(f);
  CPPUNIT_ASSERT_EQUAL_MESSAGE("Casted float is not the expected int (assert_eq)", i, cast );
  CPPUNIT_ASSERT_MESSAGE("Casted float is not the expected int (assert)", (i == cast) );
}
'

     CPLUSPLUS_MAIN='
CppUnit::Test *suite = CppUnit::TestFactoryRegistry::getRegistry().makeTest();
CppUnit::TextUi::TestRunner runner;
runner.addTest( suite );
runner.setOutputter( new CppUnit::CompilerOutputter( &runner.result(), std::cerr ) );
bool res = runner.run();
return res ? 0 : 1;
'

     my_CXXFLAGS="$CXXFLAGS"
     my_LDFLAGS="$LDFLAGS"
     my_LIBS="$LIBS"
     CXXFLAGS="$myCXXFLAGS $pkg_cv_CPPUNIT_CFLAGS $pkg_cv_CPPUNIT_CXXFLAGS"
     LDFLAGS="$my_LDFLAGS $pkg_cv_CPPUNIT_LDFLAGS"
     LIBS="$my_LIBS $pkg_cv_CPPUNIT_LIBS"
     AC_LANG_PUSH([C++])
     AX_RUN_OR_LINK_IFELSE([AC_LANG_PROGRAM([[${CPLUSPLUS_DECL}]], [[${CPLUSPLUS_MAIN}]])],
        [have_cppunit=yes], [have_cppunit=no])
     CXXFLAGS="$my_CXXFLAGS"
     LDFLAGS="$my_LDFLAGS"
     LIBS="$my_LIBS"
     AC_LANG_POP([C++])
     unset CPLUSPLUS_MAIN
     unset CPLUSPLUS_DECL
     ])
AC_MSG_RESULT(${have_cppunit})

dnl # By default keep the originally detected have_cppunit value
AC_MSG_CHECKING(for impact from --enable-cppunit option - should we build cppunit tests?)
AC_ARG_ENABLE(cppunit,
	[AS_HELP_STRING([--enable-cppunit], [enable CPPUNIT tests for C++ bindings])],
	[AS_CASE(["${enableval}"],
		["yes"], [AS_IF([test x"${have_cppunit}" = xyes], [], [AC_MSG_ERROR([--with-cppunit=yes can not be satisfied])])],
		["no"], [have_cppunit=no]
	)])
AC_MSG_RESULT(${have_cppunit})

AM_CONDITIONAL(HAVE_CPPUNIT, test "${have_cppunit}" = "yes")
AC_DEFINE_UNQUOTED(CPPUNIT_NUT_CXXFLAGS, $CPPUNIT_NUT_CXXFLAGS, [Compiler flags for cppunit tests])

AC_MSG_CHECKING(whether to install Augeas configuration-management lenses)
AC_ARG_WITH(augeas-lenses-dir,
	AS_HELP_STRING([--with-augeas-lenses-dir=PATH], [where to install Augeas configuration-management lenses (/usr/share/augeas/lenses{/dist,/})]),
[
	case "${withval}" in
	yes)
		if test -z "${auglensdir}"; then
			AC_MSG_RESULT(no)
			AC_MSG_ERROR([augeas lenses directory requested but not found in default location])
		fi
		if ! test -s scripts/augeas/nutupsconf.aug.in ; then
			AC_MSG_RESULT(no)
			AC_MSG_ERROR([augeas lenses directory requested but a non-trivial scripts/augeas/nutupsconf.aug.in was not provided by autogen.sh or dist archive])
		fi
		;;
	auto)
		if ! test -s scripts/augeas/nutupsconf.aug.in ; then
			AC_MSG_WARN([augeas lenses directory skipped because a non-trivial scripts/augeas/nutupsconf.aug.in was not provided by autogen.sh or dist archive])
			auglensdir=""
		fi
		;;
	no)
		auglensdir=""
		;;
	*)
		auglensdir="${withval}"
		;;
	esac
], [])
if test -n "${auglensdir}"; then
	AC_MSG_RESULT(using ${auglensdir})
else
	AC_MSG_RESULT(no)
fi
AM_CONDITIONAL(WITH_AUGLENS, test -n "${auglensdir}")

AC_PATH_PROGS([AUGPARSE], [augparse], [none])
AM_CONDITIONAL([HAVE_AUGPARSE], [test "x${AUGPARSE}" != "xnone"])
AC_MSG_CHECKING([whether to enable Augeas configuration-management lenses tests])
if test "x${AUGPARSE}" != xnone ; then
	AC_MSG_RESULT(yes)
else
	AC_MSG_RESULT(no)
fi


AC_MSG_CHECKING(whether to install hotplug rules)
AC_ARG_WITH(hotplug-dir,
	AS_HELP_STRING([--with-hotplug-dir=PATH], [where to install hotplug rules (/etc/hotplug)]),
[
	case "${withval}" in
	yes)
		if test -z "${hotplugdir}"; then
			AC_MSG_RESULT(no)
			AC_MSG_ERROR([hotplug directory requested but not found])
		fi
		;;
	auto)
		;;
	no)
		hotplugdir=""
		;;
	*)
		hotplugdir="${withval}"
		;;
	esac
], [])
if test -n "${hotplugdir}"; then
	AC_MSG_RESULT(using ${hotplugdir})
else
	AC_MSG_RESULT(no)
fi
AM_CONDITIONAL(WITH_HOTPLUG, test -n "${hotplugdir}")

AC_MSG_CHECKING(whether to install udev rules)
AC_ARG_WITH(udev-dir,
	AS_HELP_STRING([--with-udev-dir=PATH], [where to install udev rules (/lib/udev or /etc/udev)]),
[
	case "${withval}" in
	yes)
		if test -z "${udevdir}"; then
			AC_MSG_RESULT(no)
			AC_MSG_ERROR([udev directory requested but not found])
		fi
		if test "${nut_with_usb}" = yes && ! test -s scripts/udev/nut-usbups.rules.in ; then
			AC_MSG_RESULT(no)
			AC_MSG_ERROR([udev directory and USB driver support requested but a non-trivial scripts/udev/nut-usbups.rules.in was not provided by autogen.sh or dist archive])
		fi
		;;
	auto)
		if test "${nut_with_usb}" = yes && ! test -s scripts/udev/nut-usbups.rules.in ; then
			AC_MSG_WARN([udev directory skipped because a non-trivial scripts/udev/nut-usbups.rules.in was not provided by autogen.sh or dist archive])
			udevdir=""
		fi
		;;
	no)
		udevdir=""
		;;
	*)
		udevdir="${withval}"
		;;
	esac
], [])
if test -n "${udevdir}"; then
	AC_MSG_RESULT(using ${udevdir})
else
	AC_MSG_RESULT(no)
fi
AM_CONDITIONAL(WITH_UDEV, test -n "${udevdir}")

dnl FreeBSD devd support:

AC_MSG_CHECKING(whether to install FreeBSD devd.conf file)
AC_ARG_WITH(devd-dir,
	AS_HELP_STRING([--with-devd-dir=PATH], [where to install devd.conf file (/usr/local/etc/devd or /etc/devd)]),
[
	case "${withval}" in
	yes)
		if test -z "${devddir}"; then
			AC_MSG_RESULT(no)
			AC_MSG_ERROR([devd directory requested but not found])
		fi
		if test "${nut_with_usb}" = yes && ! test -s scripts/devd/nut-usbups.rules.in -a -s scripts/devd/nut-usb.conf.in ; then
			AC_MSG_RESULT(no)
			AC_MSG_ERROR([devd directory and USB driver support requested but non-trivial scripts/devd/nut-usbups.rules.in and scripts/devd/nut-usb.conf.in were not provided by autogen.sh or dist archive])
		fi
		;;
	auto)
		if test "${nut_with_usb}" = yes && ! test -s scripts/devd/nut-usbups.rules.in -a -s scripts/devd/nut-usb.conf.in ; then
			AC_MSG_WARN([devd directory skipped because non-trivial scripts/devd/nut-usbups.rules.in and scripts/devd/nut-usb.conf.in were not provided by autogen.sh or dist archive])
			devddir=""
		fi
		;;
	no)
		devddir=""
		;;
	*)
		devddir="${withval}"
		;;
	esac
], [])
if test -n "${devddir}"; then
	AC_MSG_RESULT(using ${devddir})
else
	AC_MSG_RESULT(no)
fi
AM_CONDITIONAL(WITH_DEVD, test -n "${devddir}")

dnl

dnl AIX system
AM_CONDITIONAL([SYSTEM_AIX], [test "xAIX" = "x`uname -s 2>/dev/null`"])

dnl processor type
AC_DEFINE_UNQUOTED(CPU_TYPE, ["$target_cpu"], [Define processor type])

dnl Can use valgrind for memory-leak testing, if present
AC_PATH_PROGS([VALGRIND], [valgrind], [none])
dnl Even if the tool is installed, it may be not usable on build platform.
dnl QEMU may further complicate things, providing CPUs that formally match
dnl a supported family but crash in practice, or hopefully rejected early:
dnl valgrind: fatal error: unsupported CPU.
dnl    Supported CPUs are:
dnl    * x86 (practically any; Pentium-I or above), AMD Athlon or above)
dnl    * AMD Athlon64/Opteron
dnl    * ARM (armv7)
dnl    * MIPS (mips32 and above; mips64 and above)
dnl    * PowerPC (most; ppc405 and above)
dnl    * System z (64bit only - s390x; z990 and above)
dnl Even if the tool does basically start, on some QEMU systems it crashes
dnl later (e.g. claims Signal 11 in tear-down after a successful test), so
dnl we support an explicit --without-valgrind (aka --with-valgrind=no) too.
AS_IF([test -n "${VALGRIND}"], [
	AC_MSG_CHECKING([whether valgrind is usable on current platform])
	AS_IF([( ${VALGRIND} --help >/dev/null 2>/dev/null )],
		[AS_IF([( ${VALGRIND} /bin/sh -c true >/dev/null 2>/dev/null )],
			[AC_MSG_RESULT([yes])],
			[AC_MSG_RESULT([no])
			 VALGRIND="none"
			])],
		[AC_MSG_RESULT([no])
		 VALGRIND="none"
		])
])
AC_MSG_CHECKING(whether to use valgrind for memory-leak testing)
AC_ARG_WITH(valgrind,
	AS_HELP_STRING([--with-valgrind=PATH], [whether to use valgrind for memory-leak testing]),
[
	dnl ### echo "Caller said: '${withval}'... Discovered tool: '${VALGRIND}'... "
	case "${withval}" in
	yes)
		if test "x$VALGRIND" = "xnone"; then
			AC_MSG_RESULT(no)
			AC_MSG_ERROR([valgrind requested but not found])
		fi
		with_valgrind="yes"
		;;
	auto)
		with_valgrind="auto"
		;;
	no)
		with_valgrind="no"
		;;
	*)
		AC_PATH_PROGS([VALGRIND], ["${withval}"], [none])
		if test "x$VALGRIND" = "xnone"; then
			AC_MSG_RESULT(no)
			AC_MSG_ERROR([valgrind requested but not found])
		fi
		with_valgrind="yes"
		;;
	esac
], [])

if test "x${with_valgrind}" = xauto; then
	if test "x$VALGRIND" = "xnone"; then
		with_valgrind="no"
	else
		with_valgrind="yes"
	fi
fi

if test "x${with_valgrind}" = xyes; then
	AC_MSG_RESULT(using ${VALGRIND})
	AC_MSG_NOTICE([Do not forget to build with debug (e.g. pass '-g' in CFLAGS for GCC) for best results with valgrind tests])
else
	AC_MSG_RESULT(no)
fi
AM_CONDITIONAL([HAVE_VALGRIND], [test "x${VALGRIND}" != "xnone"])
AM_CONDITIONAL([WITH_VALGRIND], [test "x${with_valgrind}" = "xyes"])

AC_MSG_CHECKING([whether to build cppunit tests using valgrind support])
if test "x${with_valgrind}" = xyes && test "x${have_cppunit}" = xyes ; then
	AC_MSG_RESULT(yes)
else
	AC_MSG_RESULT(no)
fi

dnl expand ${sysconfdir} and write it out - note that most packages
dnl override it to be /etc/nut, /etc/ups or similar, while the
dnl autotools default would be $prefix/etc
conftemp="${sysconfdir}"
eval conftemp=\"${conftemp}\"
eval conftemp=\"${conftemp}\"
CONFPATH=${conftemp}
AC_DEFINE_UNQUOTED(CONFPATH, "${conftemp}", [Default path for configuration files])

dnl same for datadir
conftemp="${datadir}"
eval conftemp=\"${conftemp}\"
eval conftemp=\"${conftemp}\"
DATADIR=${conftemp}
NUT_DATADIR=${conftemp}
AC_DEFINE_UNQUOTED(DATADIR, "${conftemp}", [Default path for data files])

dnl same for bindir
conftemp="${bindir}"
eval conftemp=\"${conftemp}\"
eval conftemp=\"${conftemp}\"
BINDIR=${conftemp}
AC_DEFINE_UNQUOTED(BINDIR, "${conftemp}", [Default path for user executables])

dnl same for sbindir
conftemp="${sbindir}"
eval conftemp=\"${conftemp}\"
eval conftemp=\"${conftemp}\"
SBINDIR=${conftemp}
AC_DEFINE_UNQUOTED(SBINDIR, "${conftemp}", [Default path for system executables])

dnl same for libdir
conftemp="${libdir}"
eval conftemp=\"${conftemp}\"
eval conftemp=\"${conftemp}\"
LIBDIR=${conftemp}
AC_DEFINE_UNQUOTED(LIBDIR, "${conftemp}", [Default path for system libraries])

dnl same for libexecdir
conftemp="${libexecdir}"
eval conftemp=\"${conftemp}\"
eval conftemp=\"${conftemp}\"
LIBEXECDIR=${conftemp}
AC_DEFINE_UNQUOTED(LIBEXECDIR, "${conftemp}", [Default path for system exec-libraries])


dnl checks related to --with-snmp enabled on command-line

dnl ${nut_with_snmp}: any value except "yes" or "no" is treated as "auto".
if test "${nut_with_snmp}" = "yes" -a "${nut_have_libnetsnmp}" != "yes"; then
   AC_MSG_ERROR([Net-SNMP libraries not found, required for SNMP drivers])
fi

if test "${nut_with_snmp}" != "no"; then
   nut_with_snmp="${nut_have_libnetsnmp}"
fi

NUT_REPORT_FEATURE([build SNMP drivers], [${nut_with_snmp}], [],
					[WITH_SNMP], [Define to enable SNMP support])
AM_CONDITIONAL([HAVE_SNMP], [test "${nut_have_libsnmp}" = "yes"])


if test -n "${host_alias}" ; then
	AC_DEFINE_UNQUOTED(AUTOTOOLS_HOST_ALIAS, "${host_alias}", [host env spec we run on])
else
	if test -n "${host}" ; then
		AC_DEFINE_UNQUOTED(AUTOTOOLS_HOST_ALIAS, "${host}", [host env spec we run on])
	fi
fi
if test -n "${build_alias}" ; then
	AC_DEFINE_UNQUOTED(AUTOTOOLS_BUILD_ALIAS, "${build_alias}", [host env spec we built on])
else
	if test -n "${build}" ; then
	AC_DEFINE_UNQUOTED(AUTOTOOLS_BUILD_ALIAS, "${build}", [host env spec we built on])
	fi
fi
if test -n "${target_alias}" ; then
	AC_DEFINE_UNQUOTED(AUTOTOOLS_TARGET_ALIAS, "${target_alias}", [host env spec we built for])
else
	if test -n "${target}" ; then
	AC_DEFINE_UNQUOTED(AUTOTOOLS_TARGET_ALIAS, "${target}", [host env spec we built for])
	fi
fi

if test -n "${host_cpu}" -a -n "${host_os}" ; then
	AC_DEFINE_UNQUOTED(AUTOTOOLS_HOST_SHORT_ALIAS, "${host_cpu}-${host_os}", [host OS short spec we run on])
fi
if test -n "${build_cpu}" -a -n "${build_os}" ; then
	AC_DEFINE_UNQUOTED(AUTOTOOLS_BUILD_SHORT_ALIAS, "${build_cpu}-${build_os}", [host OS short spec we built on])
fi
if test -n "${target_cpu}" -a -n "${target_os}" ; then
	AC_DEFINE_UNQUOTED(AUTOTOOLS_TARGET_SHORT_ALIAS, "${target_cpu}-${target_os}", [host OS short spec we built for])
fi

dnl ----------------------------------------------------------------------

dnl Current date
now=`TZ=UTC date +%Y-%m-%d`

AC_SUBST(now)
AC_SUBST(OS_NAME)
AC_SUBST(TREE_VERSION)
AC_SUBST(NUT_NETVERSION)
AC_SUBST(LIBSSL_CFLAGS)
AC_SUBST(LIBSSL_LIBS)
AC_SUBST(LIBSSL_REQUIRES)
AC_SUBST(LIBGD_CFLAGS)
AC_SUBST(LIBGD_LDFLAGS)
AC_SUBST(LIBNETSNMP_CFLAGS)
AC_SUBST(LIBNETSNMP_LIBS)
AC_SUBST(LIBUSB_CFLAGS)
AC_SUBST(LIBUSB_LIBS)
AC_SUBST(LIBNEON_CFLAGS)
AC_SUBST(LIBNEON_LIBS)
AC_SUBST(LIBAVAHI_CFLAGS)
AC_SUBST(LIBAVAHI_LIBS)
AC_SUBST(LIBPOWERMAN_CFLAGS)
AC_SUBST(LIBPOWERMAN_LIBS)
AC_SUBST(LIBMODBUS_CFLAGS)
AC_SUBST(LIBMODBUS_LIBS)
AC_SUBST(LIBIPMI_CFLAGS)
AC_SUBST(LIBIPMI_LIBS)
AC_SUBST(DOC_BUILD_LIST)
AC_SUBST(DOC_CHECK_LIST)
AC_SUBST(LIBWRAP_CFLAGS)
AC_SUBST(LIBWRAP_LIBS)
AC_SUBST(LIBLTDL_CFLAGS)
AC_SUBST(LIBLTDL_LIBS)
AC_SUBST(DRIVER_BUILD_LIST)
AC_SUBST(DRIVER_MAN_LIST)
AC_SUBST(DRIVER_INSTALL_TARGET)
AC_SUBST(NETLIBS)
AC_SUBST(SERLIBS)
AC_SUBST(PIDPATH)
AC_SUBST(STATEPATH)
AC_SUBST(CONFPATH)
AC_SUBST(BINDIR)
AC_SUBST(LIBDIR)
AC_SUBST(NUT_DATADIR, [`eval echo "${DATADIR}"`])
AC_SUBST(NUT_LIBEXECDIR, [`eval echo "${LIBEXECDIR}"`])
AC_SUBST(DRVPATH)
AC_SUBST(SBINDIR)
AC_SUBST(PORT)
AC_SUBST(RUN_AS_USER)
AC_SUBST(RUN_AS_GROUP)
AC_SUBST(SUN_LIBUSB)
AC_SUBST(WORDS_BIGENDIAN)
AC_SUBST(cgiexecdir)
AC_SUBST(devddir)
AC_SUBST(driverexecdir)
AC_SUBST(htmldir)
AC_SUBST(pkgconfigdir)
AC_SUBST(systemdsystemunitdir)
AC_SUBST(systemdshutdowndir)
AC_SUBST(systemdtmpfilesdir)
AC_SUBST(auglensdir)
AC_SUBST(hotplugdir)
AC_SUBST(udevdir)

dnl On a related note to warning setup below, we limit the minimum C and C++
dnl standard versions to ones we actively strive to support (C99 and C++11,
dnl GNU dialects tend to work on more systems if supported by compiler there).
dnl It is assumed that on very old systems whose compilers do not know these
dnl standards (only support ANSI/C89/C90 or older), as well as for builds
dnl that explicitly specify a CFLAGS="-std=..." (for GCC/CLANG toolkits),
dnl nothing should get added to CFLAGS/CXXFLAGS by this method:
NUT_COMPILER_FAMILY_FLAGS_DEFAULT_STANDARD

dnl Filter through known variants first, so automatic choices can be made.
dnl Note that clang identifies as gcc-compatible so should be probed first.
dnl TODO: Flip this default to "hard" when we clear existing codebase.
dnl Note: the "gcc-legacy" option is intentionally undocumented, it acts as
dnl least-surprise default if caller did not specify any --enable-warnings.
dnl Note: Currently the "gcc-minimal" mode below adapts to builds with
dnl C89/C90/ANSI mode to be less noisy. Keep this in mind if changing the
dnl default "nut_warning_difficulty" and/or the case handling below.
dnl NOTE: Until X-Mas 2021, the default was "minimal" (now "medium")
nut_warning_difficulty="medium"
AC_MSG_CHECKING([whether to pre-set warnings (from '${nut_enable_warnings}')])
AS_CASE(["${nut_enable_warnings}"],
    [no|all|gcc-legacy|gcc-minimal|clang-minimal|gcc-medium|clang-medium|gcc-hard|clang-hard], [],
    [clang], [nut_enable_warnings="${nut_enable_warnings}-${nut_warning_difficulty}"],
    [gcc], [
        AS_CASE(["${CFLAGS}"],
            [*89*|*90*|*ansi*], [nut_enable_warnings="${nut_enable_warnings}-minimal"],
            [nut_enable_warnings="${nut_enable_warnings}-${nut_warning_difficulty}"]
        )],
    [yes|auto|""], [
        AS_IF([test "${CLANGCC}" = "yes"], [nut_enable_warnings="clang-${nut_warning_difficulty}"],
            [AS_IF([test "${GCC}" = "yes"], [
                AS_CASE(["${CFLAGS}"],
                    [*89*|*90*|*ansi*], [nut_enable_warnings="gcc-minimal"],
                    [AS_CASE(["`$CC --version | grep -i gcc`"],
                        [*" "1.*|*" "2.*|3.*|*" "4.0*|*" "4.1*|*" "4.2*|*" "4.3*], [
                            AC_MSG_WARN([Very old GCC in use, disabling warnings])
                            dnl #AS_IF([test x"${nut_enable_Werror}" = xauto], [nut_enable_Werror="no"])
                            nut_enable_Werror="no"
                            nut_enable_warnings="no"],
                        [*" "4.4*|*" "4.5*|*" "4.6*|*" "4.7*|*" "4.8*], [nut_enable_warnings="gcc-legacy"],
                        [nut_enable_warnings="gcc-${nut_warning_difficulty}"]
                    )]
                )], [nut_enable_warnings="all"])
            ])
        ],
    [hard|auto-hard|auto=hard], [
        AS_IF([test "${CLANGCC}" = "yes"], [nut_enable_warnings="clang-hard"],
            [AS_IF([test "${GCC}" = "yes"], [nut_enable_warnings="gcc-hard"], [nut_enable_warnings="all"])
            ])
        ],
    [medium|auto-medium|auto=medium], [
        AS_IF([test "${CLANGCC}" = "yes"], [nut_enable_warnings="clang-medium"],
            [AS_IF([test "${GCC}" = "yes"], [nut_enable_warnings="gcc-medium"], [nut_enable_warnings="all"])
            ])
        ],
    [minimal|auto-minimal|auto=minimal], [
        AS_IF([test "${CLANGCC}" = "yes"], [nut_enable_warnings="clang-minimal"],
            [AS_IF([test "${GCC}" = "yes"], [nut_enable_warnings="gcc-minimal"], [nut_enable_warnings="all"])
            ])
        ],
    [legacy], [AS_IF([test "${GCC}" = "yes"], [nut_enable_warnings="gcc-legacy"], [nut_enable_warnings="no"])],
    [AC_MSG_WARN([Unsupported variant for --enable-warnings=${nut_enable_warnings}, ignored])
     nut_enable_warnings="no"
    ]
)
AC_MSG_RESULT(["${nut_enable_warnings}"])

dnl # Nothing special for gcc - we tend to survive it with GNU standard >= 99
dnl # and fail with strict C standard. Suggestions welcome for "gcc-hard" to
dnl # make a difference.
dnl # Note that "medium" and "hard" settings tend to trigger warnings also
dnl # from system headers, so we try to avoid them, using "-isystem path"
dnl # pre-set in our `m4/nut_compiler_family.m4` script:
dnl #    https://stackoverflow.com/questions/36355232/disable-certain-warnings-for-system-headers
dnl # and "-Wno-system-headers" below.
dnl # Some of the compiler flags (including those added by pkg-config of some
dnl # third-party dependency packages) can upset older compiler releases which
dnl # did not yet support those. Flags like "-Wno-unknown-warning" for GCC or
dnl # "-Wno-unknown-warning-option" for CLANG should take care of that at least
dnl # for toolkit versions that support these - set in NUT_COMPILER_FAMILY_FLAGS
dnl # Majority of sanity checks are enabled by "-Wextra" on both GCC and CLANG
dnl # and "-Weverything" additionally on CLANG. They are impractically picky,
dnl # especially with fallout from system headers that we can not impact anyway
dnl # so the "difficulty level" pre-sets exclude certain warning classes from
dnl # that report.
dnl ### Special exclusion picks for clang-hard:
dnl # -Wno-unused-macros -- system headers define a lot of stuff we do not use,
dnl #    gotta be fatal right?
dnl # -Wno-reserved-id-macro -- configure script tends to define _GNU_SOURCE_,
dnl #    __EXTENSIONS__ etc. which are underscored and reserved for compilers
dnl # -Wno-padded -- NSPR and NSS headers get to issue lots of that
dnl # -Wno-c++98-compat-pedantic -Wno-c++98-compat -- our C++ code uses nullptr
dnl #    as requested by newer linters, and C++98 does not. We require C++11
dnl #    or newer anyway, and skip building C++ library and test otherwise.
dnl ### Special exclusion picks for clang-medium (same as hard, plus...):
dnl # -Wno-float-conversion -Wno-double-promotion -Wno-implicit-float-conversion
dnl #    -- reduce noise due to floating-point literals like "3.14" being a C
dnl #    double type (a "3.14f" literal is a C float) cast implicitly into
dnl #    float variables. Also variadic functions like printf() cast their
dnl #    floating-point arguments into double (and small integer types into
dnl #    "int") which then confuses pedantic checks of printf("%f", floatval).
dnl # -Wno-conversion -- similarly for error: implicit conversion loses
dnl #    floating-point precision: 'double' to 'float' [-Werror,-Wconversion]
dnl #      max_output = atof(sValue);
dnl # -Wno-cast-qual -- our code calls some library methods in ways which use
dnl #    a "const char *" as a "char *" or vice-versa. Sometimes these method
dnl #    signatures differ between dependency releases; sometimes they just
dnl #    happened too hard to unravel cleanly and add more warnings.
dnl #    This exclusion may be removed after common warnings are solved,
dnl #    to allow progress on rectifying these cases next.
dnl # -Wno-incompatible-pointer-types-discards-qualifiers -- our code often
dnl #    defines (char*) as the type for struct fields and method arguments,
dnl #    but initializes/passes (char[]) variables or fixed strings.
dnl #    This makes at least clang-3.4 quite upset and noisy (seems newer
dnl #    versions care less about this situation).
dnl # -Wno-disabled-macro-expansion -- some system definitions of strncmp()
dnl #    and other routines are in fact recursive macros. The -Weverything
dnl #    mode of clang(-3.4) disables their handling, unless told otherwise.
AS_CASE(["${nut_enable_warnings}"],
    [all], [
        CFLAGS="${CFLAGS} -Wall"
        CXXFLAGS="${CXXFLAGS} -Wall"
        ],
    [clang-hard], [
        CFLAGS="${CFLAGS} -ferror-limit=0 -Wno-system-headers -Wall -Wextra -Weverything -Wno-disabled-macro-expansion -Wno-unused-macros -Wno-reserved-id-macro -Wno-padded -Wno-documentation -Wno-cast-qual -pedantic"
        CXXFLAGS="${CXXFLAGS} -ferror-limit=0 -Wno-system-headers -Wall -Wextra -Weverything -Wno-disabled-macro-expansion -Wno-unused-macros -Wno-reserved-id-macro -Wno-padded -Wno-documentation -Wno-cast-qual -Wno-c++98-compat-pedantic -Wno-c++98-compat"
        ],
    [clang-medium], [
        CFLAGS="${CFLAGS} -ferror-limit=0 -Wno-system-headers -Wall -Wextra -Weverything -Wno-disabled-macro-expansion -Wno-unused-macros -Wno-reserved-id-macro -Wno-padded -Wno-documentation -Wno-cast-qual -pedantic -Wno-float-conversion -Wno-double-promotion -Wno-implicit-float-conversion -Wno-conversion -Wno-incompatible-pointer-types-discards-qualifiers"
        CXXFLAGS="${CXXFLAGS} -ferror-limit=0 -Wno-system-headers -Wall -Wextra -Weverything -Wno-disabled-macro-expansion -Wno-unused-macros -Wno-reserved-id-macro -Wno-padded -Wno-documentation -Wno-cast-qual -Wno-c++98-compat-pedantic -Wno-c++98-compat"
        ],
    [clang-minimal], [
        CFLAGS="${CFLAGS} -ferror-limit=0 -Wall -Wextra -Wno-documentation"
        CXXFLAGS="${CXXFLAGS} -ferror-limit=0 -Wall -Wextra -Wno-documentation"
        ],
    [gcc-legacy], [CFLAGS="${CFLAGS} -Wall -Wsign-compare"],
    [gcc-minimal], [
        dnl Builds with C89 (and aliases) are quite noisy for C99+ syntax used
        dnl in NUT. The minimal-warnings should not complain in these builds.
        dnl To make matters worse, many modern OS and third-party library
        dnl headers can not be used with "C90 + pedantic" mode of GCC, either.
        CFLAGS="${CFLAGS} -Wall -Wsign-compare"
        CXXFLAGS="${CXXFLAGS} -Wall -Wextra"
        AS_CASE(["${CFLAGS}"],
            [*89*|*90*|*ansi*], [],
            [CFLAGS="${CFLAGS} -Wextra -pedantic"]
        )
        ],
    [gcc-medium|gcc-hard], [
        CFLAGS="${CFLAGS} -Wno-system-headers -Wall -Wextra -Wsign-compare"
        CXXFLAGS="${CXXFLAGS} -Wno-system-headers -Wall -Wextra"
        AS_CASE(["${CFLAGS}"],
            [*89*|*90*|*ansi*], [],
            [CFLAGS="${CFLAGS} -pedantic"]
        )
        ]
)

AC_MSG_CHECKING([whether to make warnings fatal])
AS_CASE(["${nut_enable_Werror}"],
    [yes|auto], [
        CFLAGS="${CFLAGS} -Werror"
        CXXFLAGS="${CXXFLAGS} -Werror"
        ],
    [no], [
        CFLAGS="${CFLAGS} -Wno-error"
        CXXFLAGS="${CXXFLAGS} -Wno-error"
        ]
)
AC_MSG_RESULT(["${nut_enable_Werror}"])

dnl Some compilers (e.g. older clang-3.4) have issues with built-in methods
dnl that are implemented as macros in system headers -- but only for some
dnl sources like snmp-ups.c, nutscan-serial.c, scan_eaton_serial.c, serial.c,
dnl scan_avahi.c, scan_xml_http.c, scan_snmp.c... (Seems they all refer to
dnl -DNETSNMP_USE_INLINE among other options, and tends to happen more with
dnl OpenSSL-enabled builds). Check if we like them?
AC_CHECK_HEADER([string.h],
    [AC_LANG_PUSH([C])
     CFLAGS_SAVED="${CFLAGS}"
     CFLAGS_BUILTIN_STR="-fno-builtin-strchr -fno-builtin-strcmp -fno-builtin-strncmp"
     CFLAGS="${CFLAGS} -Werror -Wunreachable-code ${LIBNETSNMP_CFLAGS} ${LIBLTDL_CFLAGS} ${LIBNEON_CFLAGS} ${LIBSSL_CFLAGS}"
     AC_MSG_CHECKING([whether we should disable string built-ins])
     dnl AC_DEFINE([HAVE_STRING_H], [1], [Define to 1 if you have <string.h>.])
     AC_COMPILE_IFELSE(
        [AC_LANG_PROGRAM(
            [[#include <string.h>
            ]], [char *s = "v1", c = '%';
if (strcmp(s, "v1") != 0) return 1;
if (strchr(s, '1') == NULL) return 1;
if (strchr(s, c) != NULL) return 1
/* no ";return 0;" here - autoconf adds one */
            ])],
        [CFLAGS="${CFLAGS_SAVED}"
         AC_MSG_RESULT([no, they are not a problem])],
        [CFLAGS="${CFLAGS_BUILTIN_STR} ${CFLAGS}"
         AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(
                [[#include <string.h>
                ]], [char *s = "v1", c = '%';
if (strcmp(s, "v1") != 0) return 1;
if (strchr(s, '1') == NULL) return 1;
if (strchr(s, c) != NULL) return 1
/* no ";return 0;" here - autoconf adds one */
                ])],
            [CFLAGS="${CFLAGS_BUILTIN_STR} ${CFLAGS_SAVED}"
             AC_MSG_RESULT([yes, this solves a problem])],
            [CFLAGS="${CFLAGS_SAVED} -Werror -Wno-unreachable-code ${LIBNETSNMP_CFLAGS} ${LIBLTDL_CFLAGS} ${LIBNEON_CFLAGS} ${LIBSSL_CFLAGS}"
             AC_COMPILE_IFELSE(
                [AC_LANG_PROGRAM(
                    [[#include <string.h>
                    ]], [char *s = "mibs", c = '%';
/* Macro version of strcmp() has problems with strings shorter than
 * 3 or 4 bytes, so to avoid nailing "-Warray-bounds" as well,
 * here we just test for longer strings - existing NUT sources were
 * fixed for this situation already */
if (strcmp(s, "mibs") != 0) return 1;
if (strchr(s, 'b') == NULL) return 1;
if (strchr(s, c) != NULL) return 1
/* no ";return 0;" here - autoconf adds one */
                    ])],
                [dnl CFLAGS="${CFLAGS_SAVED} -Wno-unreachable-code"
                 dnl NOTE: Empirically, constrain to just LIBNETSNMP_CFLAGS
                 CFLAGS="${CFLAGS_SAVED}"
                 LIBLTDL_CFLAGS="${LIBLTDL_CFLAGS} -Wno-unreachable-code"
                 LIBNETSNMP_CFLAGS="${LIBNETSNMP_CFLAGS} -Wno-unreachable-code"
                 AC_MSG_RESULT([no, but -Wno-unreachable-code solves the problem for this compiler])],
                [CFLAGS="${CFLAGS_SAVED}"
                 AC_MSG_RESULT([no, this does not solve the problem or is not supported])
                ])
            ])
        ]
     )
     AC_LANG_POP([C])]
)

dnl Similar to above, for s_addr = htonl((ntohl(ip->start.s_addr) + 1));
dnl which causes "shadowed local variable" as (re-)defined in nested macros.
dnl Technically also needs to `#include <netinet/in.h>` for struct in_addr
dnl but that should be pulled by inet.h anyway
AC_CHECK_HEADER([arpa/inet.h],
    [AC_LANG_PUSH([C])
     CFLAGS_SAVED="${CFLAGS}"
     CFLAGS_BUILTIN_NTOHL="-fno-builtin-htonl -fno-builtin-ntohl"
     CFLAGS="${CFLAGS} -Werror -Wunreachable-code -Wshadow ${LIBNETSNMP_CFLAGS} ${LIBLTDL_CFLAGS} ${LIBNEON_CFLAGS} ${LIBSSL_CFLAGS}"
     AC_MSG_CHECKING([whether we should disable htonl/ntohl built-ins])
     dnl AC_DEFINE([HAVE_ARPA_INET_H], [1], [Define to 1 if you have <arpa/inet.h>.])
     AC_COMPILE_IFELSE(
        [AC_LANG_PROGRAM(
            [[#include <arpa/inet.h>
            ]], [struct in_addr sin = {0};
sin.s_addr = htonl((ntohl(sin.s_addr) + 1))
/* no ";return 0;" here - autoconf adds one */
            ])],
        [CFLAGS="${CFLAGS_SAVED}"
         AC_MSG_RESULT([no, they are not a problem])],
        [CFLAGS="${CFLAGS_BUILTIN_NTOHL} ${CFLAGS}"
         AC_COMPILE_IFELSE(
            [AC_LANG_PROGRAM(
                [[#include <arpa/inet.h>
                ]], [struct in_addr sin = {0};
sin.s_addr = htonl((ntohl(sin.s_addr) + 1))
/* no ";return 0;" here - autoconf adds one */
                ])],
            [CFLAGS="${CFLAGS_BUILTIN_NTOHL} ${CFLAGS_SAVED}"
             AC_MSG_RESULT([yes, this solves a problem])],
            [CFLAGS="${CFLAGS_SAVED} -Werror -Wno-shadow ${LIBNETSNMP_CFLAGS} ${LIBLTDL_CFLAGS} ${LIBNEON_CFLAGS} ${LIBSSL_CFLAGS}"
             AC_COMPILE_IFELSE(
                [AC_LANG_PROGRAM(
                    [[#include <arpa/inet.h>
                    ]], [struct in_addr sin = {0};
sin.s_addr = htonl((ntohl(sin.s_addr) + 1))
                    ])],
                [CFLAGS="${CFLAGS_SAVED}"
                 LIBLTDL_CFLAGS="${LIBLTDL_CFLAGS} -Wno-shadow"
                 LIBNETSNMP_CFLAGS="${LIBNETSNMP_CFLAGS} -Wno-shadow"
                 AC_MSG_RESULT([no, but -Wno-shadow solves the problem for this compiler])],
                [CFLAGS="${CFLAGS_SAVED}"
                 AC_MSG_RESULT([no, this does not solve the problem or is not supported])
                ])
            ])
        ]
     )
     AC_LANG_POP([C])]
)

dnl Finally restore warnings settings that the caller might have provided in CFLAGS etc
NUT_POP_WARNINGS

dnl Due to possibly repetitive content, generate unique settings
dnl relative to the top_builddir (distcheck and all):
AC_MSG_CHECKING([for top build dir for this configure run])
TOP_BUILDDIR=""
AS_IF([test -n "${ac_abs_top_builddir}" && test -d "${ac_abs_top_builddir}"],
    [TOP_BUILDDIR="${ac_abs_top_builddir}"],
    [AS_IF([test -n "${ac_pwd}" && test -d "${ac_pwd}"],
        [TOP_BUILDDIR="${ac_pwd}"],
        [TOP_BUILDDIR="`dirname "$0"`"
         TOP_BUILDDIR="`cd "$TOP_BUILDDIR" && pwd`" || AC_MSG_ERROR([Can not detect TOP_BUILDDIR])]
    )]
)
AC_MSG_RESULT(["${TOP_BUILDDIR}"])

ABS_TOP_BUILDDIR="`cd "${TOP_BUILDDIR}" && pwd`" || AC_MSG_ERROR([Can not detect ABS_TOP_BUILDDIR])
ABS_TOP_SRCDIR="`cd "${abs_srcdir}" && pwd`" || AC_MSG_ERROR([Can not detect ABS_TOP_SRCDIR])
AM_CONDITIONAL([BUILDING_IN_TREE], [test "${ABS_TOP_BUILDDIR}" = "${ABS_TOP_SRCDIR}"])

AC_MSG_CHECKING([whether to customize ${TOP_BUILDDIR}/scripts/systemd/nut-common.tmpfiles.in for this system])
AS_IF([test -n "$systemdtmpfilesdir"],
    [mkdir -p "${TOP_BUILDDIR}"/scripts/systemd
     cat > "${TOP_BUILDDIR}"/scripts/systemd/nut-common.tmpfiles.in << EOF
# State file (e.g. upsd to driver) and pidfile location for NUT:
d @STATEPATH@/nut 0770 @RUN_AS_USER@ @RUN_AS_GROUP@ - -
X @STATEPATH@/nut
EOF
    AS_IF([test "$STATEPATH" != "$PIDPATH"],
        [cat >> "${TOP_BUILDDIR}"/scripts/systemd/nut-common.tmpfiles.in << EOF
d @PIDPATH@/nut 0770 @RUN_AS_USER@ @RUN_AS_GROUP@ - -
X @PIDPATH@/nut
EOF])
    AS_IF([test -n "$ALTPIDPATH" && test "$STATEPATH" != "$ALTPIDPATH" && test "$PIDPATH" != "$ALTPIDPATH"],
        [cat >> "${TOP_BUILDDIR}"/scripts/systemd/nut-common.tmpfiles.in << EOF
d @ALTPIDPATH@/nut 0770 @RUN_AS_USER@ @RUN_AS_GROUP@ - -
X @ALTPIDPATH@/nut
EOF])
    AS_IF([test -n "$ALTSTATEPATH" && test "$STATEPATH" != "$ALTSTATEPATH" && test "$ALTSTATEPATH" != "$ALTPIDPATH" && test "$PIDPATH" != "$ALTSTATEPATH"],
        [cat >> "${TOP_BUILDDIR}"/scripts/systemd/nut-common.tmpfiles.in << EOF
d @ALTSTATEPATH@/nut 0770 @RUN_AS_USER@ @RUN_AS_GROUP@ - -
X @ALTSTATEPATH@/nut
EOF])
])
AC_MSG_RESULT([done])

AC_MSG_NOTICE([Generating "data" files from templates, see below for executable scripts])
AC_CONFIG_FILES([
 clients/Makefile
 common/Makefile
 conf/Makefile
 conf/upsmon.conf.sample
 conf/upssched.conf.sample
 data/html/header.html
 data/html/Makefile
 data/Makefile
 data/driver.list
 docs/Makefile
 docs/cables/Makefile
 docs/docinfo.xml
 docs/man/Makefile
 drivers/Makefile
 include/Makefile
 lib/libupsclient-config
 lib/libupsclient.pc
 lib/libnutclient.pc
 lib/libnutclientstub.pc
 lib/libnutscan.pc
 lib/Makefile
 scripts/Aix/nut-aix.spec
 scripts/augeas/Makefile
 scripts/augeas/nutnutconf.aug
 scripts/augeas/nutupsdconf.aug
 scripts/augeas/nutupsdusers.aug
 scripts/augeas/nutupsmonconf.aug
 scripts/augeas/nutupsschedconf.aug
 scripts/augeas/nuthostsconf.aug
 scripts/augeas/nutupssetconf.aug
 scripts/avahi/nut.service
 scripts/devd/Makefile
 scripts/hotplug/Makefile
 scripts/hotplug/libhidups
 scripts/HP-UX/nut.psf
 scripts/python/Makefile
 scripts/python/module/PyNUT.py
 scripts/upsdrvsvcctl/Makefile
 scripts/systemd/Makefile
 scripts/systemd/nut-common.tmpfiles
 scripts/systemd/nut-driver@.service
 scripts/systemd/nut-monitor.service
 scripts/systemd/nut-server.service
 scripts/systemd/nut-driver-enumerator.service
 scripts/systemd/nut-driver-enumerator.path
 scripts/Solaris/nut-driver-enumerator.xml
 scripts/Solaris/nut-driver.xml
 scripts/Solaris/nut-monitor.xml
 scripts/Solaris/nut-server.xml
 scripts/Solaris/nut.xml
 scripts/Solaris/Makefile
 scripts/Solaris/pkginfo
 scripts/udev/Makefile
 scripts/udev/nut-ipmipsu.rules
 scripts/ufw/Makefile
 scripts/ufw/nut.ufw.profile
 scripts/Makefile
 server/Makefile
 tools/Makefile
 tools/nut-scanner/Makefile
 tests/Makefile
 tests/NIT/Makefile
 Makefile
])

AC_MSG_NOTICE([Generating templated script files that should be marked executable])
m4_foreach_w([SCRIPTFILE], [
 scripts/Aix/nut.init
 scripts/HP-UX/postinstall
 scripts/python/app/NUT-Monitor-py2gtk2
 scripts/python/app/NUT-Monitor-py3qt5
 scripts/augeas/gen-nutupsconf-aug.py
 scripts/python/module/test_nutclient.py
 scripts/upsdrvsvcctl/nut-driver-enumerator.sh
 scripts/upsdrvsvcctl/upsdrvsvcctl
 scripts/systemd/nutshutdown
 scripts/Solaris/svc-nut-server
 scripts/Solaris/svc-nut-monitor
 scripts/Solaris/precheck.py
 scripts/Solaris/preinstall
 scripts/Solaris/postinstall
 scripts/Solaris/preremove
 scripts/Solaris/postremove
 scripts/Solaris/preproto.pl
 scripts/Solaris/nut
 tools/gitlog2changelog.py
 tools/nut-snmpinfo.py
], [
 dnl Autoconf substitutes the token above specified in plain text,
 dnl e.g. the brace below is empty and bracket gives verbatim varname
 dnl AC_MSG_NOTICE([Script: SCRIPTFILE brace:(${SCRIPTFILE}) bracket:([SCRIPTFILE])])
 AC_CONFIG_FILES(SCRIPTFILE, chmod +x "SCRIPTFILE")
])

AC_MSG_NOTICE([Generating templated script files whose templates might have been generated (or not) by autogen.sh calling our helper scripts])
m4_foreach_w([SCRIPTFILE], [
 scripts/augeas/nutupsconf.aug
 scripts/udev/nut-usbups.rules
 scripts/devd/nut-usb.conf
], [
	AC_MSG_CHECKING([whether to generate SCRIPTFILE])
	AS_IF([test -s SCRIPTFILE.in && ! test -f SCRIPTFILE.in.AUTOGEN_WITHOUT],
		[AC_MSG_RESULT(yes)
		 AC_CONFIG_FILES(SCRIPTFILE)],
		[AC_MSG_RESULT(no)]
	)
])

AC_OUTPUT

NUT_PRINT_FEATURE_REPORT
