#!/bin/sh
#
# Copyright (C) 2024, 2025 Mikulas Patocka
#
# This file is part of Ajla.
#
# Ajla is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# Ajla is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# Ajla. If not, see <https://www.gnu.org/licenses/>.

./clean
set -e

./autogen.sh

if [ -z "${CFLAGS+set}" ]; then
	CFLAGS="-O2 -g -Wall -Wextra -Wmissing-prototypes -Wno-strict-aliasing -fdiagnostics-color=always"
#	"-fdiagnostics-color=always"
#	CFLAGS="$CFLAGS -std=c89"
	if [ -n "$CF" ]; then
		CFLAGS="$CFLAGS $CF"
	fi
	if [ "`uname -s`" = NetBSD ]; then
		CFLAGS="$CFLAGS -I/usr/pkg/include -L/usr/pkg/lib"
	fi
	export CFLAGS
fi
ARGS=""
./configure "$ARGS" "$@"
if which gmake >/dev/null 2>/dev/null; then
	MAK=gmake
else
	MAK=make
fi
if [ -z "$MAKEFLAGS" ]; then
	N=`ls -1d /sys/devices/system/cpu/cpu[0-9]* 2>/dev/null|wc -l|sed 's/ //g'`
	if test "$N" = 0 -o "$N" = ""; then
		N="`grep -c ^processor /proc/cpuinfo 2>/dev/null || true`"
	fi
	if test "$N" = 0 -o "$N" = ""; then
		N="`sysctl hw.activecpu 2>/dev/null|sed 's/[^0-9]*//'`"
	fi
	if test "$N" = 0 -o "$N" = ""; then
		N="`sysctl hw.ncpu 2>/dev/null|sed 's/[^0-9]*//'`"
	fi
	if test "$N" = 0 -o "$N" = ""; then
		N="`sysinfo 2>/dev/null|grep ^CPU|wc -l|sed 's/[^0-9]*//'`"
	fi
	if test "$N" = 0 -o "$N" = ""; then
		if test "`uname -s`" = HP-UX; then
			N=4
		fi
	fi
	if test "$N" = 0 -o "$N" = ""; then
		N=1
	fi
	if test "$N" != 1; then
		MAKEFLAGS="-j $N"
		export MAKEFLAGS
	fi
fi
"$MAK"
