#!/bin/bash

# Need LibSource dftd3 and 4

# Script to compile Castep 22.1

# If used with MKL FFT, one will probably need to add
# include 'mkl_dfti.f90'
# as first line of Source/Utility/fft.mkl.F90

set -e
declare -A opt

# Name of Fortran compiler (e.g. mpifort if COMMS=mpi)

FC=gfortran
#FC=/bin/true

# serial or mpi

COMMS=serial

# final name of executable

CASTEP=castep.serial

# Standard flags for Fortran compiler

# -DMKL is needed by license.F90, iff MKL is the maths library
# other options include -DFFTW and -DACML

# if you want OpenMP, add -fopenmp (Intel/GNU/AOCC)

# ifort
#FFLAGS='-g -convert big_endian -assume norealloc_lhs -diag-disable 8290 -diag-disable 8291 -DMKL'
# gfortran
FFLAGS='-g -fconvert=big-endian -fallow-argument-mismatch -DFFTW'

# Flag for making mod files only

# ifort, ifx, gfortran, AOCC
FFLAGS_MODULES=-fsyntax-only

# Flag for specifying module output directory

# ifort and AOCC
#MODULE_OUTDIR="-module"
# gfortran
MODULE_OUTDIR="-J"


# Additional optimisation flags

#FOPT=-O0
# ifort
#FOPT='-O3 -march=corei7-avx -axavx2'
# gfortran
FOPT='-O3 -mavx -fno-signed-zeros'

# Flag to get version from Fortran compiler. Blank if none
FC_VER=--version

# Files for which other optimisation flags should be used

#opt[firstd.f90]='-O2'
#opt[semp_disp_corr.f90]='-O2'
#opt[geometry_deloc_algor.f90]='-O2'
#opt[geometry_deloc_utils.f90]='-O2'
#opt[hamiltonian.f90]='-O2'
#opt[nlpot.f90]='-O2'
#opt[tssearch_utils.f90]='-O2'
# Uncomment next line for ifort
#opt[otfg_generate.f90]="${FOPT} -fp-model=consistent"
opt[fft.mkl.F90]="${FOPT} -qmkl=sequential"

# Extra flags for linking

#LDFLAGS='-static-intel'

# Extra libraries for linking (never need MPI libraries here in TCM)

# MKL
#LIBS='-qmkl=sequential'
# FFTW
LIBS='-llapack -lblas -lfftw3'

# Name(s) of FFT source files to use from Utility
#FFT='fft_gpfa.F90 fft.generic.F90'
 FFT='fft.fftw3.F90 fftw3_version.c'
# FFT='fft.acml.F90'
#FFT='fft.mkl.F90'

# Use SYSV stuff to accelerate MPI? Set to "true" or "false"
# Needs an MPI C compiler too if true

SYSV=false
CC=gcc
CFLAGS=

# Hints for customisation:
#
# FC=ifort
# FFLAGS='-convert big_endian -assume norealloc_lhs -diag-disable 8290 -diag-disable 8291'
# opt[firstd.f90]='-O2'
# Other useful flags: FOPT='-g -O0' for debug
#                          '-O3 -msse3' for optimised

# FC=openf90
# FFLAGS='-cpp -w -byteswapio'
# Other useful flags: FOPT='-g -O0' for debug
#                          '-O2' for optimised

# FC=gfortran
# FFLAGS='-fconvert=big-endian -frecord-marker=4 -ffree-line-length-none'
# Other useful flags: FOPT='-g -O0' for debug
#                          '-O3 -funroll-loops -msse3' for optimised

#
# End customisation
#

LIBS="${LIBS} libxcf90.a libxc.a libsymspg.a lib/libdlmg.a libdftd3.a libdftd4.a libmctc-lib.a"

if $SYSV && [ "$COMMS" = "mpi" ]
then
  CMS="FreeIPC.f90 FreeIPC_c.c comms.f90 comms.${COMMS}.F90"
else
  CMS="comms.f90 comms_threads.F90 comms.${COMMS}.F90"
  [ "$COMMS" = "mpi" ] && CMS="sleep.F90 $CMS"
  opt[comms.mpi.F90]="${opt[comms.mpi.F90-$FOPT]} -DNOSYSV"
fi

UTIL="constants.F90 trace.f90 ${CMS} io.F90 algor.F90 $FFT buildinfo.f90 
cml.dummy.F90 license.F90 bib.f90 spglib_f08.f90 plumed_wrapper.F90
memory.f90 f90wrap_stub.f90
SocketTools.F90 sockets.c csockets.c f90sockets.F90"

OTFG='../Fundamental/parameters.f90 xc_libxc.stub.f90 xc_kernels.f90 otfg_pspot.f90 otfg_basis.f90 
otfg_atom.f90 otfg_algor.f90 otfg_data.f90 ../Fundamental/cell.f90
otfg_io.f90 otfg_solvers.f90
otfg_scf.f90 otfg_pseudise.f90 otfg_generate.f90 otfg.f90'

FUND='basis_utils.f90 basis.f90
soc.f90 ion.f90 wave.f90
density.f90 pot.f90 dielectric_permittivity.f90 nlxc_basis.f90 local_basis.f90
free_atom.f90'

DISP='hirshfeld.f90 dftd_utils.f90 mbd_disp_corr.f90 xdm_disp_corr.f90
   dftd_d3.f90 dftd_d4.f90 semp_disp_corr.f90'

FUNC1='nlpot.f90 nlxc_utils.f90 hubbard.f90 multigrid_dlmg.f90 
locps.f90 xc.f90 model.f90 dm.f90 md_extrap.f90 api.f90 deltascf.f90 ewald.f90
hartree.f90 smeared_ions.f90 openbc_locps.f90 ncm_constraints.f90
locpot.f90 nlxc.f90 hamiltonian.f90 magres_utils.f90 secondd_symmetry.f90
thirdd_utils.f90 thirdd.f90 secondd.f90 tddft.f90 ion_ion.f90'


FUNC2='dftd.f90 firstd.f90 
implicit_solvent.f90 electronic.f90 
raman.f90 pair_pot.f90 polarisation.f90  phonon.f90 efield.f90 elf.f90 epcoupling.f90
geometry_deloc_utils.f90 geometry_deloc_algor.f90 md_pathint.f90
popn.f90 gap_hybrid.f90 md.f90 geometry.f90 paw_recon.f90 magres_efg.f90
magres_gtensor.f90 magres_hyperfine.f90 magres_jcoupling.f90
magres_nmr.f90 magres.f90 oep.f90 spectral.f90
thermodynamics.f90 tssearch_utils.f90 tssearch_algor.f90 tssearch_neb.f90
tssearch.f90 pair_pot_quip.stub.f90 xrd_sf.f90 elastic.f90
socketdriver.f90 castep.f90'

#
# Check arguments
#

quick=false
if [ "$1" = "-q" ]
then
  quick=:
  shift
  echo "Warning: dangerous quick compile requested"
fi

verbose=false
if [ "$1" = "-v" ]
then
  verbose=:
  shift
fi


if [ $# -ne 1 ]
then
  echo 'Usage: compile [-q] [-v] path/to/CASTEP-ver'
  echo '       compile clean'
  exit
fi

if [ "$1" = "clean" ]
then
  set +e
  rm *.o *.mod *.inc Makefile makefile.spglib
  rm -r lib lib64 cmake
  rm config.h config.log config.status lib* buildinfo_data.f90
  rm xc-info xc_version.h stamp-h1 xc-threshold
  rm -r testsuite include build maple pkgconfig scripts src platforms o pylibxc
  rm -r xc spg dftd3 dftd4
  exit
fi


SRC=$1/Source
[ ${SRC:0:1} != "/" ] && SRC="`pwd`/$SRC"


tot=`echo $UTIL $OTFG $FUND $FUNC1 $FUNC2 $DISP buildinfo castep | wc -w`
count=0
start_time=`date '+%s'`

function fcomp {
  count=`expr $count + 1`
  file=`basename $1`
  root=`basename $file .f90`
  root=`basename $root .F90`
  root=`basename $root .c`
  if $quick
  then
    if [ "$root".o -nt "$1" ]
    then
      echo "Skipping compilation of $file  ($count of $tot)"
      return
    fi
  fi
  echo "Compiling $file  ($count of $tot)"
  if expr match  "$1" '.*\.c$' > /dev/null
  then
    $CC $CFLAGS -c $1
  else
    $verbose && echo $FC $FFLAGS ${opt[$file]-$FOPT} -c $1
    $FC $FFLAGS ${opt[$file]-$FOPT} -c $1
  fi
}

if $quick
then
 :
else

# Worry about libs

#
# Worry about libxc
#

 here=`pwd`
 [ ! -d xc ] && mkdir xc
 cd xc
 ${SRC}/../LibSource/libxc-*/configure FC=${FC} --enable-fortran=yes --enable-shared=no --libdir=${here} --includedir=${here}/include --bindir=${here}
 make
 make install
 cd ..
 ln -sf include/libxc_funcs_m.mod
 ln -sf include/xc_f90_lib_m.mod
 ln -sf include/xc_f90_types_m.mod
 
#
# Worry about spglib
#

 [ ! -d spg ] && mkdir spg
 cd spg
 SPGLIB_SOURCE=`echo ${SRC}/../LibSource/spglib-1.*`
 sed 's/include/#include/' < ${SPGLIB_SOURCE}/Makefile > makefile.spglib
 [ ! -d lib64 ] && mkdir lib64
 make -f makefile.spglib SPGLIB_SOURCE=${SPGLIB_SOURCE} OBJ_EXTN=o AR=ar ARFLAGS=cr RM=rm
 cp lib64/libsymspg.a ..
 cd ..

 #
 # Worry about dl_mg
 #

 dl_mg_dir=`echo ${SRC}/../LibSource/dl_mg-*`
 
 if [ "$COMMS" = "mpi" ]
 then
     dl_mg_fflags="$FFLAGS -DMPI"
 else
     dl_mg_fflags="$FFLAGS"
 fi	

 [ ! -d platforms ] && mkdir platforms
 touch platforms/null.inc
 [ ! -d src ] && mkdir src
 ln -sf ${dl_mg_dir}/src/depend.mk src/depend.mk
 
 make -f ${dl_mg_dir}/Makefile \
      CASTEP_ROOT=${SRC}/../ MG_ROOTDIR=. PLATFORM=null \
      VPATH=${dl_mg_dir}/src: FC=$FC FFLAGS="$dl_mg_fflags"

 ln -sf ${dl_mg_dir}/src/dl_mg_common_params.inc

 #
 # Build mctc
 #

 MCTC_SOURCE=`echo ${SRC}/../LibSource/mctc-lib-*`
 [ ! -d mctc ] && mkdir mctc
 cd mctc
 make -f $MCTC_SOURCE/Makefile F90=$FC OBJ_EXTN="o" LIB_EXTN=a RANLIB="ranlib" LIBDIR=. SOURCEDIR=$MCTC_SOURCE/src_flat ROOTDIR=$MCTC_SOURCE/../.. FFLAGS_MODULES=$FFLAGS_MODULES MODULE_OUTDIR=$MODULE_OUTDIR LIBDIR=.. INCDIR=.. FFLAGS="$FFLAGS"

 cd ..

#
# Build simple-dftd3
#

 DFTD3_SOURCE=`echo ${SRC}/../LibSource/simple-dftd3-*`
 [ ! -d dftd3 ] && mkdir dftd3
 cd dftd3
 make -f $DFTD3_SOURCE/Makefile F90=$FC OBJ_EXTN="o" LIB_EXTN=a RANLIB="ranlib" LIBDIR=. SOURCEDIR=$DFTD3_SOURCE/src_flat ROOTDIR=$DFTD3_SOURCE/../.. FFLAGS_MODULES="$FFLAGS_MODULES -I.." MODULE_OUTDIR=$MODULE_OUTDIR LIBDIR=.. INCDIR=.. FFLAGS="$FFLAGS -I.."

 cd ..

#
# Build dftd4
#

 DFTD4_SOURCE=`echo ${SRC}/../LibSource/dftd4-*`
 [ ! -d dftd4 ] && mkdir dftd4
 cd dftd4
 make -f $DFTD4_SOURCE/Makefile F90=$FC OBJ_EXTN="o" LIB_EXTN=a RANLIB="ranlib" LIBDIR=. SOURCEDIR=$DFTD4_SOURCE/src_flat ROOTDIR=$DFTD4_SOURCE/../.. FFLAGS_MODULES="$FFLAGS_MODULES -I.." MODULE_OUTDIR=$MODULE_OUTDIR LIBDIR=.. INCDIR=.. FFLAGS="$FFLAGS -I.."

 cd ..
  
fi

#
# Build in Utility
#

for f in $UTIL
do
  fcomp ${SRC}/Utility/${f}
done

#
# Make buildinfo module
#

cat > buildinfo_data.f90 << EOF
submodule (buildinfo) buildinfo_data

! TCM-generated buildinfo module

contains
  module function get_build_info()
    type(build_info_type) :: get_build_info
    get_build_info = &
      build_info_type( &
        'git version unavailable',& ! GITVERSION
EOF
echo "   '${FOPT}',& ! BUILD_LEVEL" >> buildinfo_data.f90
cat >> buildinfo_data.f90 << EOF
   '',& ! MATHLIBS
EOF
echo "   '`echo $FFT | cut -d ' ' -f 1`',& ! FFT" >> buildinfo_data.f90
echo "   'Linux ${FC}',& ! PLATFORM" >> buildinfo_data.f90
echo "   '`date -R`',& ! DATE" >> buildinfo_data.f90
if [ -n "$FC_VER" ]
then
  cver=`${FC} ${FC_VER} | head -1`
  echo "   '$cver',& !COMPILER_VERSION" >> buildinfo_data.f90
else
  echo "   '',& !COMPILER_VERSION"  >> buildinfo_data.f90
fi
  echo "   '$COMMS',& !COMMS_VERSION" >> buildinfo_data.f90
cat >> buildinfo_data.f90 << EOF
'') !MATHLIB_VERSION
  end function get_build_info
end submodule buildinfo_data
EOF

fcomp buildinfo_data.f90


#
# Build in OTFG
#

for f in $OTFG
do
  fcomp ${SRC}/OTFG/${f}
done

#
# Build in Fundamental
#

for f in $FUND
do
  fcomp ${SRC}/Fundamental/${f}
done

#
# Build in Functional
#

for f in $FUNC1
do
  fcomp ${SRC}/Functional/${f}
done

#
# Build in Dispension
#

for f in $DISP
do
    fcomp ${SRC}/Dispersion/${f}
done

#
# Build more in Functional
#

for f in $FUNC2
do
  fcomp ${SRC}/Functional/${f}
done


#
# Make final executable
#

fcomp ${SRC}/main.f90

if $quick
then
  echo 'Linking after dangerous quick build'
else
  echo 'Linking'
fi

OBJ=`echo "$UTIL $OTFG $FUND $FUNC1 $DISP $FUNC2" | sed -e 's%\.\./[^/]*/%%g' -e 's/\.[fF]90/.o/g' -e 's/\.c /.o /g'`

$verbose && echo $FC -o $CASTEP $FFLAGS $FOPT $LDFLAGS main.o ${OBJ} ${LIBS}
$FC -o $CASTEP $FFLAGS $FOPT $LDFLAGS main.o ${OBJ} buildinfo_data.o ${LIBS}

end_time=`date '+%s'`

echo
echo "Total compile time: `expr $end_time - $start_time` s"
echo
