#!/bin/bash
#set -vx
# Default options
#
#
#
date
#### 1  Set up the compiling options
#### Define some directories
submitdir=$( pwd )
modipsl=$submitdir/../..
arch_path=$submitdir/ARCH 

#### Set default options 
# Optimization mode
# optmode=prod/dev/debug
optmode=prod
# Resolution of LMDZ in regular mode
regular_latlon=yes
resol_atm_3d=144x142x79
# Also compile ce0l subprogram to LMDZ (y/n)
ce0l=n

optchimie=NMHC_AER_S
#recompilation de inca seul ou de tous les modeles
clean_inca=""
full_flag=""

# choose radiative code compilation option 
rad=rrtm
opt_rad=""


# fcm_arch
fcm_arch=default
# Default values to be overritten
parallel=mpi_omp
export fcm_arch parallel xios

# Default netcdf_lib is used for XIOS but can be change by argument
netcdf_lib=""

# Output text file for compilation of each component
datestr=`LC_ALL=C date +"%Y%m%dT%H%M"`
outfile=$submitdir/out_compile_lmdzorinca.$datestr
echo > $outfile
echo; echo "Text output from compilation will be stored in file out_compile_lmdzorinca.$datestr"; echo 

#### Read arguments 
# Loop over all arguments to modify default set up
while (($# > 0)) ; do
    case $1 in
	"-h") cat <<fin

########################################################################
# Usage of the script compile_lmdzorinca.sh
#
########################################################################

./compile_config [Options] 

Options: -full, -regular_latlon, -chimie, -clean_inca, -debug, -dev, -prod(default)

Example 1: Default compilation of LMDZ-ORCHIDEE-INCA  with XIOS and IOIPSL - NMHC_AER_S / 96x95x39 
./compile_lmdzorinca.sh

Example 2: Compilation with a chosen chemistry, for example DUSS  (default: NMHC_AER_S)
./compile_lmdzorinca.sh -chimie DUSS 

Example 3: Compile in debug mode  - in this case you need to modify Optmode in config.card 
./compile_lmdzorinca.sh -debug

Example 4: Default compilation with full recompilation of all components
./compile_lmdzorinca.sh -full

Example 5: Default compilation with recompilation of inca model only 
./compile_lmdzorinca.sh -clean_inca

Example 6: Compilation of LMDZ in regular lat-lon for other dimensions (default: 96x95x39) 
The dimension can be changed to any other 3d dimension.
./compile_lmdzorinca.sh -regular_latlon 144x142x79 

Example 7: choose radiative schema for LMDZ (oldrad/rrtm/ecrad). Default is rrtm
./compile_lmdzorinca.sh -rad ecrad


fin
	    exit;;

	"-parallel")
	    parallel=$2 ; shift ; shift ;; 
	
	"-arch")
	    fcm_arch="$2" ; shift ; shift ;;
	
	"-xios")
	    xios="$2" ; shift ; shift ;;
	
	"-optmode")
	    optmode=$2 ; shift ; shift ;;

	"-debug")
	    optmode=debug ; shift ;;

	"-dev")
	    optmode=dev ; shift ;;

	"-prod")
	    optmode=prod ; shift ;;

	"-ce0l")             
	    ce0l=y ; shift ;;

	"-rad")        
	    rad=$2; shift ; shift;;

	"-regular_latlon")
	    regular_latlon=yes ;
	    resol_atm_3d=$2 ; shift ; shift ;;
	
	"-full")
	    full_flag="-full"; shift ;;

	"-clean_inca")
	    clean_inca="-clean"; shift ;;
	
        "-netcdf_lib_seq")
            netcdf_lib="--netcdf_lib netcdf4_seq"; shift ;;

	"-chimie") 
	    echo $2; 
	    optchimie=$2; shift ; shift;;

	*)
	    echo "unknown option "$2" , exiting..."
	    exit 
    esac
done

echo "Following arguments are set in current compiling:" >> $outfile 
echo "   optmode = $optmode, parallel = $parallel, fcm_arch = $fcm_arch, full_flag=$full_flag regular_latlon=$regular_latlon" >> $outfile 
echo "   ce0l=${ce0l}" >> $outfile 
echo "   chimie = $optchimie, clean_inca = ${clean_inca}" 
echo >> $outfile

### Read host dependent default values
### These variables will not be changed if they were set as argument
###./host.sh $host
# Later : Following lines should be set in host.sh file
# begin host.sh
if [ $fcm_arch == default ] ; then
    # Find out current host and source specific paths and commands for the host
    case $( hostname -s ) in
        jean-zay*)
            fcm_arch=X64_JEANZAY;;
        irene170|irene171|irene190|irene191|irene192|irene193)
            fcm_arch=X64_IRENE;;
        irene172|irene173|irene194|irene195)
            fcm_arch=X64_IRENE-AMD;;
	asterix*|obelix*)
	    fcm_arch=ifort_LSCE;;
	ciclad*|climserv*)
	    fcm_arch=ifort_CICLAD;;
	*)
	    echo Current host is not known. You must use option -arch to specify which architecuture files to use.
	    echo Exit now.
	    exit
    esac
fi

# Set a link to arch.env if arch-${fcm_arch}.env file exist for current fcm_arch.
# The link arch.env is also set in config.card and will be used by libIGCM to ensure the same running environnement.
if [ -f ARCH/arch-${fcm_arch}.env ] ; then
    echo >> $outfile
    echo "The file ARCH/arch-${fcm_arch}.env will be used for the compilation of each component"
    rm -f ARCH/arch.env
    ln -s arch-${fcm_arch}.env ARCH/arch.env
fi

#### 2 Do the compilation 
## 2.1 Compile ioipsl
cd $modipsl/modeles/IOIPSL
echo; echo "NOW COMPILE IOIPSL"
echo >> $outfile ; echo " NOW COMPILE IOIPSL"   >> $outfile 

# Check if compilation with fcm is included in IOIPSL
if [ ! -f makeioipsl_fcm ] ; then
  echo "The file makeiopsl_fcm do not exist. Probably this is not the right version of IOIPSL."
  echo "Version of IOIPSL with fcm compilation is needed to compile with this script. Stop now."
  exit
fi

echo ./makeioipsl_fcm -$optmode -parallel -arch ${fcm_arch} -arch_path $arch_path -j 8 $full_flag   >> $outfile 
     ./makeioipsl_fcm -$optmode -parallel -arch ${fcm_arch} -arch_path $arch_path -j 8 $full_flag   >> $outfile 2>&1
# Test if compiling succeded 
if [[ $? != 0 ]] ; then 
    echo "THERE IS A PROBLEM IN IOIPSL COMPILATION - STOP"
    exit
fi

## 2.2 Compile xios
cd $modipsl/modeles/XIOS
echo; echo "NOW COMPILE XIOS"
echo >> $outfile ; echo " NOW COMPILE XIOS"   >> $outfile 
echo ./make_xios --$optmode --arch $fcm_arch --arch_path $arch_path ${netcdf_lib} --job 4 $full_flag   >> $outfile 
     ./make_xios --$optmode --arch $fcm_arch --arch_path $arch_path ${netcdf_lib} --job 4 $full_flag   >> $outfile 2>&1
# Test if compiling succeded 
if [[ $? != 0 ]] ; then 
    echo "THERE IS A PROBLEM IN XIOS COMPILATION - STOP"
    exit
fi
# Move executables to modipsl/bin
if [ -f $modipsl/modeles/XIOS/bin/xios_server.exe ] ; then 
    mv $modipsl/modeles/XIOS/bin/xios_server.exe $modipsl/bin/xios_server_${optmode}.exe
else
    echo "THERE IS A PROBLEM IN XIOS COMPILATION EXECUTABLE MISSING - STOP"
    exit
fi


## 2.3 Compile orchidee
cd $modipsl/modeles/ORCHIDEE
echo; echo "NOW COMPILE ORCHIDEE"
echo >> $outfile ; echo " NOW COMPILE ORCHIDEE"   >> $outfile 

echo 	./makeorchidee_fcm -j 8 -xios -parallel $parallel -$optmode -arch ${fcm_arch} -arch_path $arch_path $full_flag -driver   >> $outfile 
        ./makeorchidee_fcm -j 8 -xios -parallel $parallel -$optmode -arch ${fcm_arch} -arch_path $arch_path $full_flag -driver    >> $outfile 2>&1
# Test if compiling finished
if [[ $? != 0 ]] ; then
    echo "THERE IS A PROBLEM IN ORCHIDEE COMPILATION - STOP"
    exit
fi


## 2.4 Compile LMDZ and INCA for regular latlon configuration
if [ $regular_latlon = yes ] ; then

    cd $modipsl/modeles/INCA
    #compile INCA regulat lat_lon chimie librairy 
    echo; echo "NOW COMPILE INCA ${optchimie} on resolution = ${resol_atm_3d}"
    echo ./makeinca_fcm -chimie ${optchimie} -$optmode -xios -parallel mpi_omp  -j 8 -arch ${fcm_arch}  -arch_path $arch_path $full_flag $clean_inca >> $outfile 
         ./makeinca_fcm -chimie ${optchimie} -$optmode -xios -parallel mpi_omp  -j 8 -arch ${fcm_arch} -arch_path $arch_path  $full_flag $clean_inca >> $outfile 2>&1

    # Test if compiling finished
    if [[ $? != 0 ]] ; then
	echo "THERE IS A PROBLEM IN INCA COMPILATION - STOP"
	exit
    fi

    echo "Move inca.dat modipsl/bin"
    if [[ -f $modipsl/modeles/INCA/SIMULATIONS/$optchimie/inca.dat ]] ;  then  
	mv $modipsl/modeles/INCA/SIMULATIONS/$optchimie/inca.dat $modipsl/bin/inca_${resol_atm_3d}_${optmode}_${optchimie}.dat ;
#	cp $modipsl/bin/inca_${resol_atm_3d}.dat inca.dat; 
    else
	echo "THERE IS A PROBLEM IN INCA COMPILATION - STOP"
	exit	
    fi


    cd $modipsl/modeles/LMDZ
    # Compile LMDZ regular lat-lon exectuable
    echo; echo "NOW COMPILE LMDZ REGULAR LAT-LON MODE. Resolution = ${resol_atm_3d}"
    echo >> $outfile ; echo " NOW COMPILE LMDZ REGULAR LAT-LON MODE. Resolution = ${resol_atm_3d}"   >> $outfile 

    # Retrieve the final svn release number, needed for radiative code suffix of executable
    lmdzsvn=`svnversion . | egrep -o "[0-9]+"  | awk 'NR==1'`


    # Check if the compilation of LMDZ was previsouly interupted prematured. 
    # In that case, the files dimension.h and .lock exist. If the files exist, they are here removed to avoid makelmdz_fcm 
    # to ask question and wait for interactivly answer from the user.
    if [ -f libf/grid/dimensions.h ] || [ -f .lock ] ; then
        echo >> $outfile
        echo " WARNING!! The file LMDZ/libf/grid/dimension.h and/or the LMDZ/.lock exist. "   >> $outfile
        echo "           This means that the compilation is either currently on going in another terminal was previous interupted before the end."   >> $outfile
        echo "           The files dimension.h and .lock will now be removed. "   >> $outfile
        echo >> $outfile
        rm -f libf/grid/dimensions.h
        rm -f .lock
    fi

    # Need to define the proper option for radiative code compilation. By default, we use rrtm
    case $rad in
	oldrad) opt_rad="" ;;
	rrtm)   if [ $lmdzsvn -le 4185 ] ; then opt_rad="-rrtm true" ; else opt_rad="-rad rrtm" ; fi ;;
	ecrad)  opt_rad="-rad ecrad" ;;
	*) echo Only oldrad rrtm ecrad for rad option ; exit
    esac

    if [ $lmdzsvn -le 4185 -a $rad = "ecrad" ] ; then echo "ecrad only available for LMDZ rev starting with 4186 " ; exit ; fi




    echo ./makelmdz_fcm -d ${resol_atm_3d} -p lmd ${opt_rad} -$optmode -mem -parallel $parallel -io xios -v orchidee2.1 -chimie INCA -arch $fcm_arch -arch_path $arch_path -j 8 $full_flag gcm    >> $outfile 
         ./makelmdz_fcm -d ${resol_atm_3d} -p lmd ${opt_rad} -$optmode -mem -parallel $parallel -io xios -v orchidee2.1 -chimie INCA -arch $fcm_arch -arch_path $arch_path -j 8 $full_flag gcm    >> $outfile 2>&1
    # Test if compiling finished
    if [[ $? != 0 ]] ; then
	echo "THERE IS A PROBLEM IN LMDZ REGULAR LATLON COMPILATION - STOP"
	exit
    fi


    suffix=_${resol_atm_3d}_phylmd
    if [ $lmdzsvn -ge 4186 ] ; then suffix=${suffix}_${rad} ; fi

    # Find executable suffix
    if [ $parallel == seq ] || [ $parallel == none ] ; then
	suffix=${suffix}_seq_orch_inca
    else
	suffix=${suffix}_para_mem_orch_inca
    fi
    echo suffix = $suffix
    
    # Move executables to modipsl/bin folder
    echo "Move gcm.e and ce0l executable to modipsl/bin"
    if [ -f $modipsl/modeles/LMDZ/bin/gcm${suffix}.e ] ;  then 
         mv $modipsl/modeles/LMDZ/bin/gcm${suffix}.e $modipsl/bin/gcm_${resol_atm_3d}_${optmode}_${optchimie}.e ; 
    
    else
        echo "THERE IS A PROBLEM IN EXECUTABLE CREATION - STOP"
        exit

    fi

# Compile ce0l initialization program for LMDZ regular lat-lon exectuable
if [ $ce0l == y ] ; then
    echo; echo "NOW COMPILE CE0L OF LMDZ. Resolution = ${resol_atm}"
    echo >> $outfile ; echo " NOW COMPILE CE0L OF LMDZ. Resolution = ${resol_atm}"   >> $outfile 
    

    echo ./makelmdz_fcm -d ${resol_atm_3d} -p lmd ${opt_rad} -$optmode  -arch $fcm_arch -chimie INCA -arch_path $arch_path -j 8 $full_lmdz ce0l    >> $outfile 
         ./makelmdz_fcm -d ${resol_atm_3d} -p lmd ${opt_rad} -$optmode  -arch $fcm_arch -chimie INCA -arch_path $arch_path -j 8 $full_lmdz ce0l    >> $outfile 2>&1
    # Test if compiling finished
    if [[ $? != 0 ]] ; then
	echo "THERE IS A PROBLEM IN CE0L (LMDZ) REGULAR LATLON COMPILATION - STOP"
	exit
    fi

    
    # Move executables to modipsl/bin folder
    echo >> $outfile
    echo "Move ce0l.e executable to modipsl/bin" >> $outfile
    echo ls -lrt $modipsl/modeles/LMDZ/bin   >> $outfile
    ls -lrt $modipsl/modeles/LMDZ/bin  >> $outfile
    echo >> $outfile
    suffix=_${resol_atm_3d}_phylmd_seq.e
    echo ce0l suffix = $suffix

    if [ -f $modipsl/modeles/LMDZ/bin/ce0l${suffix} ] ;  then 
	mv $modipsl/modeles/LMDZ/bin/ce0l${suffix} $modipsl/bin/ce0l_${resol_atm}_${optmode}_${optchimie}.e
    else
	echo "ERROR ce0l${suffix} executable does not exist." 
	echo "THERE IS A PROBLEM IN CE0L (LMDZ) REGULAR LATLON COMPILATION - STOP"
	exit
    fi  
fi



fi


echo >>$outfile ; echo "ALL COMPILING FINISHED" >> $outfile
echo; echo "ALL COMPILING FINISHED"

if [ $optmode == 'debug' ] || [ $optmode == 'dev' ]; then 
    echo; echo "===================================================="
    echo; echo "DON'\T FORGET TO MODIFY Optmode IN cconfig.card" 
    echo; echo "Optmode="$optmode
    echo; echo "===================================================="
fi 

date
exit


