#! /bin/sh
#
# create_installer.sh
# Copyright (C) 2019-2021 Uwe Schitt <uwe.schmitt@id.ethz.ch>
#
# Distributed under terms of the MIT license.
#

set -e

# we have inplace changes we don't want to spoil to # "real" branches.
# we 1. determine current branch,
# 2. setup error handler to switch back to previous branch in all casses
# 3. create a new branch
OLD_BRANCH=$(/usr/local/bin/git branch --show-current)
WORK_BRANCH=setup_euler_temp_branch
cleanup() {
      echo CLEANUP
      git checkout ${OLD_BRANCH}
      git branch -D ${WORK_BRANCH}
  }
trap cleanup 0

git checkout -b ${WORK_BRANCH}

# files to include for installation:
NOTEBOOKS=??_*.ipynb

LOCAL_BUILD_FOLDER=$(pwd)/build
rm -rf ${LOCAL_BUILD_FOLDER}

# create fresh folder structure to build archive with notebooks
rm -rf ${LOCAL_BUILD_FOLDER}
mkdir -p ${LOCAL_BUILD_FOLDER}/course
mkdir -p ${LOCAL_BUILD_FOLDER}/solutions

cp ../custom.html ${LOCAL_BUILD_FOLDER}/course
cp ../custom.html ${LOCAL_BUILD_FOLDER}/solutions

cp -r ../data ${LOCAL_BUILD_FOLDER}/course
cp -r ../data ${LOCAL_BUILD_FOLDER}/solutions

cp -r ../images ${LOCAL_BUILD_FOLDER}/course
cp -r ../images ${LOCAL_BUILD_FOLDER}/solutions

# create solution notebooks, copy originals and solutions
# to build folder
pushd .. >/dev/null

for NOTEBOOK in ${NOTEBOOKS}; do
    echo process ${NOTEBOOK}
    jupyter nbconvert --ClearOutputPreprocessor.enabled=True --inplace ${NOTEBOOK}

    TARGET=${LOCAL_BUILD_FOLDER}/course/${NOTEBOOK}
    echo ${TARGET}
    nb-filter-cells -i $NOTEBOOK -t solution | nb-filter-cells -t TODO -o ${TARGET}

    TARGET=${LOCAL_BUILD_FOLDER}/solutions/${NOTEBOOK%.ipynb}-with-solutions.ipynb
    nb-filter-cells -i $NOTEBOOK -t TODO -o ${TARGET}
    # cp $NOTEBOOK ${TARGET}
done

popd >/dev/null
echo