#!/bin/bash
#
# Initialize the environment for use with my tools.
#
# Several additional options are provided as one-time initializations:
#   cocalc: Initial a CoCalc project for use as described here:
#      https://alum.mit.edu/www/mforbes/public/notes/cocalc-workflow/

function usage() {
    echo "usage: mmf_setup cocalc [options] OR mmf_setup -v [options] OR source mmf_setup [options]"
    echo
    echo "The first invocation will setup cocalc.com projects:"
    echo
    echo "   mmf_setup cocalc [options]"
    echo
    echo "Additional options are passed to mmf_initial_setup.  For more info run"
    echo
    echo "   mmf_initial_setup -h"
    echo
    echo "The second invocation will show which environmental variables will be set:"
    echo
    echo "   mmf_setup -v [options]"
    echo
    echo "The third invocation will actually set this in your shell by running mmf_setup_bash.py:"
    echo
    echo "   source mmf_setup [options]   OR . mmf_setup [options]"
    echo
    echo "Valid options for mmf_setup_bash.py are:"
    echo "$(mmf_setup_bash.py -h)"    
}

BIN_DIR="$(dirname $BASH_SOURCE{0})"

if [[ -n $1 ]]; then
    case $1 in
        -v)
            shift # move to the next argument
            echo "mmf_setup environment:"
            echo "$(mmf_setup_bash.py $*)"
            exit 0
            ;;
        smc|cocalc)
            hg="$(type -p hg)"
            if [[ -n "${hg}" ]]; then
		            hg_python="$(hg debuginstall -T'{pythonexe}')"
                echo "Upgrading mercurial, hg-evolve, and hg-git for hg=${hg}..."
                echo "${hg_python} -m pip install --upgrade --user mercurial hg-evolve hg-git"
                ${hg_python} -m pip install --upgrade --user mercurial hg-evolve hg-git
            else
                echo "Installing mercurial, hg-evolve, and hg-git for python3..."
                python3 -m pip install --upgrade --user mercurial hg-evolve hg-git
            fi
            
            DATA_DIR="$(python -c 'import mmf_setup;print(mmf_setup.DATA)')"
            echo "Setting up config files for CoCalc..."
            shift # move to the next argument
            "$BIN_DIR/mmf_initial_setup" \
                 -v "$DATA_DIR/config_files/cocalc" $*
            cat "$DATA_DIR/config_files/cocalc/message.txt"

            # Upgrade jupytext
            echo "Upgrading jupytext for python3..."
            python3 -m pip install --upgrade --user jupytext
            exit 0
            ;;
        -h)
            usage
            exit 1
            ;;
    esac
fi
if [[ -n $BASH_VERSION ]] && [[ "$(basename "$0" 2> /dev/null)" == "mmf_setup" ]]; then
    # Ensure that this script is sourced, not executed
    >&2 echo "Error: mmf_setup must be sourced. Run 'source mmf_setup' or '. mmf_setup' instead of 'mmf_setup'"
    >&2 echo
    usage
else
    # Okay.  Actually source the environment
    eval "$(mmf_setup_bash.py $*)"
fi
