#!/bin/sh

if [ "$1" = "" ] || [ "$2" = "" ]; then
    echo "Usage: $0 <version> <build>"
    exit 1
fi

version=$1
build=$2

fwdir="/Library/Frameworks/UIM.framework"
prefix="/Library/Frameworks/UIM.framework/Versions/${version}"
top=`pwd`
dest="${top}/../../Package/dest"

rm -rf ${dest}${fwdir}

cp -fv ../Info.plist.in Info.plist
cp -fv ../version.plist.in version.plist
perl -pi -e "s|\@VERSION\@|${version}|" *.plist
perl -pi -e "s|\@BUILD\@|${build}|" *.plist

perl -pi -e 's|SUBDIRS =.*|SUBDIRS = scm uim|' Makefile.in
perl -pi -e 's|\texamples pixmaps||' Makefile.in

PATH="${prefix}/bin:/Library/Anthy/bin:/Library/PRIME/bin:/Library/M17NLib/bin:/bin:/usr/bin"

export MACOSX_DEPLOYMENT_TARGET="10.3"

LDFLAGS="-L/opt/macuim/lib -L/Library/M17NLib/lib -L/Library/Anthy/lib" \
CPPFLAGS="-I/opt/macuim/include -I/Library/M17NLib/include -I/Library/Anthy/include" \
CFLAGS="-I/opt/macuim/include -I/Library/M17NLib/include -I/Library/Anthy/include" \
PKG_CONFIG="/opt/macuim/bin/pkg-config" \
PKG_CONFIG_PATH="/Library/PRIME/lib/pkgconfig:/Library/Anthy/lib/pkgconfig:/Library/M17NLib/lib/pkgconfig" \
./configure --prefix=${prefix} --exec-prefix=${prefix} --enable-debug \
--without-gtk2 --disable-fep --disable-applet \
--with-x || exit 1

#mkdir -p ${dest}${prefix}/lib

cd replace
make -w || exit 1
cd ../

cd uim
make -w pkglibdir=${prefix}/pkglib || exit 1
cd ../

gcc -dynamiclib -undefined dynamic_lookup \
-o uim/.libs/UIM \
uim/.libs/libuim_la*.o uim/.libs/libuim_custom_la*.o replace/.libs/libreplace.a \
-L/opt/macuim/lib -liconv -ldl -lintl \
-install_name /Library/Frameworks/UIM.framework/Versions/${version}/UIM \
-compatibility_version ${version} -current_version ${version} || exit 1

cd uim

perl -pi -e "s|^library_names=.*$|library_names='UIM'|" libuim.la
perl -pi -e "s|^library_names=.*$|library_names='UIM'|" libuim-custom.la

make -w pkglibdir=${prefix}/pkglib || exit 1

cd ..

make -w DESTDIR=${dest} pkglibdir=${prefix}/pkglib \
  install || exit 1

cd xim
make -w || exit 1
make -w DESTDIR=${dest} install || exit 1
cd ..

cd ${dest}/${prefix}
mv include/uim Headers
ln -sv lib/UIM .
rm -rf include share/applications bin/uim-sh lib/libuim* 

mkdir Resources
install -c -m 644 ${top}/Info.plist Resources
install -c -m 644 ${top}/version.plist Resources

cd ..
ln -sv ${version} Current

cd ..
ln -sv Versions/Current/UIM .
ln -sv Versions/Current/Headers .
ln -sv Versions/Current/Resources .
