#!/bin/bash
#
#########################################
#
# Script to build and maintain en environment to run
# the python code in this directory. We verify that
# all needed packages are available.
# This is based on the anaconda python system : https://www.anaconda.com/distribution/
#
# Usage : source Environment
#
#########################################
#
# Functions
#
function hasanaconda (){
    ipsl="ipsl camelot climserv ciclad"
    idris="idris jean-zay"
    case $(hostname -d) in
	climserv*|private.ipsl.fr|ipsl.polytechnique.fr)
	    echo "IPSL"
	    eval  "$1='ipsl'"
	    ;;
	idris*|jean-zay*)
	    echo "IDRIS"
	    eval "$1='idris'"
	    ;;
	*)
	    echo "unknown machine : $(hostname -d)"
	    eval "$1='unknown'"
    esac
}

function checkenv (){
    rm -f checkenv.py
    cat <<EOF > checkenv.py
import mpi4py
import spherical_geometry
import netCDF4
import matplotlib
import mpl_toolkits
import configparser
import numba
import cartopy
print ("OK")
EOF
    python checkenv.py > /dev/null
    if [ $? -gt 0 ] ; then
	echo "Environment not OK. Some packages must be missing."
	echo "This was tested with the checkenv.py code."
    else
	rm -f checkenv.py
    fi
}
#
# Main
#
loc=''
hasanaconda loc

if [ loc != "unknown" ] ; then
    #
    # Make sure the right version of Python
    #
    case $loc in
	"ipsl")
	    module unload python
	    module load python/3.6-anaconda50
	    #
	    # Test if the MPI environment is installed.
	    #
	    if [ ! -e ${HOME}/.conda/envs/MPI ] ; then
		#
		# Create the MPI environment as it does not exist.
		#
		conda create -y -n MPI --channel astropy mpi4py numba astropy spherical-geometry netcdf4 ConfigParser
		source activate MPI
		conda install -y --channel astropy matplotlib basemap
		conda install -y --channel astropy cartopy
	    else
		source activate MPI
	    fi
	    ;;
	"idris")
	    module load python/3.7.3
	    if [[ -L ${HOME}/.conda && -d ${HOME}/.conda ]] ; then
		if [ ! -e ${WORK}/.conda/envs/MPI ] ; then
		    conda create -y -n MPI mpi4py numba astropy netcdf4 matplotlib basemap ConfigParser cartopy
		    conda activate MPI
		    if [[ -L ${HOME}/.local && -d ${HOME}/.local ]] ; then
			export PYTHONUSERBASE=$WORK/.local
			if [ $(find $PYTHONUSERBASE -name spherical_geometry -ls | wc -l) -le 0 ] ; then
			    git clone https://github.com/spacetelescope/spherical_geometry.git
			    cd spherical_geometry
			    python setup.py install --user
			fi
		    else
			echo "Make sure \$HOME/.link is a link to your \$WORK/.local"
		    fi
		else
		    conda activate MPI
		fi
	    else
		echo "Make sure \$HOME/.conda is a link to your \$WORK/.conda"
	    fi
	    ;;
	*)
	    echo "Environment for $loc is not foreseen yet"
	    exit
	    ;;
	esac
fi
#
# Verify we can load all the needed modules.
	#
	
checkenv