#!/bin/bash

set -e

# Taken from https://github.com/scikit-learn/scikit-learn/blob/72b3041ed57e42817e4c5c9853b3a2597cab3654/.binder/postBuild
# under BSD3 license, copyright the scikit-learn contributors

python -m pip install .

# This script is called in a binder context. When this script is called, we are
# inside a git checkout of the scikit-image/scikit-image repo. This script
# generates notebooks from the scikit-image python examples.

if [[ ! -f /.dockerenv ]]; then
    echo "This script was written for repo2docker and is supposed to run inside a docker container."
    echo "Exiting because this script can delete data if run outside of a docker container."
    exit 1
fi

# Copy content we need from the scikit-image repo
TMP_CONTENT_DIR=/tmp/scikit-image
mkdir -p $TMP_CONTENT_DIR
cp -r doc/examples .binder $TMP_CONTENT_DIR
# delete everything in current directory including dot files and dot folders
# to create a "clean" experience for readers
find . -delete

# Generate notebooks and remove other files from examples folder
GENERATED_NOTEBOOKS_DIR=auto_examples
cp -r $TMP_CONTENT_DIR/examples $GENERATED_NOTEBOOKS_DIR

find $GENERATED_NOTEBOOKS_DIR -name '*.py' -exec sphx_glr_python_to_jupyter.py '{}' +
NON_NOTEBOOKS=$(find $GENERATED_NOTEBOOKS_DIR -type f | grep -v '\.ipynb')
rm -f $NON_NOTEBOOKS

# Modify path to be consistent by the path given by sphinx-gallery
mkdir notebooks
mv $GENERATED_NOTEBOOKS_DIR notebooks/


# Put the .binder folder back (may be useful for debugging purposes)
mv $TMP_CONTENT_DIR/.binder .
# Final clean up
rm -rf $TMP_CONTENT_DIR
