#! /bin/sh

##  Win32 cross-compilation for libpipi -- Sam Hocevar <sam@zoy.org>
##  $Id$

set -x
set -e

# Clean up our working directory
PROJECT="ThePimp"
SRCDIR="`pwd`"
VERSION="`sed -ne 's/^AC_INIT(.*, \(.*\)).*/\1/p' configure.ac`"
if [ -f .git/svn/trunk/unhandled.log ]; then
  VERSION="${VERSION}-`grep '^r' .git/svn/trunk/unhandled.log | tail -n 1`"
elif [ -f .svn/entries ]; then
  VERSION="${VERSION}-r`head -n 4 .svn/entries | tail -n 1`"
fi
DIRNAME="${PROJECT}-${VERSION}"
INSTALLDIR="`pwd`/${DIRNAME}"
BUILDDIR="${INSTALLDIR}/build"
rm -Rf "${INSTALLDIR}"
rm -f "${INSTALLDIR}.zip"
mkdir "${INSTALLDIR}"
mkdir "${BUILDDIR}"

make distclean || true

cd "${BUILDDIR}"
# Build for win32
"${SRCDIR}/configure" --host=i586-mingw32msvc --prefix=/ --bindir=/bin --libdir=/lib CPPFLAGS="-I${SRCDIR}/win32/gdiplus/include" LIBS="-L${SRCDIR}/win32/gdiplus/lib" "$@"
make pkglibdir=/lib pkgdatadir=/data bindir=/bin
# Install into our private directory
make install DESTDIR="${INSTALLDIR}" pkglibdir=/lib/ pkgdatadir=/ bindir=/bin/
# Clean up
cd "${SRCDIR}"
rm -Rf "${BUILDDIR}"

#i586-mingw32msvc-strip "${INSTALLDIR}/bin/"*.exe || true
#i586-mingw32msvc-strip "${INSTALLDIR}/lib/"*.dll || true

# Install pipi.exe
echo 'int main(int argc, char *argv[], char *envp[]) { argv[0] = ".\\bin\\pipi.exe"; execve(argv[0], argv, envp); return 0; }' > run.c
i586-mingw32msvc-gcc run.c -mwindows -o "${INSTALLDIR}/pipi.exe"
i586-mingw32msvc-strip "${INSTALLDIR}/pipi.exe"

# Install gtk-sharp
cp -r "win32/gtksharp/"* "${INSTALLDIR}/"
find "${INSTALLDIR}/" -name .svn -prune -exec rm -rf '{}' ';'

# Install pipi-sharp
mv "${INSTALLDIR}/lib/mono/gac/pipi-sharp/"*/* "${INSTALLDIR}/bin/"
rm -Rf "${INSTALLDIR}/lib/mono"

# Install The Pimp
mv "${INSTALLDIR}/lib/ThePimp.exe" "${INSTALLDIR}/bin/"
echo 'int main(int argc, char *argv[], char *envp[]) { argv[0] = ".\\bin\\ThePimp.exe"; execve(argv[0], argv, envp); return 0; }' > run.c
i586-mingw32msvc-gcc run.c -mwindows -o "${INSTALLDIR}/ThePimp.exe"
i586-mingw32msvc-strip "${INSTALLDIR}/ThePimp.exe"

# Install documentation
mkdir "${INSTALLDIR}/doc"
for f in COPYING NOTES; do
   sed -e 's/$/
/' < "${SRCDIR}/${f}" > "${INSTALLDIR}/doc/${f}.txt"
done
rm -f "${INSTALLDIR}/lib/"*.a
rm -f "${INSTALLDIR}/lib/"*.la

# Pack the directory
zip "${DIRNAME}.zip" `find "${DIRNAME}"`
rm -Rf "${INSTALLDIR}"

