#!/bin/sh

# build the custom libiconv from source

echo " --- $0 ---"

PRGLOC="`cd $(dirname $0)/../..;pwd`"
SRCLOC="${PRGLOC}/libiconv-1.12"
OBJLOC="${PRGLOC}/build_win/libiconv.build"
MODLOC="${PRGLOC}/project/source/iconv_custom"
DISTFILE=${PRGLOC}/project/packages/libiconv-1.12.tar.gz

GPERF="${PRGLOC}/project/make_win/gperf.exe"

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}
echo ${GPERF}

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

if [ ! -d ${SRCLOC} ]; then
	echo "extracting source file ..."
	cd ${PRGLOC}/
	tar xzf ${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 "lib/macromanfull.h"
patch4pregex "lib/cp1252full.h"
patch4pregex "lib/converters.h"
patch4pregex "lib/encodings.def"
patch4pregex "lib/flags.h"

# we need to patch more on win32
patch4pregex "windows/windres-options"
patch4pregex "lib/aliases.gperf"
patch4pregex "lib/aliases.h"
patch4pregex "lib/canonical.h"
patch4pregex "lib/canonical_local.h"

${SRCLOC}/configure --build=i686-pc-mingw32 \
                    --enable-static=yes --enable-shared=no \
                    --enable-relocatable --enable-extra-encodings && \
make

mv -v lib/.libs/libiconv.a ${OBJLOC}/

echo "build complete"
ls -al ${OBJLOC}/include/iconv.h
nm -a ${OBJLOC}/libiconv.a |grep full
${OBJLOC}/src/iconv_no_i18n -l|grep FULL

