#!/bin/bash

if [ $PY_VER != 3.6 ]; then
    echo "PY_VER: $PY_VER"
    echo "Please use conda-build with --python=3.6 option"
    exit 1
fi

rm -rf Lib/ensurepip

if [ `uname` == Darwin ]; then
    export CFLAGS="-I$PREFIX/include $CFLAGS"
    export LDFLAGS="-L$PREFIX/lib $LDFLAGS"
    export MACOSX_DEPLOYMENT_TARGET="10.6"
fi

PYTHON_BAK=$PYTHON
unset PYTHON

if [ `uname` == Darwin ]; then
    ./configure --enable-shared --enable-ipv6 --with-ensurepip=no \
        --prefix=$PREFIX \
        --with-tcltk-includes="-I$PREFIX/include" \
        --with-tcltk-libs="-L$PREFIX/lib -ltcl8.6 -ltk8.6"
    # see https://bugs.python.org/issue24844
#    replace \
#        '#define HAVE_BUILTIN_ATOMIC 1' \
#        '/* #define HAVE_BUILTIN_ATOMIC 1 */' \
#        pyconfig.h
fi
if [ `uname` == Linux ]; then
    ./configure --enable-shared --enable-ipv6 --with-ensurepip=no \
        --prefix=$PREFIX \
        --with-tcltk-includes="-I$PREFIX/include" \
        --with-tcltk-libs="-L$PREFIX/lib -ltcl8.6 -ltk8.6" \
        CPPFLAGS="-I$PREFIX/include" \
        LDFLAGS="-L$PREFIX/lib -Wl,-rpath=$PREFIX/lib,--no-as-needed"
fi

make -j 8
make install

pushd $PREFIX/bin
ln -s python3.6 python
ln -s pydoc3.6 pydoc
popd

export PYTHON=$PYTHON_BAK

# Remove wininst* executables due to old included zlib
rm $STDLIB_DIR/distutils/command/wininst*.exe

DYNLOAD_DIR=$PREFIX/lib/python3.6/lib-dynload
if [ `uname` == Darwin ]; then
    rm $DYNLOAD_DIR/_hashlib.cpython-36m-darwin_failed.so
    rm $DYNLOAD_DIR/_ssl.cpython-36m-darwin_failed.so
    pushd Modules
    rm -rf build
    cp $RECIPE_DIR/setup_misc.py .
    $PREFIX/bin/python setup_misc.py build
    cp build/lib.macosx-*/_hashlib.cpython-36m-darwin.so \
       build/lib.macosx-*/_ssl.cpython-36m-darwin.so \
           $DYNLOAD_DIR
    popd
    pushd $DYNLOAD_DIR
    if [ -f readline.cpython-36m-darwin_failed.so ]; then
        mv readline.cpython-36m-darwin_failed.so readline.cpython-36m-darwin.so
    fi
    if [ -f _lzma.cpython-36m-darwin_failed.so ]; then
        mv _lzma.cpython-36m-darwin_failed.so _lzma.cpython-36m-darwin.so
    fi
    if [ -f _tkinter.cpython-36m-darwin_failed.so ]; then
        mv _tkinter.cpython-36m-darwin_failed.so _tkinter.cpython-36m-darwin.so
    fi
    popd
    sed -i -e "s/'MACOSX_DEPLOYMENT_TARGET': '10.9'/MACOSX_DEPLOYMENT_TARGET': '10.6'/g" $PREFIX/lib/python3.6/_sysconfigdata_m_darwin_darwin.py
    sed -i -e "s/MACOSX_DEPLOYMENT_TARGET=10.9/MACOSX_DEPLOYMENT_TARGET=10.6/g" $PREFIX/lib/python3.6/config-3.6m-darwin/Makefile
fi
