#!/bin/bash -eu

. /usr/lib/uhubuild/common

UB_CFLAGS="-O2 -m64 -mtune=generic ${CFLAGS:-}"

export CFLAGS="$UB_CFLAGS"

argv=()
argx=(
	--prefix="/usr"             \
	--sysconfdir="/etc"         \
	--localstatedir="/var"      \
	--mandir="/usr/share/man"   \
	--infodir="/usr/share/info" \
)

shopt -s extglob

configure="${UB_CONFIGURE_SCRIPT:-${UB_CONFIGURE_DIR:-.}/configure}"

if grep -q enable-shared "$configure"; then
	argx[${#argx[@]}]="--enable-shared"
fi

if [ -z "${UB_CONFIGURE_NO_DISABLE_STATIC:-}" ]; then
	if grep -q disable-static || grep -q enable-static "$configure"; then
		argx[${#argx[@]}]="--disable-static"
	fi
fi

# add --disable-schemas-install if the configure script supports it
if grep -q disable-schemas-install "$configure"; then
		argx[${#argx[@]}]="--disable-schemas-install"
fi
# add --disable-scrollkeeper if the configure script supports it
if grep -q disable-scrollkeeper "$configure"; then
		argx[${#argx[@]}]="--disable-scrollkeeper"
fi

# libexecdir (/usr/libexec), sharedstatedir (/usr/com),
for i in "${argx[@]}"; do
	pattern="$i"
	pattern="${pattern/%=*/=*}"
	pattern="${pattern/#--@(en|dis)able-/--@(en|dis)able-}"
	pattern="${pattern/#--with?(out)-/--with?(out)-}"
	overridden="no"
	for arg in "$@"; do
		if [ "$i" == "$arg" ]; then
			warn "fölöslegesen megadott paraméter: [$arg]"
		fi
		case "$arg" in
			$pattern)
				overridden="yes"
				;;
		esac
	done
	if [ "$overridden" == "no" ]; then
		argv[${#argv[@]}]="$i"
	fi
done

# be verbose :)
echo "$configure"
for i in "$@" "${argv[@]}"; do
	echo -e "\t$i"
done
"$configure" "$@" "${argv[@]}"
