#!/bin/bash

# This script runs in a Binder context within a git checkout of the
# neuroinformatics-unit/ethology repository. It generates Jupyter notebooks
# from the ethology Python examples.
# The script was adapted from https://github.com/scikit-learn/scikit-learn/blob/1.8.0rc1/.binder/postBuild

set -euo pipefail       # fail immediately on errors and undefined vars

# Safety check: exit if not running inside a docker container.
: "${REPO_DIR:?This script is for repo2docker and REPO_DIR must be set. \
Exiting because this script can delete data if run outside of a repo2docker context.}"

# Create a temporary directory for staging the examples
TMP_DIR=$(mktemp -d /tmp/ethology-XXXXXX)
# Clean up temporary directory on exit
trap 'rm -rf "$TMP_DIR"' EXIT

# Stage the examples in a temporary directory
cp -r examples "$TMP_DIR/"
# Recursively convert all python scripts to notebooks
find "$TMP_DIR/examples" -name '*.py' -exec sphinx_gallery_py2jupyter '{}' +
# Remove all non-notebook files
find "$TMP_DIR/examples" -type f ! -name '*.ipynb' -delete

# Remove everything except the existing .binder folder to present a clean workspace
# (the .binder folder is kept for debugging purposes)
find . -mindepth 1 -maxdepth 1 ! -name '.binder' -exec rm -rf {} +

# Move the generated notebook files to where Binder expects
mkdir -p notebooks
mv "$TMP_DIR/examples" notebooks/
