#!/bin/bash

# This setups a Python 3.8 venv on the desktop, installs some packages,
# copies it to myfiles, setups some start files, and adds VSCode extenstions.
# As is, it is suitable to use on the VM infrastructure used in e.g.
# BC07-08 or CO02x. It will probably not work right away on local VM
# images may lack automatic mounting of myfiles at ~/Desktop/myfiles.
# Authors: Jean-Philippe Pellet, Matthieu Bovel
# Version: 2022-09-12

PYTHON=python3.10
COURSEFOLDERNAME=ICC_Programmation

echostep() {
    str="$1"
    len=${#str}
    pad="$(printf %-$((len + 5))s '')"
    pre="$(tput bold)$(tput setaf 4)$(tput rev)"
    post="$(tput sgr0)"
    echo ""
    echo "----"
    echo "$pre$pad$post"
    echo "$pre>> $1  $post"
    echo "$pre$pad$post"
    echo "----"
}

clear

echostep "Creating a Python virtual environment on myfiles..."

cd ~/Desktop/myfiles
mkdir -p "$COURSEFOLDERNAME"
cd "$COURSEFOLDERNAME"
mkdir -p venv/lib64 # needed to avoid symlink creation error on smb share
$PYTHON -m venv --copies venv
source venv/bin/activate

echostep "Installing Python packages..."

pip install --upgrade pip
pip install --upgrade six
pip install --upgrade wheel
pip install --upgrade setuptools
pip install pylint # linter
pip install mypy   # type checker
pip install mypy-extensions
pip install numpy
pip install matplotlib
pip install black  # code formatter
pip install bpython # interpreter with completion and syntax highlighting
pip install jupyter
pip install ipykernel
python -m ipykernel install --user --name=venv --display-name "Python (venv)"

# NOT NEEDED ANY MORE
## Change virtual env path from Desktop/venv to
## Desktop/myfiles/Programmation/$COURSEFOLDERNAME/venv in all scripts.
#grep -rl '/Desktop/venv' venv/bin | xargs sed -i "s|/Desktop/venv|/Desktop/myfiles/Programmation/$COURSEFOLDERNAME/venv|g"


echostep "Finishing setup in myfiles..."

#mkdir -p myfiles/Programmation/$COURSEFOLDERNAME
#echo "Removing old env... This may take a while..."
#rm -rf myfiles/Programmation/$COURSEFOLDERNAME/.env
#rm -rf myfiles/Programmation/$COURSEFOLDERNAME/venv
#echo "Copying new env... This may take a while..."
#cp -r venv myfiles/Programmation/$COURSEFOLDERNAME/
#rm -rf venv
#cd myfiles/Programmation/$COURSEFOLDERNAME/
mkdir -p .vscode

# This can be of course tweaked to reflect the best initial options for
# the created VS Code workspace. Careful with $, which must be escaped.
rm -f __workspace__.code-workspace
rm -f workspace.code-workspace
rm -f icc_prog.code-workspace
cat > icc_prog.code-workspace << EOM
// Ce fichier détermine les paramètres de votre workspace.
// Merci de ne pas le modifier à moins que la donnée d'un
// exercice vous demande de le faire.
{
    "folders": [
        {
            "path": "."
        }
    ],
    "settings": {
        "workbench.editor.showTabs": true,
        "workbench.tree.indent": 15,
        "zenMode.centerLayout": false,
        "python.envFile": "\${workspaceRoot}/venv",
        "python.defaultInterpreterPath": "venv/bin/$PYTHON",
        "python.formatting.provider": "black",
        "python.linting.pylintEnabled": false,
        "python.linting.mypyEnabled": true,
        "python.linting.mypyArgs": [
            "--disallow-any-expr",
            "--disallow-untyped-defs",
            "--warn-redundant-casts",
            "--warn-return-any"
        ],
        "python.terminal.activateEnvironment": false,
        "code-runner.executorMap": {
            "python": "PYTHONIOENCODING='utf-8' venv/bin/$PYTHON"
        },
        "code-runner.clearPreviousOutput": true,
        "code-runner.saveAllFilesBeforeRun": true,
        "code-runner.saveFileBeforeRun": true,
        "code-runner.runInTerminal": true,
        "code-runner.ignoreSelection": true,
        "files.watcherExclude": {
            "**/.env/**": true,
            "**/venv/**": true
        },
        "files.exclude": {
            "**/.DS_Store": true,
            "**/mypy.ini": true,
            "**/.env": true,
            "**/venv": true,
            "**/.vscode": true,
            "**/.mypy_cache": true,
            "**/.ipynb_checkpoints": true
        },
    },
}
EOM

# Allows silencing some of the mypy warnings.
rm -f mypy.ini
cat > mypy.ini << EOM
[mypy]

[mypy-numpy]
ignore_missing_imports = True
EOM

# Predefined tasks can be provided like this
rm -f .vscode/tasks.json
cat > .vscode/tasks.json << EOM
{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "bpython",
            "type": "shell",
            "command": "source venv/bin/activate && venv/bin/bpython",
            "problemMatcher": [],
            "presentation": {
                "focus": true,
                "showReuseMessage": true,
                "echo": false,
                "panel": "dedicated"
            }
        },
        {
            "label": "jupyter",
            "type": "shell",
            "command": "source venv/bin/activate && venv/bin/jupyter-notebook",
            "problemMatcher": [],
            "presentation": {
                "focus": false,
                "showReuseMessage": true,
                "echo": false,
                "panel": "dedicated"
            }
        }
    ]
}
EOM



# Simple Python test file
if [ ! -f test.py ]; then
	cat > test.py << EOM
# Cliquez sur le bouton Play en haut à droite pour exécuter ceci
# en choisissant Run Code. Vous pouvez aussi utiliser le raccourci
# Ctrl+Alt+N (cela prend un peu de temps la première fois).
msg: str = 'Welcome to Python!'
print(msg)
EOM
fi

# Simple notebook test file
if [ ! -f test.ipynb ]; then
	cat > test.ipynb << EOM
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Bienvenue sur les Jupyter Notebooks!\n",
    "\n",
    "Ceci est un moyen, sur une même «page», de proposer du contenu textuel et des extraits de code, qui peuvent être exécutés et qui sont potentiellement modifiables.\n",
    "\n",
    "Chacune des cellules de type «code» ci-dessous peut être évaluée en cliquant dessus puis en tapant Majuscule-Retour."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "6"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "3 + 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "3 * 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "27"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "a = 3\n",
    "a ** a"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
EOM
fi

# Key bindings are directly put in the user's settings folder,
# they can't be loaded from workspace settings
cd ~/Desktop/myfiles
mkdir -p epfl_roaming/ic_in-sc/.Code/User/
rm -f epfl_roaming/ic_in-sc/.Code/User/keybindings.json
cat > epfl_roaming/ic_in-sc/.Code/User/keybindings.json << EOM
// Custom keybindings for the course
[
    {
        "key": "ctrl+j",
        "command": "-workbench.action.togglePanel"
    },
    {
        "key": "ctrl+i",
        "command": "workbench.action.tasks.runTask",
        "args": "bpython"
    },
    {
        "key": "ctrl+j",
        "command": "workbench.action.tasks.runTask",
        "args": "jupyter"
    }
]
EOM


echostep "Installing VS Code extensions..."

code --install-extension ms-python.python
code --uninstall-extension formulahendry.code-runner
code --install-extension ramyaraoa.show-offset
code --install-extension ms-toolsai.jupyter

echostep "Done. Close this window, launch VS Code, and open the workspace file."
