#!/bin/bash
set -eu  # exit on most (not all!) error codes, and error on unset variables

pip install ephem

# This should install ecrad in some directory and build it

# last ecRad version tested within htexplo
commit="fa642e2"  # 03/08/2024

#This script install and compile ecrad
ROOT="$(pwd)"
install_dir=$(realpath $ROOT/..)

ECRAD="ecrad"
ECRADroot=""
if [[ -d $ROOT/../../$ECRAD ]] ; then
   ECRADroot=$ROOT/../..
else
   # By default, ECRAD is installed next to HighTune like LMDZ
   ECRADroot=$ROOT/..
fi
ECRADroot=$(readlink -f "$ECRADroot")
ECRADdir=$ECRADroot/$ECRAD

echo "export ECRADdir=$ECRADdir" > $install_dir/env_ECRAD.profile

hostname=$(hostname) 
case ${hostname:0:6} in
  "beleno") echo "\
# this config is designed for belenos
# module purge tries to unalias condam but the alias does not exist so it raises an error
# so I create a false condam alias so that it can be unaliased...
alias condam="ls"
module purge
module load gcc/9.2.0
module load cmake/3.24.1
module load openmpi/gnu/ilp64/4.0.5.1 # this is a prereq for hdf5
module load hdf5/1.8.18
export PATH=/opt/softs/libraries/GCC_5.3.0/nco-4.5.5/bin/:\$PATH
export PATH=$install_dir/bin:\$PATH   # we still need sed_i command
alias ncap2="ncap"
" >> $install_dir/env_ECRAD.profile
    ;;

  *) # in the general case, we copy env.sh to env_ECRAD.profile
    cat $install_dir/env.sh >> $install_dir/env_ECRAD.profile
    ;;
esac

source $install_dir/base_env.profile
test -f $install_dir/env_LMDZ.profile && source $install_dir/env_LMDZ.profile


if [[ ! -d $ECRADdir ]] ; then
  echo "ECRAD installation "
  cd "$ECRADroot"
  git clone https://github.com/ecmwf/ecrad
fi
cd "$ECRADdir"
set +e
command -v git > /dev/null 2>&1
if [ $? -eq 0 ] ; then 
  git checkout "$commit"
  make PROFILE=gfortran
else
  echo "warning: git command not available, could not checkout commit $commit in $ECRADdir"
fi
set -e

if [[ ! -d dephy2ecRad ]] ; then
  git clone https://gitlab.com/najdavlf/dephy2ecrad.git -b master dephy2ecRad
fi
