#!/bin/sh

# We build where we are
SDK_BUILD_BASE=$(pwd -P)/output

if [ -z "$SDK_SRC_BASE" ]
then
echo Script variable SDK_SRC_BASE must be set in the calling \'configure\' script,
echo to the root location of the sources, typically with such a pattern:
echo 'SDK_SRC_BASE="$(cd "$(dirname "$0")"; pwd -P)"' 
echo "(see 'configure.template' from the argeo-build directory)"
echo In order to build Argeo Build itself, explicitly set SDK_SRC_BASE as an environment variable
exit 1
fi

SDK_MK=$SDK_SRC_BASE/sdk.mk

if [ -f "$SDK_MK" ]; 
then
echo "File $SDK_MK already exists. Remove it in order to configure a new build location:"
echo "rm $SDK_MK"
exit 1

else

if [ -z "$JAVA_HOME" ]
then
JAVA_HOME=$(dirname $(dirname $(readlink -f $(which java))))
echo "Environment variable JAVA_HOME not set, using $JAVA_HOME of $(which java)"
fi

# Create build directory, so that it can be used right away
# and we check whether we have the rights
mkdir -p $SDK_BUILD_BASE
if [ ! -d "$SDK_BUILD_BASE" ];
then
echo "Cannot create $SDK_BUILD_BASE, SDK configuration has failed."
exit 2
fi

# Generate sdk.mk
cat > "$SDK_MK" <<EOF
SDK_SRC_BASE := $SDK_SRC_BASE
SDK_BUILD_BASE := $SDK_BUILD_BASE
JAVA_HOME := $JAVA_HOME

-include branch.mk
-include sdk/branches/\$(BRANCH).bnd
EOF

# Add standard GNU paths
for i in "$@"; do
	case $i in
	--prefix=*)
		echo "prefix := ${i#*=}" >> "$SDK_MK"
      	shift
      	;;
	--sysconfdir=*)
		echo "sysconfdir := ${i#*=}" >> "$SDK_MK"
      	shift
      	;;
	--localstatedir=*)
		echo "localstatedir := ${i#*=}" >> "$SDK_MK"
      	shift
      	;;
  esac
done

# Even when building in MSYS (that is, with proper '/' paths)
# we still need at some places the Windows '\' path to output
if command -v cygpath 2>&1 >/dev/null
then
echo "export SDK_BUILD_BASE_WIN=$(cygpath -w "$SDK_BUILD_BASE")" >> "$SDK_MK"
fi

echo SDK was configured.
echo "JAVA_HOME        : $JAVA_HOME"
echo "Base for sources : $SDK_SRC_BASE"
echo "Base for builds  : $SDK_BUILD_BASE"
fi
