#!/bin/bash -eu

if [ -f meson.build ]; then
	argv=()
	argx=(
		--prefix="/usr"             \
		--sysconfdir="/etc"         \
		--localstatedir="/var"      \
		--mandir="/usr/share/man"   \
		--infodir="/usr/share/info" \
		--backend=ninja		        \
		--optimization=2            \
		--default-library=shared	\
		-Ddebug=false               \
	)
	for i in "${argx[@]}"; do
		argv[${#argv[@]}]="$i"
	done
	# be verbose :)
	echo "meson setup build"
	for i in "$@" "${argv[@]}"; do
		echo -e "\t$i"
	done
	
	meson setup build \
		"$@" "${argv[@]}"
	meson compile \
		-C build
fi

if [ -f CMakeLists.txt ]; then
	argv=()
	argx=(
        -GNinja \
	    -DCMAKE_BUILD_TYPE=Release \
		-DCMAKE_INSTALL_PREFIX="/usr" \
	)
	for i in "${argx[@]}"; do
		argv[${#argv[@]}]="$i"
	done
	# be verbose :)
	echo "cmake"
	for i in "$@" "${argv[@]}"; do
		echo -e "\t$i"
	done

	mkdir -p build
	cd build
	cmake \
		"$@" "${argv[@]}" \
		..
fi

if [ -f "configure" -a ! -f CMakeLists.txt -a ! -f meson.build ]; then
	ub_configure "$@"
else
	if [ -f "autogen.sh" -a ! -f CMakeLists.txt -a ! -f meson.build ]; then
		NOCONFIGURE=1 ./autogen.sh && ub_configure "$@"
	fi
	if [ ! -f "configure" -a ! -f "autogen.sh" -a ! -f CMakeLists.txt -a ! -f meson.build ]; then
	    if [ -f configure.ac -o -f configure.in ]; then
		    autoreconf -vif && ub_configure "$@"
		fi
	fi
fi

if [ -f pyproject.toml ]; then
    python3 -m build --wheel --no-isolation
    exit 0
fi

if [ -f Makefile.PL ]; then
	perl Makefile.PL "$@"
fi

if [ -f Build.PL ]; then
	perl Build.PL -no-packlist "$@"
	exec ./Build
fi

exec ub_make
