#!/bin/sh

. config/options $1

PY_DISABLED_MODULES="readline _curses _curses_panel _tkinter nis gdbm bsddb _codecs_kr _codecs_jp _codecs_cn _codecs_tw _codecs_hk"

cd $PKG_BUILD

mkdir -p .objdir-host && cd .objdir-host

setup_toolchain host

OPT="$HOST_CFLAGS" \
LDFLAGS="$LDFLAGS -lexpat" \
../configure --prefix=$ROOT/$TOOLCHAIN \
             --cache-file=config.cache \
             --enable-shared \
             --without-cxx-main \
             --with-threads \
             --enable-unicode=ucs4 \

make
make install

cp Parser/pgen ./hostpgen
cp python ./hostpython

cd ..

mkdir -p .objdir-target && cd .objdir-target

setup_toolchain target

# dont use some optimizations because of problems
# this fixes problems with expat (maybe)
  LDFLAGS=`echo $LDFLAGS | sed -e "s|-Wl,--as-needed||"`

  strip_lto

ac_cv_file_dev_ptc=no \
ac_cv_file_dev_ptmx=yes \
ac_cv_func_lchflags_works=no \
ac_cv_func_chflags_works=no \
ac_cv_func_printf_zd=yes \
OPT="$CFLAGS -fno-strict-aliasing" \
LDFLAGS="$LDFLAGS -lexpat" \
../configure --host=$TARGET_NAME \
             --build=$HOST_NAME \
             --cache-file=config.cache \
             --prefix=/usr \
             --sysconfdir=/etc \
             --enable-shared \
             --with-threads \
             --enable-unicode=ucs4 \
             --disable-ipv6 \
             --disable-profiling \
             --without-pydebug \
             --without-doc-strings \
             --without-tsc \
             --without-pymalloc \
             --without-fpectl \
             --without-wctype-functions \
             --without-cxx-main \
             --with-system-ffi \

make  -j1 CC="$TARGET_CC" \
      HOSTPYTHON=../.objdir-host/hostpython \
      HOSTPGEN=../.objdir-host/hostpgen \
      BLDSHARED="$CC -shared" \
      PYTHON_DISABLE_MODULES="$PY_DISABLED_MODULES" \
      CROSS_COMPILE="$TARGET_NAME" \
      CROSS_COMPILE_TARGET="yes" \
      PYTHON_MODULES_INCLUDE=$SYSROOT_PREFIX/usr/include \
      PYTHON_MODULES_LIB="$SYSROOT_PREFIX/lib $SYSROOT_PREFIX/usr/lib" \

make  -j1 CC="$TARGET_CC" \
      DESTDIR=$SYSROOT_PREFIX \
      HOSTPYTHON=../.objdir-host/hostpython \
      HOSTPGEN=../.objdir-host/hostpgen \
      BLDSHARED="$CC -shared" \
      PYTHON_DISABLE_MODULES="$PY_DISABLED_MODULES" \
      CROSS_COMPILE="$TARGET_NAME" \
      CROSS_COMPILE_TARGET="yes" \
      PYTHON_MODULES_INCLUDE=$SYSROOT_PREFIX/usr/include \
      PYTHON_MODULES_LIB="$SYSROOT_PREFIX/lib $SYSROOT_PREFIX/usr/lib" \
      install

cp -R ../Lib ./
  $ROOT/$TOOLCHAIN/bin/python -Wi -t ./Lib/compileall.py -f -x test ./Lib

# replace python-config to make sure python uses $SYSROOT_PREFIX
  mkdir -p $ROOT/$TOOLCHAIN/bin
  rm -rf $ROOT/$TOOLCHAIN/bin/python*-config

  sed -e "s:%PREFIX%:$SYSROOT_PREFIX/usr:g" -e "s:%CFLAGS%:$TARGET_CFLAGS:g" \
    $ROOT/$PKG_DIR/scripts/python-config > $ROOT/$TOOLCHAIN/bin/python2.6-config
  chmod +x $ROOT/$TOOLCHAIN/bin/python2.6-config
  ln -s python2.6-config $ROOT/$TOOLCHAIN/bin/python-config
