#!/bin/bash

# Note : this is a build script, not an install script, for cross-compilation.
# So no need to run as root.


# load config.mk
config_file=$(cat config.mk)


# alter platform
target="include \$(TOP)/config/platform/darwin-universal"
rep="include \$(TOP)/config/platform/mingw"

config_file=${config_file/"$target"/"$rep"}


# alter site: coming from EITHER standard OR beta-install
target="include \$(TOP)/config/site/standard"
rep="include \$(TOP)/config/site/windows-release"
config_file=${config_file/"$target"/"$rep"}
target="include \$(TOP)/config/site/beta-install"
rep="include \$(TOP)/config/site/windows-release"
config_file=${config_file/"$target"/"$rep"}


# find out where the dlls are, and save that folder

# this is a lot easier said than done
# we need to go through the directories in the library search path of the cross-compiler,
# and if libpcre.la is there, we can try to extract its dlname= variable.
# note, this will only work for this particular crosscompiler executable!

paths=$(i586-mingw32msvc-gcc --print-search-dirs | grep "programs: =")
paths=${paths/"programs: ="/" "}
paths=$(echo $paths | tr ":" " ")

for i in $paths
do
	echo "looking in ${i}libpcre.la ......"
	if [ -f "${i}libpcre.la" ] ; then
		echo "found!"
		LIBPRCE_LA=$(cat "${i}libpcre.la")
		LIBPCRE_LA_FOUND_IN=$i 
		break
	fi
done

if [ -n "$LIBPCRE_LA_FOUND_IN" ] ; then 
	echo "-----------> $LIBPCRE_LA_FOUND_IN" 
	
	DLNAME_LINE=$(grep "^dlname='" < "${LIBPCRE_LA_FOUND_IN}libpcre.la")
	echo "dlname line == $DLNAME_LINE"
	DLNAME_LINE=$(echo $DLNAME_LINE | tr -d "'")
	dlname=${DLNAME_LINE/"dlname="/""}
	
	
	echo "$LIBPCRE_LA_FOUND_IN$dlname"
	deduced_path=$(dirname $LIBPCRE_LA_FOUND_IN$dlname)
	deduced_path=$(cd "$deduced_path" && pwd)
	
	echo "Deduced path to DLLS as $deduced_path..... "
	
	# if either (LIBPCRE_DLL_PATH and LIBGLIB_DLL_PATH) or LIB_DLL_PATH are set
	# in the config file, our guess for the dll location will be overridden,
	# because we put it at the beginning of the config.mk file.
	
	prepend=$( cat <<HERE

LIB_DLL_PATH=$deduced_path


HERE
	)
	config_file="$prepend
$config_file" 

else 
	echo "Couldn't find libpcre.la!! If you did not specify dll paths in your config.mk, then make will fail."
fi



# save config.mk
rm -f config.mk.bak
mv config.mk config.mk.bak
echo "$config_file" > config.mk

if [ -f config.mk ] ; then echo "config.mk exists" ; else echo "config.mk doesn't exist" ; exit ; fi
if [ -f config.mk.bak ] ; then echo "config.mk.bak exists" ; else echo "config.mk.bak doesn't exist" ; exit ; fi

# make cwb

make clean
make depend
make cl
make mingw-libgnurx-2.5.1
make utils
make cqp

# and finally....

make release

# restore original state of config file (so subversion doesn't get confused if this directory is under version control)
rm config.mk
mv config.mk.bak config.mk
