#!/bin/bash

mkdir -p /home/jovyan/work/.jupyter_config/lab/user-settings/@jupyterlab/toc-extension
cp ./.user-settings/@jupyterlab/toc-extension/plugin.jupyterlab-settings /home/jovyan/work/.jupyter_config/lab/user-settings/@jupyterlab/toc-extension/plugin.jupyterlab-settings

# sync latest changes from upstream fork
# TODO: maybe we'll switch this to main in the future
REMOTE_BRANCH="master"

# get current semester
ORIGIN=$(git remote get-url origin)
SEMESTER=$(echo ${ORIGIN} | sed -re 's/https\:\/\/renkulab\.io\/gitlab\/.+\/(.*)\.git/\1/gi')

# Did someone start the semester repo directly?
if [ ${ORIGIN} != "https://renkulab.io/gitlab/grundkurs-programmieren/${SEMESTER}.git" ]
then
    # add upstream remote
    git remote add upstream https://renkulab.io/gitlab/grundkurs-programmieren/${SEMESTER}.git

    # make sure we're in master branch
    git checkout ${REMOTE_BRANCH}

    # fetch and pull changes
    while true; do
        git fetch upstream
        if [ $? -eq 0 ]; then
            git pull upstream ${REMOTE_BRANCH}
            break
        fi
    done

    # Check if requirements.txt did change
    CHANGES=$(git diff-tree --no-commit-id --name-only -r upstream/master)
    PIP=$( echo ${CHANGES} | awk '/requirements.txt/{print $0}' )

    if [ ! -z ${PIP} ]
    then
        # If requirements.txt did change we need to install new packages
        pip install -r requirements.txt
    fi

    # add local changes
    git add .
    git commit -m "chore: add latest user changes"

    # sync back to origin
    git push origin ${REMOTE_BRANCH}
fi