#!/bin/bash

# build the custom pcre from source

echo " --- $0 ---"

PRGLOC="`cd $(dirname $0)/../..;pwd`"
SRCLOC="${PRGLOC}/pcre-7.8"
OBJLOC="${PRGLOC}/build_mac/pcre.build"
MODLOC="${PRGLOC}/project/source/pcre_custom"
DISTFILE="${PRGLOC}/project/packages/pcre-7.8.tar.bz2"

patch4pregex() {
	test $# -ne 1 && echo "patch4pregex <file>" && return
	
	if [ -a "${SRCLOC}/${1}" ]; then	
		# backup original file
		mv -v "${SRCLOC}/${1}" "${SRCLOC}/${1}".dist
		echo "-> backed up  ${SRCLOC}/${1}"
	fi
	
	cp -i "${MODLOC}/${1}" "${SRCLOC}/${1}"
	echo " patched  ${SRCLOC}/${1}"	
	
	return
}

echo "${PRGLOC}"
echo "${SRCLOC}"
echo "${OBJLOC}"
echo "${DISTFILE}"

if [ -f "${OBJLOC}/libpcre.a" ]; then
	echo "already built, exiting ..."
	exit
fi

if [ ! -d "${SRCLOC}" ]; then
	echo "extracting source file ..."
	cd "${PRGLOC}"
	tar xjf "${DISTFILE}"
fi

if [ ! -d "${OBJLOC}" ]; then
	echo "setting up build location ..."
	mkdir -pv "${OBJLOC}"
fi

cd "${OBJLOC}"

if [ -f Makefile ]; then
	make distclean
fi

patch4pregex "pcre_compile.c"

env  CFLAGS="-arch ppc -g -Os -pipe " \
    CCFLAGS="-arch ppc -g -Os -pipe " \
   CXXFLAGS="-arch ppc -g -Os -pipe " \
    LDFLAGS="-arch ppc  " \
"${SRCLOC}/configure"  \
			 --enable-static=yes --enable-shared=no \
			 --enable-newline-is-cr --enable-bsr-anycrlf \
             --enable-utf8 --enable-unicode-properties && \
make

mv -v .libs bin-ppc
make distclean

env  CFLAGS="-arch i386 -g -Os -pipe " \
    CCFLAGS="-arch i386 -g -Os -pipe " \
   CXXFLAGS="-arch i386 -g -Os -pipe " \
    LDFLAGS="-arch i386 " \
"${SRCLOC}/configure"  \
			 --enable-static=yes --enable-shared=no \
			 --enable-newline-is-cr --enable-bsr-anycrlf \
             --enable-utf8 --enable-unicode-properties &&  \
make

mv -v .libs bin-i386

echo "creating univeral binary ..."
lipo -create bin-i386/libpcre.a bin-ppc/libpcre.a -o libpcre.a

echo "build complete"
ls -al "${OBJLOC}/pcre.h"
ls -al "${OBJLOC}/libpcre.a"
file   "${OBJLOC}/libpcre.a"



