#!/bin/sh

##############################
##  Configurer for BitlBee  ##
##                          ##
##  Copyright 2004 Lintux   ##
##  Copyright 2002 Lucumo   ##
##############################

prefix="/usr/local/"
bindir="$prefix/bin/"
sbindir="$prefix/sbin/"
etcdir="$prefix/etc/bitlbee/"
mandir="$prefix/share/man/"
datadir="$prefix/share/bitlbee/"
config="/var/lib/bitlbee/"
libdir="$prefix/lib/"
plugindir="$prefix/lib/bitlbee/"
includedir="$prefix/include/bitlbee/"
systemdsystemunitdir=""
sysusersdir=""
libevent="/usr/"
pidfile="/var/run/bitlbee.pid"
ipcsocket=""
pcdir="$prefix/lib/pkgconfig"
systemlibdirs="/lib64 /usr/lib64 /usr/local/lib64 /lib /usr/lib /usr/local/lib"
sysroot=""

configure_args="$*"

# Set these to default-on to let it be overriden by either the user or purple
#
# If the user sets one of these to 1, purple won't disable them.
# Otherwise, if it's still default-on, it gets included in normal builds,
# but not purple ones.
jabber="default-on"

twitter=1
purple=0

verbose=0
doc=1
debug=0
strip=0
gcov=0
asan=0
plugins=1
otr=0

events=glib
external_json_parser=auto
ssl=auto

pam=0
ldap=0

pie=1

systemd=auto

arch=$(uname -s)
arch_rel=$(uname -r)

GLIB_MIN_VERSION=2.32

# Cygwin, Darwin and SunOS < 5.11 do not support PIC/PIE
case "$arch" in
	CYGWIN* )
		pie=0;;
	Darwin )
		pie=0;;
	SunOS )
		if [ "$arch_rel" = "5.10" ]; then
			pie=0
		fi
		;;
esac

get_version() {
	REAL_BITLBEE_VERSION=$(grep '^#define BITLBEE_VERSION ' "$srcdir"/bitlbee.h | sed 's/.*\"\(.*\)\".*/\1/')

	if [ -n "$BITLBEE_VERSION" ]; then
		# environment variable already set to something to spoof it
		# don't replace it with the git stuff
		return
	fi

	BITLBEE_VERSION=$REAL_BITLBEE_VERSION

	if [ -d "$srcdir"/.git ] && type git > /dev/null 2> /dev/null; then
		timestamp=$(cd "$srcdir" || exit 1; git show -s --format=%ci HEAD | sed 's/ .*$//; s/-//g')
		branch=$(cd "$srcdir" || exit 1; git rev-parse --abbrev-ref HEAD)

		search='\(.*\)-\([0-9]*\)-\(g[0-9a-f]*\)'
		replace="\1+$timestamp+$branch+\2-\3-git"

		if ! describe=$(cd "$srcdir" || exit 1; git describe --long --tags 2>/dev/null) ; then
			describe=${REAL_BITLBEE_VERSION}-0-g$(cd "$srcdir" || exit; git rev-parse --short HEAD)
		fi

		BITLBEE_VERSION=$(echo "$describe" | sed "s#$search#$replace#")

		unset timestamp branch search replace describe
	fi
}

if [ "$1" = "--dump-version" ]; then
	srcdir=$(cd "$(dirname "$0")" || exit;pwd)
	get_version
	echo "$BITLBEE_VERSION"
	exit
fi

echo BitlBee configure

while [ -n "$1" ]; do
	e="$(expr "X$1" : 'X--\(.*=.*\)')"
	if [ -z "$e" ]; then
		cat<<EOF

Usage: $0 [OPTIONS]

Option		Description				Default

--prefix=...	Directories to put files in		$prefix
--bindir=...						$bindir
--sbindir=...						$sbindir
--etcdir=...						$etcdir
--mandir=...						$mandir
--datadir=...						$datadir
--plugindir=...						$plugindir
--systemdsystemunitdir=...				$systemdsystemunitdir
--sysusersdir                       $sysusersdir
--pidfile=...						$pidfile
--config=...						$config

--verbose=0/1	Disable/enable verbose build		$verbose

--jabber=0/1	Disable/enable Jabber part		$jabber
--twitter=0/1	Disable/enable Twitter part		$twitter

--purple=0/1	Disable/enable libpurple support	$purple
		(automatically disables other protocol modules)

--pam=0/1	Disable/enable PAM authentication	$pam
--ldap=0/1	Disable/enable LDAP authentication	$ldap

--doc=0/1	Disable/enable help.txt generation	$doc
--debug=0/1	Disable/enable debugging		$debug
--strip=0/1	Disable/enable binary stripping		$strip
--pie=0/1       Build position independent executable   $pie
--gcov=0/1	Disable/enable test coverage reporting	$gcov
--asan=0/1	Disable/enable AddressSanitizer		$asan
--plugins=0/1	Disable/enable plugins support		$plugins
--otr=0/1/auto/plugin
		Disable/enable OTR encryption support	$otr

--events=...	Event handler (glib, libevent)		$events
--ssl=...	SSL library to use (gnutls, nss, openssl, auto)
							$ssl
--external_json_parser=0/1/auto	Use External JSON parser $external_json_parser
--systemd=0/1  Enable/disable systemd support $systemd


--target=...	Cross compilation target 		same as host
--sysroot=...	Cross compilation sysroot 		$sysroot
EOF
		exit;
	fi
	eval "$e"
	shift;
done

# Expand $prefix and get rid of double slashes
bindir=$(eval echo "$bindir/" | sed 's/\/\{1,\}/\//g')
sbindir=$(eval echo "$sbindir/" | sed 's/\/\{1,\}/\//g')
etcdir=$(eval echo "$etcdir/" | sed 's/\/\{1,\}/\//g')
mandir=$(eval echo "$mandir/" | sed 's/\/\{1,\}/\//g')
datadir=$(eval echo "$datadir/" | sed 's/\/\{1,\}/\//g')
config=$(eval echo "$config/" | sed 's/\/\{1,\}/\//g')
libdir=$(eval echo "$libdir/" | sed 's/\/\{1,\}/\//g')
plugindir=$(eval echo "$plugindir/" | sed 's/\/\{1,\}/\//g')
includedir=$(eval echo "$includedir"/ | sed 's/\/\{1,\}/\//g')
libevent=$(eval echo "$libevent"/ | sed 's/\/\{1,\}/\//g')

pidfile=$(eval echo "$pidfile" | sed 's/\/\{1,\}/\//g')
ipcsocket=$(eval echo "$ipcsocket" | sed 's/\/\{1,\}/\//g')
pcdir=$(eval echo "$pcdir" | sed 's/\/\{1,\}/\//g')

protocols_mods=""

cat <<EOF >Makefile.settings
## BitlBee settings, generated by configure

# ./configure $configure_args

PREFIX=$prefix
BINDIR=$bindir
SBINDIR=$sbindir
ETCDIR=$etcdir
MANDIR=$mandir
DATADIR=$datadir
PLUGINDIR=$plugindir
CONFIG=$config
LIBDIR=$libdir
INCLUDEDIR=$includedir
PCDIR=$pcdir

TARGET=$target

INSTALL=install -p

DESTDIR=
LFLAGS=
EFLAGS=-lm
EOF

srcdir=$(cd "$(dirname "$0")" || exit;pwd)
currdir=$(pwd)
if [ ! "$srcdir" = "$currdir" ]; then 
	echo
	echo "configure script run from a different directory. Will create some symlinks..."
	if [ ! -e Makefile ] || [ -L Makefile ]; then
		COPYDIRS="doc lib protocols tests utils"
		mkdir -p "$(cd "$srcdir" || exit 1; find "$COPYDIRS" -type d)"
		find . -name Makefile -type l -print0 | xargs -0 rm 2> /dev/null
		dst="$PWD"
		cd "$srcdir" || exit 1
		find . -type f -name Makefile -print | while read -r i ; do
			ln -s "$PWD${i#.}" "$dst/$i";
		done
		cd "$dst" || exit 1
		rm -rf .bzr
	fi
	
	echo "_SRCDIR_=$srcdir/" >> Makefile.settings
	CFLAGS="$CFLAGS -I${dst}"
else
	srcdir=$PWD
fi

cat<<EOF >config.h
/* BitlBee settings, generated by configure
   
   Do *NOT* use any of these defines in your code without thinking twice, most
   of them can/will be overridden at run-time */

#define BITLBEE_CONFIGURE_ARGS "$configure_args"

#define CONFIG "$config"
#define ETCDIR "$etcdir"
#define VARDIR "$datadir"
#define PLUGINDIR "$plugindir"
#define DATADIR "$datadir"
#define PIDFILE "$pidfile"
#define IPCSOCKET "$ipcsocket"
EOF



if [ -n "$target" ]; then
	# prepend sysroot to system lib dirs

	systemlibdirs_cross=''
	for i in $systemlibdirs; do
		systemlibdirs_cross="$systemlibdirs_cross $sysroot$i"
	done
	systemlibdirs=$systemlibdirs_cross
	unset systemlibdirs_cross

	# backward compatibility

	if [ -z "$PKG_CONFIG_LIBDIR" ]; then
		PKG_CONFIG_LIBDIR=/usr/"$target"/lib/pkgconfig
		export PKG_CONFIG_LIBDIR
	fi

	if [ -d /usr/"$target"/bin ]; then
		PATH=/usr/"$target"/bin:$PATH
	fi

	if [ -d /usr/"$target"/lib ]; then
		systemlibdirs="$systemlibdirs /usr/$target/lib"
	fi

	CC=$target-cc
	LD=$target-ld
	STRIP=$target-strip
fi

if [ "$asan" = "1" ]; then
	CFLAGS="$CFLAGS -fsanitize=address"
	LDFLAGS="$LDFLAGS -fsanitize=address"
	debug=1
fi

if [ "$verbose" = "0" ]; then
	echo 'VERBOSE=@' >> Makefile.settings
else
	echo 'VERBOSE=' >> Makefile.settings
fi

cat <<EOF >>Makefile.settings

# Enable/disable output verbosity
ifdef V
ifeq (\$(V),1)
	VERBOSE=
else
	VERBOSE=@
endif
endif

EOF

if [ "$debug" = "1" ]; then
	echo 'DEBUG=1' >> Makefile.settings
	CFLAGS="$CFLAGS -g3 -DDEBUG -O0"
else
	[ -z "$CFLAGS" ] && CFLAGS="-g -O2"
fi

if [ "$pie" = "1" ]; then
	echo 'CFLAGS_BITLBEE=-fPIE' >> Makefile.settings
	echo 'LDFLAGS_BITLBEE=-pie' >> Makefile.settings
fi

# shellcheck disable=SC2129
echo "LDFLAGS=$LDFLAGS" >> Makefile.settings

echo "CFLAGS=$CFLAGS $CPPFLAGS" >> Makefile.settings
echo CFLAGS+=-I"${srcdir}" -I"${srcdir}"/lib -I"${srcdir}"/protocols -I. >> Makefile.settings

echo CFLAGS+=-DHAVE_CONFIG_H -D_GNU_SOURCE >> Makefile.settings

if type gcc > /dev/null 2> /dev/null; then
	CC=gcc
elif type cc > /dev/null 2> /dev/null; then
	CC=cc
else
	echo 'Cannot find a C compiler, aborting.'
	exit 1;
fi

echo "CC=$CC" >> Makefile.settings;
if echo $CC | grep -qw 'gcc\|clang'; then
	# Apparently -Wall is gcc-specific?
	echo CFLAGS+=-Wall -Wformat -Werror=format-security >> Makefile.settings
fi

if [ -z "$LD" ]; then
	if type ld > /dev/null 2> /dev/null; then
		LD=ld
	else
		echo 'Cannot find ld, aborting.'
		exit 1;
	fi
fi

echo "LD=$LD" >> Makefile.settings

if [ -z "$PKG_CONFIG" ]; then
	PKG_CONFIG=pkg-config
fi

if ! $PKG_CONFIG --version > /dev/null 2>/dev/null; then
	echo
	echo 'Cannot find pkg-config, aborting.'
	exit 1
fi

if $PKG_CONFIG glib-2.0; then
	if $PKG_CONFIG glib-2.0 --atleast-version=$GLIB_MIN_VERSION; then
		cat<<EOF >>Makefile.settings
EFLAGS+=$($PKG_CONFIG --libs glib-2.0 gmodule-2.0)
CFLAGS+=$($PKG_CONFIG --cflags glib-2.0 gmodule-2.0)
EOF
	else
		echo
		echo "Found glib2 $($PKG_CONFIG glib-2.0 --modversion), but version $GLIB_MIN_VERSION or newer is required."
		exit 1
	fi
else
	echo
	echo 'Cannot find glib2 development libraries, aborting. (Install libglib2-dev?)'
	exit 1
fi

if [ "$events" = "libevent" ]; then
	if ! [ -f "${libevent}include/event.h" ]; then
		echo
		echo 'Warning: Could not find event.h, you might have to install it and/or specify'
		echo 'its location using the --libevent= argument. (Example: If event.h is in'
		echo '/usr/local/include and binaries are in /usr/local/lib: --libevent=/usr/local)'
	fi
	
	echo '#define EVENTS_LIBEVENT' >> config.h
	cat <<EOF >>Makefile.settings
EFLAGS+=-levent -L${libevent}lib
CFLAGS+=-I${libevent}include
EOF
elif [ "$events" = "glib" ]; then
	## We already use glib anyway, so this is all we need (and in fact not even this, but just to be sure...):
	echo '#define EVENTS_GLIB' >> config.h
else
	echo
	echo 'ERROR: Unknown event handler specified.'
	exit 1
fi
echo 'EVENT_HANDLER=events_'$events'.o' >> Makefile.settings

if [ "$external_json_parser" = "auto" ]; then
	if pkg-config --exists json-parser; then
		external_json_parser=1
	else
		external_json_parser=0
	fi
fi
echo "EXTERNAL_JSON_PARSER=$external_json_parser" >> Makefile.settings
if [ "$external_json_parser" = "1" ]; then
    # shellcheck disable=SC2129
    echo "CFLAGS+=$(pkg-config --cflags json-parser)" >> Makefile.settings
    echo "LDFLAGS_BITLBEE+=$(pkg-config --libs json-parser)" >> Makefile.settings
    echo "LDFLAGS_TESTS+=$(pkg-config --libs json-parser)" >> Makefile.settings
fi


detect_gnutls()
{
	if $PKG_CONFIG --exists gnutls; then
		cat <<EOF >>Makefile.settings
EFLAGS+=$($PKG_CONFIG --libs gnutls) $(libgcrypt-config --libs)
CFLAGS+=$($PKG_CONFIG --cflags gnutls) $(libgcrypt-config --cflags)
EOF
		ssl=gnutls
		if ! $PKG_CONFIG gnutls --atleast-version=2.8; then
			echo
			echo 'Warning: With GnuTLS versions <2.8, certificate expire dates are not verified.'
		fi
		ret=1
	elif libgnutls-config --version > /dev/null 2> /dev/null; then
		cat <<EOF >>Makefile.settings
EFLAGS+=$(libgnutls-config --libs) $(libgcrypt-config --libs)
CFLAGS+=$(libgnutls-config --cflags) $(libgcrypt-config --cflags)
EOF
		
		ssl=gnutls
		ret=1;
	else
		ret=0;
	fi;
}

detect_nss()
{
	if $PKG_CONFIG --version > /dev/null 2>/dev/null && $PKG_CONFIG nss; then
		cat<<EOF >>Makefile.settings
EFLAGS+=$($PKG_CONFIG --libs nss)
CFLAGS+=$($PKG_CONFIG --cflags nss)
EOF
		
		ssl=nss
		ret=1;
	else
		ret=0;
	fi;
}

RESOLV_TESTCODE='
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h> 

int main()
{

	res_query( NULL, 0, 0, NULL, 0);
	dn_expand( NULL, NULL, NULL, NULL, 0);
	dn_skipname( NULL, NULL);
}
'
RESOLV_NS_TESTCODE='
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h> 

int main()
{
	ns_initparse( NULL, 0, NULL );
	ns_parserr( NULL, ns_s_an, 0, NULL );
}
'
RESOLV_NS_TYPES_TESTCODE='
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/nameser.h>

int main()
{
	ns_msg nsh;
	ns_rr rr;

	/* Not all platforms we want to work on have
	 ns_* routines, so use this to make sure
	 the compiler uses it.*/
	return (int)(sizeof(nsh) + sizeof(rr));
}
'

BACKTRACE_TESTCODE='
#include <execinfo.h>

int main()
{
	void *trace[16];
	return backtrace(trace, 16);
}
'

detect_resolv_dynamic()
{
	case "$arch" in
	OpenBSD )
		# In FreeBSD res_*/dn_* routines are present in libc.so
		LIBRESOLV=;;
	FreeBSD )
		# In FreeBSD res_*/dn_* routines are present in libc.so
		LIBRESOLV=;;
	CYGWIN* )
		# In Cygwin res_*/dn_* routines are present in libc.so
		LIBRESOLV=;;
	* )
		LIBRESOLV=-lresolv;;
	esac
	TMPFILE=$(mktemp /tmp/bitlbee-configure.XXXXXX)
	ret=1
	if echo "$RESOLV_TESTCODE" | $CC -o "$TMPFILE" -x c - $LIBRESOLV >/dev/null 2>/dev/null ; then
		echo "EFLAGS+=$LIBRESOLV" >> Makefile.settings
		ret=0
	fi

	rm -f "$TMPFILE"
	return $ret
}

detect_resolv_static()
{
	TMPFILE=$(mktemp /tmp/bitlbee-configure.XXXXXX)
	ret=1
	for i in $systemlibdirs; do
		if [ -f "$i"/libresolv.a ]; then
			if echo "$RESOLV_TESTCODE" | $CC -o "$TMPFILE" -x c - -Wl,"$i"/libresolv.a >/dev/null 2>/dev/null ; then
				echo "EFLAGS+=$i/libresolv.a" >> Makefile.settings
				ret=0
			fi
		fi
	done

	rm -f "$TMPFILE"
	return $ret
}

detect_resolv_ns_dynamic()
{
	case "$arch" in
	FreeBSD )
		# In FreeBSD ns_ routines are present in libc.so
		LIBRESOLV=;;
	* )
		LIBRESOLV=-lresolv;;
	esac
	TMPFILE=$(mktemp /tmp/bitlbee-configure.XXXXXX)
	ret=1
	if echo "$RESOLV_NS_TESTCODE" | $CC -o "$TMPFILE" -x c - $LIBRESOLV >/dev/null 2>/dev/null ; then
		ret=0
	fi

	rm -f "$TMPFILE"
	return $ret
}

detect_resolv_ns_static()
{
	TMPFILE=$(mktemp /tmp/bitlbee-configure.XXXXXX)
	ret=1
	for i in $systemlibdirs; do
		if [ -f "$i"/libresolv.a ]; then
			if echo "$RESOLV_NS_TESTCODE" | $CC -o "$TMPFILE" -x c - -Wl,"$i"/libresolv.a >/dev/null 2>/dev/null ; then
				ret=0
			fi
		fi
	done

	rm -f "$TMPFILE"
	return $ret
}

detect_nameser_has_ns_types()
{
	TMPFILE=$(mktemp /tmp/bitlbee-configure.XXXXXX)
	ret=1
	# since we aren't actually linking with ns_* routines
	# we can just compile the test code
	if echo "$RESOLV_NS_TYPES_TESTCODE" | $CC -o "$TMPFILE" -x c -  >/dev/null 2>/dev/null ; then
		ret=0
	fi

	rm -f "$TMPFILE"
	return $ret
}

detect_backtrace()
{
	TMPFILE=$(mktemp /tmp/bitlbee-configure.XXXXXX)
	ret=1
	if echo "$BACKTRACE_TESTCODE" | $CC -o "$TMPFILE" -x c -  >/dev/null 2>/dev/null ; then
		ret=0
	fi

	rm -f "$TMPFILE"
	return $ret
}

if [ "$ssl" = "auto" ]; then
	detect_gnutls
	if [ "$ret" = "0" ]; then
		# Disable NSS for now as it's known to not work very well ATM.
		#detect_nss
		:
	fi
elif [ "$ssl" = "gnutls" ]; then
	detect_gnutls
elif [ "$ssl" = "nss" ]; then
	detect_nss
elif [ "$ssl" = "openssl" ]; then
	echo
	echo 'No detection code exists for OpenSSL. Make sure that you have a complete'
	echo 'installation of OpenSSL (including devel/header files) before reporting'
	echo 'compilation problems.'
	echo
	echo 'Also, keep in mind that the OpenSSL is, according to some people, not'
	echo 'completely GPL-compatible. Using GnuTLS is recommended and better supported'
	echo 'by us. However, on many BSD machines, OpenSSL can be considered part of the'
	echo 'operating system, which makes it GPL-compatible.'
	echo
	echo 'For more info, see: http://www.openssl.org/support/faq.html#LEGAL2'
	echo '                    http://www.gnome.org/~markmc/openssl-and-the-gpl.html'
	echo
	echo 'Please note that distributing a BitlBee binary which links to OpenSSL is'
	echo 'probably illegal. If you want to create and distribute a binary BitlBee'
	echo 'package, you really should use GnuTLS instead.'
	echo
	echo 'Also, the OpenSSL license requires us to say this:'
	echo ' *    "This product includes software developed by the OpenSSL Project'
	echo ' *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"'
	
	echo 'EFLAGS+=-lssl -lcrypto' >> Makefile.settings
	
	ret=1
else
	echo
	echo 'ERROR: Unknown SSL library specified.'
	exit 1
fi

if [ "$ret" = "0" ]; then
	echo
	echo 'ERROR: Could not find a suitable SSL library (GnuTLS, libnss or OpenSSL).'
	echo '       Please note that this script doesn'\''t have detection code for OpenSSL,'
	echo '       so if you want to use that, you have to select it by hand.'
	
	exit 1
fi;

echo 'SSL_CLIENT=ssl_'$ssl'.o' >> Makefile.settings

if detect_nameser_has_ns_types; then
	echo '#define NAMESER_HAS_NS_TYPES' >> config.h
fi
if detect_resolv_dynamic || detect_resolv_static; then
	echo '#define HAVE_RESOLV_A' >> config.h
	if detect_resolv_ns_dynamic || detect_resolv_ns_static; then
		echo '#define HAVE_RESOLV_A_WITH_NS' >> config.h
	fi
else
	echo 'Insufficient resolv routines. Jabber server must be set explicitly'
fi

if detect_backtrace; then
	echo '#define HAVE_BACKTRACE' >> config.h
	echo "#define CRASHFILE \"${config}crash.log\"" >> config.h
fi

STORAGES="xml"

for i in $STORAGES; do
	STORAGE_OBJS="$STORAGE_OBJS storage_$i.o"
done
echo "STORAGE_OBJS=$STORAGE_OBJS" >> Makefile.settings

authobjs=
authlibs=
if [ "$pam" = "0" ]; then
	echo '#undef WITH_PAM' >> config.h
else
	if ! echo '#include <security/pam_appl.h>' | $CC -E - >/dev/null 2>/dev/null; then
		echo 'Cannot find libpam development libraries, aborting. (Install libpam0g-dev?)'
		exit 1
	fi
	echo '#define WITH_PAM' >> config.h
	authobjs=$authobjs'auth_pam.o '
	authlibs=$authlibs'-lpam '
fi
if [ "$ldap" = "0" ]; then
	echo '#undef WITH_LDAP' >> config.h
else
	if ! echo '#include <ldap.h>' | $CC -E - >/dev/null 2>/dev/null; then
		echo 'Cannot find libldap development libraries, aborting. (Install libldap2-dev?)'
		exit 1
	fi
	echo '#define WITH_LDAP' >> config.h
	authobjs=$authobjs'auth_ldap.o '
	authlibs=$authlibs'-lldap '
fi
echo AUTH_OBJS="$authobjs" >> Makefile.settings
echo EFLAGS+="$authlibs" >> Makefile.settings

if [ "$strip" = "0" ]; then
	echo "STRIP=\# skip strip" >> Makefile.settings;
else
	if [ "$debug" = "1" ]; then
		echo
		echo 'Stripping binaries does not make sense when debugging. Stripping disabled.'
		echo 'STRIP=\# skip strip' >> Makefile.settings
		strip=0;
	elif [ -n "$STRIP" ]; then
		echo "STRIP=$STRIP" >> Makefile.settings;
	elif type strip > /dev/null 2> /dev/null; then
		echo "STRIP=strip" >> Makefile.settings;
	else
		echo
		echo 'No strip utility found, cannot remove unnecessary parts from executable.'
		echo 'STRIP=\# skip strip' >> Makefile.settings
		strip=0;
	fi;
fi

if [ ! "$systemd" = "0" ]; then
    if ! $PKG_CONFIG --exists systemd ; then
        if [ -n "$systemdsystemunitdir" ] || [ $systemd -eq 1 ]; then
            echo "systemd requested but not found"
            exit 1
        else
            systemd=0
        fi
    fi
fi

pkgconf_systemd_var() {
    # First try deprecated variable, use newer variable if not found
    if $PKG_CONFIG --print-variables systemd | grep -q "$1" ; then
        $PKG_CONFIG --variable="$1" systemd
    else
        $PKG_CONFIG --variable="$2" systemd
    fi
}

if [ "$systemd" = "1" ]; then
	if [ -z "$systemdsystemunitdir" ]; then
		systemdsystemunitdir=$(pkgconf_systemd_var systemdsystemunitdir systemd_system_unit_dir)
	fi
    if [ -z "$sysusersdir" ] ; then
        sysusersdir=$(pkgconf_systemd_var sysusersdir sysusers_dir)
    fi

	echo "SYSTEMDSYSTEMUNITDIR=$systemdsystemunitdir" >> Makefile.settings
    echo "SYSUSERSDIR=$sysusersdir" >> Makefile.settings
fi

if [ "$gcov" = "1" ]; then
	echo "CFLAGS+=--coverage" >> Makefile.settings
	echo "EFLAGS+=--coverage" >> Makefile.settings
fi

if [ "$plugins" = "0" ]; then
	plugindir=""
	echo '#undef WITH_PLUGINS' >> config.h
else
	echo '#define WITH_PLUGINS' >> config.h
fi

if [ "$otr" = "auto" ]; then
	! $PKG_CONFIG --exists libotr
	otr=$?
fi

if [ "$otr" != "0" ] && ! $PKG_CONFIG --atleast-version=4.0 --print-errors libotr; then
	exit 1
fi

if [ "$otr" = "1" ]; then
	# BI == built-in
	echo '#define OTR_BI' >> config.h
	# shellcheck disable=SC2129
	echo "EFLAGS+=$($PKG_CONFIG --libs libotr) $(libgcrypt-config --libs)" >> Makefile.settings
	echo "CFLAGS+=$($PKG_CONFIG --cflags libotr) $(libgcrypt-config --cflags)" >> Makefile.settings
	echo 'OTR_BI=otr.o' >> Makefile.settings
elif [ "$otr" = "plugin" ]; then
	# for some mysterious reason beyond the comprehension of my mortal mind,
	# the libgcrypt flags aren't needed when building as plugin. add them anyway.
	echo '#define OTR_PI' >> config.h
	# shellcheck disable=SC2129
	echo "OTRFLAGS=$($PKG_CONFIG --libs libotr) $(libgcrypt-config --libs)" >> Makefile.settings
	echo "CFLAGS+=$($PKG_CONFIG --cflags libotr) $(libgcrypt-config --cflags)" >> Makefile.settings
	echo 'OTR_PI=otr.so' >> Makefile.settings
fi

if [ -z "$PYTHON" ]; then
	for pp in python python3 python2; do
		if which $pp > /dev/null; then
			PYTHON=$pp
			break
		fi
	done
fi

if [ "$doc" = "1" ]; then
	# check this here just in case someone tries to install it in python2.4...
	if [ ! -e "$srcdir"/doc/user-guide/help.txt ] && ! $PYTHON -m xml.etree.ElementTree > /dev/null 2>&1; then
		echo
		echo 'ERROR: Python (>=2.5 or 3.x) is required to generate docs'
		echo "(Use the PYTHON environment variable if it's in a weird location)"
		exit 1
	fi
	echo "DOC=1" >> Makefile.settings
	echo "PYTHON=$PYTHON" >> Makefile.settings
fi

get_version

if [ ! "$BITLBEE_VERSION" = "$REAL_BITLBEE_VERSION" ]; then
	echo "Spoofing version number: $BITLBEE_VERSION"
	echo "#undef BITLBEE_VERSION" >> config.h
	echo "#define BITLBEE_VERSION '$BITLBEE_VERSION'" >> config.h
	echo
fi

if ! make helloworld > /dev/null 2>&1; then
	echo "WARNING: Your version of make (BSD make?) does not support BitlBee's makefiles."
	echo "BitlBee needs GNU make to build properly. On most systems GNU make is available"
	echo "under the name 'gmake'."
	echo
	if gmake helloworld > /dev/null 2>&1; then
		echo "gmake seems to be available on your machine, great."
		echo
	else
		echo "gmake is not installed (or not working). Please try to install it."
		echo
	fi
fi

pkgconfiglibs=''
case "$arch" in
CYGWIN* )
	pkgconfiglibs="-L${libdir} -lbitlbee -no-undefined"
esac

cat <<EOF >bitlbee.pc
prefix=$prefix
includedir=$includedir
plugindir=$plugindir
libdir=$libdir
datadir=$datadir

Name: bitlbee
Description: IRC to IM gateway
Requires: glib-2.0
Version: $BITLBEE_VERSION
Libs: $pkgconfiglibs
Cflags: -I\${includedir}

EOF

protocols=''
protoobjs=''

if [ "$purple" = "0" ]; then
	echo '#undef WITH_PURPLE' >> config.h
else
	if ! $PKG_CONFIG purple; then
		echo
		echo 'Cannot find libpurple development libraries, aborting. (Install libpurple-dev?)'
		exit 1
	fi
	echo '#define WITH_PURPLE' >> config.h
	cat<<EOF >>Makefile.settings
EFLAGS += $($PKG_CONFIG purple --libs)
PURPLE_CFLAGS += $($PKG_CONFIG purple --cflags)
EOF
	protocols=$protocols'purple '
	protoobjs=$protoobjs'purple_mod.o '

	# only disable these if the user didn't enable them explicitly
	[ "$jabber" = "default-on" ] && jabber=0

	echo '#undef PACKAGE' >> config.h
	echo '#define PACKAGE "BitlBee-LIBPURPLE"' >> config.h
	
	if [ "$events" = "libevent" ]; then
		echo 'Warning: Some libpurple modules (including msn-pecan) do their event handling'
		echo 'outside libpurple, talking to GLib directly. At least for now the combination'
		echo 'libpurple + libevent is *not* recommended!'
		echo
	fi
fi

case "$CC" in
*gcc* )
	echo CFLAGS+=-MMD -MF .depend/\$@.d >> Makefile.settings
	for i in . lib tests protocols protocols/*/; do
		mkdir -p "$i"/.depend
	done
esac

if [ "$jabber" = "0" ]; then
	echo '#undef WITH_JABBER' >> config.h
else
	echo '#define WITH_JABBER' >> config.h
	protocols=$protocols'jabber '
	protoobjs=$protoobjs'jabber_mod.o '
fi

if [ "$twitter" = "0" ]; then
	echo '#undef WITH_TWITTER' >> config.h
else
	echo '#define WITH_TWITTER' >> config.h
	protocols=$protocols'twitter '
	protoobjs=$protoobjs'twitter_mod.o '
fi

if [ "$protocols" = "PROTOCOLS = " ]; then
	echo "Warning: You haven't selected any communication protocol to compile!"
	echo "         BitlBee will run, but you will be unable to connect to IM servers!"
fi

echo "PROTOCOLS = $protocols" >> Makefile.settings
echo "PROTOOBJS = $protoobjs" >> Makefile.settings

echo Architecture: "$arch"
case "$arch" in
Linux )
;;
GNU/* )
;;
*BSD )
;;
Darwin )
	echo 'STRIP=\# skip strip' >> Makefile.settings
;;
IRIX )
;;
SunOS )
	echo 'EFLAGS+=-lresolv -lnsl -lsocket' >> Makefile.settings
	echo 'STRIP=\# skip strip' >> Makefile.settings
	echo '#define NO_FD_PASSING' >> config.h
	if [ "$arch_rel" = "5.10" ]; then
		echo '#define NO_STRCASESTR' >> config.h
	fi
;;
AIX )
	echo 'EFLAGS+=-Wl,-brtl' >> Makefile.settings
;;
CYGWIN* )
	echo 'EFLAGS+=-Wl,--export-all,--out-implib,libbitlbee.dll.a' >> Makefile.settings
	echo 'IMPLIB=libbitlbee.dll.a' >> Makefile.settings
;;
Windows )
	echo 'Native windows compilation is not supported anymore, use cygwin instead.'
;;
* )
	echo 'We haven'\''t tested BitlBee on many platforms yet, yours is untested. YMMV.'
	echo 'Please report any problems at http://bugs.bitlbee.org/.'
;;
esac

if [ -n "$target" ]; then
	echo "Cross-compiling for: $target"
fi

echo
echo 'Configuration done:'

if [ "$debug" = "1" ]; then
	echo '  Debugging enabled.'
else
	echo '  Debugging disabled.'
fi

if [ "$asan" = "1" ]; then
	echo '  AddressSanitizer (ASAN) enabled.'
else
	echo '  AddressSanitizer (ASAN) disabled.'
fi

if [ "$pie" = "1" ]; then
	echo '  Building PIE executable'
else
	echo '  Building non-PIE executable'
fi

if [ "$strip" = "1" ]; then
	echo '  Binary stripping enabled.'
else
	echo '  Binary stripping disabled.'
fi

if [ "$otr" = "1" ]; then
	echo '  Off-the-Record (OTR) Messaging enabled.'
elif [ "$otr" = "plugin" ]; then
	echo '  Off-the-Record (OTR) Messaging enabled (as a plugin).'
else
	echo '  Off-the-Record (OTR) Messaging disabled.'
fi

if [ "$systemd" = "1" ]; then
	echo '  systemd enabled.'
else
	echo '  systemd disabled.'
fi

echo '  Using python: '$PYTHON

if [ "$external_json_parser" = "1" ]; then
    echo '  Using system JSON parser.'
else
    echo '  Using bundled JSON parser.'
fi

echo '  Using event handler: '$events
echo '  Using SSL library: '$ssl
#echo '  Building with these storage backends: '$STORAGES

if [ -n "$protocols" ]; then
	echo '  Building with these protocols:' "$protocols""$protocols_mods"
	case "$protocols" in
	*purple*)
		echo "    Note that BitlBee-libpurple is supported on a best-effort basis. It's"
		echo "    not *fully* compatible with normal BitlBee. Don't use it unless you"
		echo "    absolutely need it (i.e. support for a certain protocol or feature)."
	esac
else
	echo '  Building without IM-protocol support. We wish you a lot of fun...'
fi
