#!/bin/bash

# stop as soon as a comand returns an error:
set -e

## Default values for various script options
installdir="trunk"
commit="HEAD"
arch="local"
compiler_suite="gnu"
repo="svn"
netcdf=false

dim=32x24x27
bands=17x23
physics=pluto
testcase=pluto

# dim=32x32x15
# bands=32x36
# physics=std
# testcase=earlymars

machine=`hostname`
#if [[ ${machine:7:10} == "occigen" ]] ; then
#  arch=X64_OCCIGEN
#fi
#if [[ ${machine:0:5} == "ada33" ]] ; then
#  arch=X64_ADA
#fi

# 0.1 Check that prerequisits are there
for logiciel in svn wget tar gzip make ; do
if [ "`which $logiciel`" = "" ] ; then
echo You must first install $logiciel on your system
exit
fi
done

if [ "`which fcm`" = "" ] ; then
echo "You must first install fcm and add it to your PATH, e.g.:"
echo "cd ; svn co http://forge.ipsl.jussieu.fr/fcm/svn/PATCHED/FCM_V1.2"
echo "and add FCM_V1.2/bin to your PATH environment variable,"
echo "e.g. add in your .bashrc the following line:"
echo 'export PATH=$PATH:$HOME/FCM_V1.2/bin'
exit
fi

# 0.2 Get user options from command line
while (($# > 0))
   do
   case $1 in
    "-h") cat <<........end
    Script usage:
    $0 [option1 value1 option2 value2 ...]
    where available options are:
    -installdir name of subdirectory to install in (default: $installdir)
    -netcdf (install netcdf? default: deactivated )
    -git (default: deactivated )
    -git-https (default: deactivated )
    -planeto_rev revision number of planeto repository (default: $commit)
    -compiler compiler family (default: $compiler_suite ; gnu | intel )
........end
     exit ;;
    "-netcdf") netcdf=true ;  shift ;;
    "-git") repo=git ;  shift ;;
    "-git-https") repo=git-https ;  shift ;;
    "-installdir") installdir=$2 ; shift ; shift ;;
    "-planeto_rev") commit==$2 ; shift ; shift ;;
    "-compiler") compiler_suite=$2 ; shift ; shift ;;
    *) $0 -h ; exit
   esac
done

# check compiler is available
if [[ ${compiler_suite} == "gnu" ]] ; then
  f_compiler="gfortran"
  c_compiler="gcc"
elif [[ ${compiler_suite} == "intel" ]] ; then
  f_compiler="ifort"
  c_compiler="icc"
else
  echo "unknown compiler family $compiler_suite"
  echo "might as well stop here"
  exit
fi
for logiciel in $f_compiler $c_compiler ; do
if [ "`which $logiciel`" = "" ] ; then
echo You must first install $logiciel on your system
exit
fi
done

rootdir=`pwd -P`

# 1. Check out "Planeto" repository
cd $rootdir
if [ "$repo" = "svn" ]; then
    echo Installing svn
    svn co --revision $commit http://svn.lmd.jussieu.fr/Planeto/trunk --depth empty  $installdir
    cd $installdir
    svn update LMDZ.COMMON LMDZ.PLUTO DOC
    echo Installed svn
elif [ "$repo" = "git" ]; then
    echo Installing git
    if [ -d $installdir ]; then
        echo "$installdir already used. Trying current repository..."
        cd $installdir
        git checkout $commit
        # git pull --rebase
    else
        git clone git@gitlab.in2p3.fr:la-communaut-des-mod-les-atmosph-riques-plan-taires/git-trunk.git $installdir
        cd $installdir
        git checkout $commit
    fi
    echo Installed git
elif [ "$repo" = "git-https" ]; then
    echo Installing git
    if [ -d $installdir ]; then
        echo "$installdir already used. Trying current repository..."
        cd $installdir
        # git pull --rebase
    else
        git clone https://gitlab.in2p3.fr/la-communaut-des-mod-les-atmosph-riques-plan-taires/git-trunk.git $installdir
        cd $installdir
    fi
    echo Installed git
else
    echo "Repository '$repo' not recognized. Use either 'svn' or 'git'."
fi

# 1.2 Download bench test case
cd $rootdir
if [ -f bench_${testcase}_${dim}_b${bands}.tar.gz ]; then
    mv bench_${testcase}_${dim}_b${bands}.tar.gz bench_${testcase}_${dim}_b${bands}.tar.gz.save
fi
wget -nv --no-check-certificate http://www.lmd.jussieu.fr/~lmdz/planets/pluto/bench_${testcase}_${dim}_b${bands}.tar.gz

# 1.3. Check out and build the NetCDF library
if [ "$netcdf" = "true" ];then
    echo Installing netCDF
    cd $rootdir
    mkdir -p netcdf
    cd netcdf
    if [ -f lib/libnetcdf.a ]; then
        echo "Found existing netcdf library installed in netcdf/. Skipping install"
    else
        wget -nv --no-check-certificate http://www.lmd.jussieu.fr/~lmdz/pub/script_install/install_netcdf4_hdf5_seq.bash
        chmod u=rwx install_netcdf4_hdf5_seq.bash
        netcdflog=$rootdir/netcdf.log
        ./install_netcdf4_hdf5_seq.bash -compiler $compiler_suite > $netcdflog 2>&1
        echo Installed netCDF
    fi
    export NETCDF=$rootdir/netcdf
    export NETCDFINCLUDE=$NETCDF/include
    export NETCDFDIR=$NETCDF/lib
else
    export NETCDF=$(nf-config --prefix)
    export NETCDFINCLUDE=$(nf-config --includedir)
    export NETCDFDIR="$(nf-config --flibs) $(nc-config --libs)"
fi

# 2.1 Compile IOIPSL
echo Installing IOIPSL
cd $rootdir/$installdir/LMDZ.COMMON/ioipsl
if  [[ ${compiler_suite} == "gnu" ]] ; then
sed -i -e s:'NETCDF_HOME=$(nf-config --prefix)':"NETCDF_HOME=$NETCDF":1 install_ioipsl_gfortran.bash
./install_ioipsl_gfortran.bash > install_ioipsl_gfortran.out 2>&1
else
sed -i -e s:'NETCDF_HOME=$(nf-config --prefix)':"NETCDF_HOME=$NETCDF":1 install_ioipsl_ifort.bash
./install_ioipsl_ifort.bash > install_ioipsl_ifort.out 2>&1
fi
echo Installed IOIPSL

# 2.2 Compile LMDZ
cd $rootdir/$installdir/LMDZ.COMMON
# 2.2.1 Make arch files
cd arch
echo 'ROOT=$PWD' > arch-local.path
echo "" >> arch-local.path
echo 'NETCDF_LIBDIR="-L'$NETCDF'/lib"' >> arch-local.path
echo 'NETCDF_LIB="-lnetcdf -lnetcdff"' >> arch-local.path
echo 'NETCDF_INCDIR="-I'$NETCDF'/include"' >> arch-local.path
echo "" >> arch-local.path
echo 'IOIPSL_INCDIR="-I$ROOT/ioipsl/modipsl/lib"' >> arch-local.path
echo 'IOIPSL_LIBDIR="-L$ROOT/ioipsl/modipsl/lib"' >> arch-local.path
echo 'IOIPSL_LIB="-lioipsl"' >> arch-local.path
echo "" >> arch-local.path
echo 'XIOS_INCDIR="-I$ROOT/../XIOS/inc"' >> arch-local.path
echo 'XIOS_LIBDIR="-L$ROOT/../XIOS/lib"' >> arch-local.path
echo 'XIOS_LIB="-lxios -lstdc++"' >> arch-local.path

if  [[ ${compiler_suite} == "gnu" ]] ; then
cp arch-gfortran.fcm arch-local.fcm
else
cp arch-linux-ifort.fcm arch-local.fcm
fi

if [ "$netcdf" = "true" ];then
    echo 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:'${NETCDF}'/lib' > arch-local.env
fi

# 2.2.2 Compile PCM
echo Compiling PCM
cd $rootdir/$installdir/LMDZ.COMMON
./makelmdz_fcm -arch $arch -p $physics -d $dim -b $bands -j 8 gcm #> makelmdz_fcm.out 2>&1

if [ -f bin/gcm_${dim}_phy${physics}_b${bands}_seq.e ] ; then
  echo "success! Executable is in $rootdir/$installdir/LMDZ.COMMON/bin"
else
  echo "something went wrong"
  echo "check file $rootdir/$installdir/LMDZ.COMMON/makelmdz_fcm.out"
fi

# 3. Run Bench
cd $rootdir
tar xvzf bench_${testcase}_${dim}_b${bands}.tar.gz
cp $installdir/LMDZ.COMMON/bin/gcm_${dim}_phy${physics}_b${bands}_seq.e bench_${testcase}_${dim}_b${bands}/
cd bench_${testcase}_${dim}_b${bands}/

if [ ! -d datadir ];then
    \rm -rf \~lmdz # in case of previous download
    if wget --no-host-directories -nc --continue --no-verbose --no-parent --recursive "https://web.lmd.jussieu.fr/~lmdz/planets/${physics}/datadir/"
    then
        echo Success downloading datadir!
    fi
    \mv \~lmdz/planets/${physics}/datadir .
    \rm -rf \~lmdz
fi

echo 'source '$rootdir'/'$installdir'/LMDZ.COMMON/arch.env' > run_gcm.sh
echo "./gcm_${dim}_phy${physics}_b${bands}_seq.e > gcm.out 2>&1" >> run_gcm.sh
chmod u=rwx run_gcm.sh
echo Running gcm...
cat run_gcm.sh
./run_gcm.sh
echo "Bench testcase run in $rootdir/bench_${testcase}_${dim}_b${bands}/ using run_gcm.sh"
echo "Outputs are in gcm.out which ends with:"
tail gcm.out
