#!/bin/bash
#
# ==================================================================== #
# Author: Sonia Labetoulle                                             #
# Contact: sonia.labetoulle _at_ ipsl.jussieu.fr                       #
# Created: March 21 2016                                               #
# History:                                                             #
# Modification:                                                        #
# ==================================================================== #
# Launch everything needed to track the consumption                    #
# for GENCI projects.                                                  #
# To be executed by a cron                                             #
# ======================================================================

date
whereami=$( hostname -s )

# set -vx

# .. System dependant steps ..
# ============================

python_exe="python"
case ${whereami} in
  pc-236) 
    echo "maison"
    python_exe="/opt/epd7/bin/python"
    ;;
  curie*)
    echo "curie"
    # ... Initialize module command ...
    # ---------------------------------
    if [ -f /etc/bashrc ] ; then
      . /etc/bashrc
    fi
    # ... Load python ...
    # -------------------
    # python/2.7.3 is the default, but it comes with matplotlib 1.2, 
    # which is too old (no context manager for PdfPages)
    module load python/2.7.8
    ;;
  *)
    echo "Unknown host ${whereami}, exit"
    exit 1
    ;;
esac

# Go to root directory
# ====================
ROOT_DIR=$( dirname $0 )
cd ${ROOT_DIR}
BIN_DIR=${ROOT_DIR}/bin

declare -A proj_center=(["gencmip6"]="tgcc" ["rgzi"]="idris")

for projet in "${!proj_center[@]}"
do
  centre=${proj_center[${projet}]}

  echo -e "\n* ${projet}/${centre}"
  echo -e "================================================="

  # .. Insert cpt data into database ..
  # ===================================
  echo -e "1) Insert cpt data into table"
  echo -e "-------------------------------------------------"
  ${python_exe} ${BIN_DIR}/insert_conso_tbl.py -v ${projet} ${centre}
  RC=$?
  if [ ${RC} -gt 1 ] ; then
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
    echo "!                                    ! "
    echo "!   ERROR: script ended abnormally   !"
    echo "!                                    ! "
    echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"
  elif [ ${RC} -ne 0 ] ; then
    echo -e "\n   => nothing to do for ${projet}/${centre}"
    continue
  fi

  echo "test"

  # .. Plot daily consumption ..
  # ============================
  echo -e "\n2) Plot daily consumption"
  echo -e "-------------------------------------------------"
  ${python_exe} ${BIN_DIR}/plot_bilan.py -vdf ${projet} ${centre}
done

