#!/usr/bin/env sh

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

success() {
    if [ $? -ne 0 ]; then
        echo $1
        exit 1
    fi
}

cd src

# Apply two patches to 'setup.py' in the correct order (the second
# one is based on the first one!):
patch -p1 < ../patches/dont-add-system-libs-if-binary-build.patch &&
patch -p1 < ../patches/search-lib64-dirs-if-appropriate.patch
success "Error patching PIL"

echo "Deleting old versions..."
rm -rf "$SAGE_LOCAL"/lib/python/site-packages/PIL
rm -f "$SAGE_LOCAL"/lib/python/site-packages/PIL.pth
success "Error deleting previous version of PIL"

python setup.py install

if [ $? -ne 0 ]; then
    echo "Warning: Failed to install PIL with TK, retrying without TK support..."
    export SAGE_PIL_NOTK='yes'
    python setup.py install
fi

success "Error building / installing PIL"
