#!/bin/sh
# Configuration script for mxallowd
# (c) 2007-2008 Michael Stapelberg

_call="$*"
INCLUDE_PATHS="/usr/include /usr/local/include"
LIBRARY_PATHS="/usr/lib /usr/local/lib"
# Temporary variable which will be set after need_file() succeeds
DIRNAME=""

show_help() {
	cat << EOF
Usage: $0 [OPTIONS]

Options:
  --enable-debug	Enable compiling debug-symbols 		[disable debug]
  --dont-optimize	Disable optimization (-O2)		[optimize]
  --broken-unbind	Enable when using Kernel >=2.6.23	[disabled]
  --disable-ipv6	Don't compile IPv6-support		[enable]
  --prefix=[dir]	Install to dir/{sbin,share}		[/usr/local]
EOF
	exit 0
}

# Checks if the file is in one of the given paths and sets its path in $DIRNAME
need_file() {
	for i in $1; do
		[ -f "${i}/${2}" ] && { DIRNAME=$(dirname "${i}/${2}"); return 0; }
	done
	return 1
}

# Defaults
debug="no"
optimize="yes"
broken_unbind="no"
disable_ipv6="no"
prefix="/usr/local"

# Parse all options
for ac_option do
	case "$ac_option" in
	--help|-help|-h)
		show_help;;
	--enable-debug)
		debug="yes";;
	--dont-optimize)
		optimize="no";;
	--broken-unbind)
		broken_unbind="yes";;
	--disable-ipv6)
		disable_ipv6="yes";;
	--prefix=*)
		prefix=$(echo $ac_option | cut -d '=' -f 2);;
	*)
		echo "Unknown option: $ac_option"
		exit 1;;
	esac
done

INSTALL=$(which install) || {
	echo "ERROR: \"install\" not found!"
	exit 1
}

echo "Searching libnetfilter_queue.h..."
need_file "${INCLUDE_PATHS}" "libnetfilter_queue.h" ||
need_file "${INCLUDE_PATHS}" "libnetfilter_queue/libnetfilter_queue.h"
if [ $? -eq 1 ]; then
	echo -e "\nWARNING: libnetfilter_queue.h was not found. Please install package libnetfilter-queue-dev
or similar (depends on your distribution)."
fi
echo "LIBPATH=\"${DIRNAME}\"" > Makefile

need_file "${LIBRARY_PATHS}" "libnetfilter_queue.a"

if [ "$?" -eq 1 ]; then
	echo "libnetfilter_queue was not found. Please install package libnetfilter-queue1 or similar (depends on your distribution)."
	exit 1
fi

if [ "$debug" = "yes" -a "$optimize" = "yes" ]; then
	echo "WARNING: You cannot use debugging AND optimization, turning off optimization..."
	optimize="no"
fi
echo "Enable debugging symbols... $debug"
echo "Optimization (-O2 -s)... $optimize"
echo "Broken unbind... $broken_unbind"
echo "Disable IPv6... $disable_ipv6"

if [ "$broken_unbind" = "yes" ]; then
	unb="-DBROKEN_UNBIND"
else
	unb=""
fi

if [ "$debug" = "yes" ]; then
	echo "CC_FLAGS=-g $unb" >> Makefile
else
	if [ "$optimize" = "yes" ]; then
		echo "CC_FLAGS=-O2 -s $unb" >> Makefile
	else
		echo "CC_FLAGS=$unb" >> Makefile
	fi
fi

if [ "${disable_ipv6}" = "no" ]; then
	echo "V6DEF=-DIPV6" >> Makefile
else
	echo "V6DEF=" >> Makefile
fi

echo "LIBS=-lnetfilter_queue -lpthread" >> Makefile
echo "PREFIX=${prefix}" >> Makefile

echo "QUEUEDEF=-DNFQUEUE
CC=${CC:=cc}
INSTALL=${INSTALL}" >> Makefile
cat Makefile.in >> Makefile
