#!/usr/bin/env bash

if [ "$SAGE_LOCAL" = "" ]; then
   echo "SAGE_LOCAL undefined ... exiting";
   echo "Maybe run 'sage -sh'?"
   exit 1
fi

# distribute doesn't allow itself to be replaced by setuptools
# so we manually have to delete it
# (pip actually can uninstall setuptools but we may not have pip
# install yet)
rm -rf "$SAGE_LOCAL"/lib/python*/site-packages/setuptools*
rm -rf "$SAGE_LOCAL"/lib/python*/site-packages/distribute*

export PYTHON_EGG_CACHE="$DOT_SAGE/.python-eggs"

cd src

# Apply patches.  See SPKG.txt for information about what each patch
# does.
for patch in ../patches/*.patch; do
    [ -r "$patch" ] || continue  # Skip non-existing or non-readable patches
    patch -p1 <"$patch"
    if [ $? -ne 0 ]; then
        echo >&2 "Error applying '$patch'"
        exit 1
    fi
done

# Prevent setuptools from installing itself with easy_install
python setup.py install --single-version-externally-managed --record=/dev/null
