#!/bin/sh

prefix="/tmp/prefix"

opt_prefix=""
if [ -n "$prefix" ]; then
	export LD_LIBRARY_PATH="$prefix"/lib
	export PKG_CONFIG_PATH="$prefix"/lib/pkgconfig
	opt_prefix="--prefix=$prefix"
fi


reposes="
libosmocore
libosmo-abis
libosmo-netif
libosmo-sccp
openggsn
libsmpp34
openbsc/openbsc
osmo-pcu
"

do_clean="1"

if [ "$1" = "noclean" ]; then
	do_clean="0"
elif [ -n "$1" ]; then
	echo "unknown argument: '$1'"
	echo "
Args:
  noclean   skip the 'make clean' step
"
	exit 1
fi

set -x -e
base="$PWD"
builddir="build-2G"
for r in $reposes; do
	echo "======================= $r ======================"

	cd "$base/$r"
	if [ "$do_clean" = "1" ]; then
		set +e
		make distclean
		rm -rf "$builddir"
		set -e
		autoreconf -fi
	fi

	mkdir -p "$builddir"
	cd "$builddir"

	if [ "$do_clean" = "1" ]; then
		opt_enable=""
		if [ "$r" = 'openbsc/openbsc' ]; then
			opt_enable="--enable-smpp --enable-osmo-bsc --enable-nat"
		fi

		../configure "$opt_prefix" $opt_enable
		set +e
		make clean
		set -e
	fi

	make -j CFLAGS+="-fsanitize=address -fsanitize=undefined" CXXFLAGS+="-fsanitize=address -fsanitize=undefined" \
	  || make CFLAGS+="-fsanitize=address -fsanitize=undefined" CXXFLAGS+="-fsanitize=address -fsanitize=undefined"
	if [ "$r" != asn1c ]; then
		make check CFLAGS+="-fsanitize=address -fsanitize=undefined" CXXFLAGS+="-fsanitize=address -fsanitize=undefined"
	fi
	make install CFLAGS+="-fsanitize=address -fsanitize=undefined" CXXFLAGS+="-fsanitize=address -fsanitize=undefined"
done
