#/bin/bash -x

#============================
# Executables
#============================
nCPU=16
NPAR=4
nCPUForMKL=1
nCPUForMKLDOS=$nCPU
MKL_NUM_THREADS=1

MPIBIN=/usr/local/openmpi-intel131/bin
VASPPATH=/usr/local/VASP-5.3.5/bin/vasp
#VASPPATH=vasp
VASP="$MPIBIN/mpirun -machinefile hosts -np $nCPU $VASPPATH"

TEE=$HOME/bin/ktee
VASPDir=$TkPerlDir/VASP
export "VASPplCMD=/usr/bin/perl $VASPDir/VASP.pl"
export "PHONOPYplCMD=/usr/bin/perl $VASPDir/Phonopy.pl"

RelaxDOVASPCommand=DoVASP-Relax.sh
#PhonopyDOVASPCommand="mpirun -np 16 vasp"
PhonopyDOVASPCommand=$VASP

#============================
# Directories
#============================
HostName=`hostname`
BaseDir=`pwd`
RelaxDir=$BaseDir/Relax
DFPTDir=$BaseDir/DFPT
TemplateDir=$BaseDir/template
#KListDir=$TemplateDir
KListDir=$RelaxDir

#====================================
# Common definitions
#====================================
Title=`pwd`
Title=${Title##*/}
EMail=tkamiya@msl.titech.ac.jp
SMTPServer=lucid.msl.titech.ac.jp
Domain=lucid.msl.titech.ac.jp
MailerName=SendMail.pl:DoPhonopy.sh
From=$EMail

#=====================================
# Material and calculation condition
#=====================================
CIFFile=*.cif
KListFile=*.klist

UseConventionalCell=Yes
#Functional=PAW|PAW_PBE|PAW_LDA52|PAW_PBE52|GGA|US
Functional=PAW_PBE
#HybridFunctional=|HF|HSE06|PBE0
HybridFunctional=
SpinPolarized=No

Precision=Accurate
ENCUT=500
aKProduct=2.0
GammaOnly=0
EDIFF=1.0e-8
EDIFFG=-1.0e-4
KeepSymmetry=1
ISMEAR=-5
SIGMA=0.1

Interface=VASP
#Interface=VASPDFPT
nSupercell="2 2 2"
MeshPoints="8 8 8"
BandPoints=51
#fConversion=521.471
fConversion=

#============================
# Control flags
#============================
DoRelaxation=1
DoDOS=1
DoThermalProperties=1
DoPDOS=1
DoBand=1
DoSendMail=1

#============================
# Functions
#============================
function SendMail
{
	local EMail=$1
	local SMTPServer=$2
	local MailerName=$3
	local Domain=$4
	local From=$5
	local Title=$6
	local Subject=$7

	echo ' '
	echo '================================================================'
	echo "  Send notification e-mail to [$EMail]"
	echo '================================================================'
	perl $TkPerlDir/Mail/SendMail.pl --SMTPServer=$SMTPServer \
					 --MailerName=$MailerName --Domain=$Domain \
					 --WorkDir=`pwd` --HostName="$HostName" \
					 --To=$EMail --From=$From \
					 --Title=$Title --Subject="$Subject"
}

function PrintError()
{
	local Message1=$1
	local Message2=$2
	local DoExit=$3
	
	echo " "
	echo "Error: $Message1"
	echo $Message2

	if [ "$DoExit" = "1" ]; then
	  echo Stop.
	  exit
	fi
	
	return $DoExit
}

#==================================
# Run structure relaxation by VASP
#==================================
if [ $DoRelaxation ]; then
  if [ -d $RelaxDir ]; then
    echo Dir [$RelaxDir] exists.
    echo Skip structure relaxation.
  else
    echo Run structure relaxation in [$RelaxDir].

    mkdir $RelaxDir
    cp $TemplateDir/{INCAR,POSCAR,POTCAR,KPOINTS,hosts,$CIFFile,$KListFile} $RelaxDir
    sed -e "s/{nCPU}/$nCPU/" \
        -e "s/{NPAR}/$NPAR/" \
        -e "s/{nCPUForMKL}/$nCPUForMKL/" \
        -e "s/{nCPUForMKLDOS}/$nCPUForMKLDOS/" \
        -e "s/{MKL_NUM_THREADS}/$MKL_NUM_THREADS/" \
        -e "s/{Title}/$Title/" \
        -e "s/{EMail}/$EMail/" \
        -e "s/{SMTPServer}/$SMTPServer/" \
        -e "s/{Domain}/$Domain/" \
        -e "s/{MailerName}/$MailerName/" \
        -e "s/{From}/$From/" \
        -e "s/{UseConventionalCell}/$UseConventionalCell/" \
        -e "s/{Functional}/$Functional/" \
        -e "s/{HybridFunctional}/$HybridFunctional/" \
        -e "s/{SpinPolarized}/$SpinPolarized/" \
        -e "s/{Precision}/$Precision/" \
        -e "s/{ENCUT}/$ENCUT/" \
        -e "s/{EDIFF}/$EDIFF/" \
        -e "s/{EDIFFG}/$EDIFFG/" \
        -e "s/{KeepSymmetry}/$KeepSymmetry/" \
        -e "s/{aKProduct}/$aKProduct/" \
        -e "s/{GammaOnly}/$GammaOnly/" \
        -e "s/{ISMEAR}/$ISMEAR/" \
        -e "s/{SIGMA}/$SIGMA/" \
        $TemplateDir/$RelaxDOVASPCommand > $RelaxDir/$RelaxDOVASPCommand

    cd $RelaxDir
    chmod +x *.sh

    echo "Run [$RelaxDOVASPCommand]."
    $RelaxDOVASPCommand
  fi
fi

if [ -s $RelaxDir/VCRelax/POSCAR ]; then
  echo ' '
else
  if [ "$DoSendMail" = "1" -a "$EMail" != "" ]; then
    SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
    	     "$Title" "$HostName: $Title failed in Relaxation"
  fi
  PrintError "[$RelaxDir/VCRelax/POSCAR] does not exist." \
	     "Something wrong in the structural relaxation by VASP." 1
fi

#========================================================================
# Preprocess for phonopy
# creates disp.yaml  POSCAR  POSCAR-001  POSCAR-002  POSCAR-003  SPOSCAR
#========================================================================
cd $BaseDir
echo ' '
echo ' '

if [ "$Interface" = "VASPDFPT" ]; then
  echo "cp $RelaxDir/VCRelax/POSCAR ."
  cp $RelaxDir/VCRelax/POSCAR ./POSCAR-unitcell

  echo "phonopy -d --dim="$nSupercell" -c POSCAR-unitcell"
  phonopy -d --dim="$nSupercell" -c POSCAR-unitcell
else
  echo "cp $RelaxDir/VCRelax/POSCAR ."
  cp $RelaxDir/VCRelax/POSCAR ./POSCAR

  echo "phonopy -d --dim=\"$nSupercell\""
  phonopy -d --dim="$nSupercell"
fi

if [ -s $BaseDir/POSCAR-001 ]; then
  echo ' '
else
  if [ "$DoSendMail" = "1" -a "$EMail" != "" ]; then
    SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
    	     "$Title" "$HostName: $Title failed in phonony preprocess"
  fi
  PrintError "[$BaseDir/POSCAR-001] does not exist." \
	     "Something wrong in the phonopy preprocess." 1
fi

#============================
# Run vasp for hessian matrix / POSCAR-*
#============================
echo ' '
echo ' '
DirList=
if [ "$Interface" = "VASPDFPT" ]; then
  if [ -d $DFPTDir ]; then
        echo Dir [$DFPTDir] exists.
        echo Skip.
  else 
    mkdir $DFPTDir
    cp $TemplateDir/hosts $DFPTDir
    cp $RelaxDir/POTCAR $DFPTDir
    cp ./SPOSCAR $DFPTDir/POSCAR

    cd $DFPTDir
    $PHONOPYplCMD --Action=MakePhonopyINCAR --PhonopyTarget=$Interface --ENCUT=$ENCUT INCAR
    $PHONOPYplCMD --Action=MakeKPOINTSforSPOSCAR --aKProduct=$aKProduct KPOINTS

    echo Run [$PhonopyDOVASPCommand] to calculate hessian matrix.
    if [ "$DoSendMail" = "1" -a "$EMail" != "" ]; then
      SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
    	       "$Title" "$HostName: $Title DFPT VASP started"
    fi
    SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
   	       "$Title" "$HostName: $Title DFPT VASP started"
    $PhonopyDOVASPCommand

   if [ -s $DFPTDir/vasprun.xml ]; then
     echo ' '
    if [ "$DoSendMail" = "1" -a "$EMail" != "" ]; then
      SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
    	       "$Title" "$HostName: $Title DFPT VASP finished"
    fi
   else
     if [ "$DoSendMail" = "1" -a "$EMail" != "" ]; then
       SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
    	        "$Title" "$HostName: $Title DFPT VASP failed"
     fi
     PrintError "[$DFPTDir/vasprun.xml] does not exist." \
                "Something wrong in the DFPT calculation by VASP." 1
    fi
  fi
else
  for i in $(seq 1 10000)
  do
    cd $BaseDir

    Index=$(printf "%03d" $i)
    POSCARName=POSCAR-$Index

    if [ -f $POSCARName ]; then
      WorkDir=disp-$Index
      DirList="$DirList $WorkDir/vasprun.xml"

      if [ -d $WorkDir ]; then
        echo Dir [$WorkDir] exists.
        echo Skip.
        continue
      else 
        mkdir $WorkDir
        cp $TemplateDir/hosts $WorkDir
        cp $RelaxDir/POTCAR $WorkDir
        cp $POSCARName $WorkDir/POSCAR
      
        cd $WorkDir
        $PHONOPYplCMD --Action=MakePhonopyINCAR --PhonopyTarget=$Interface --ENCUT=$ENCUT INCAR
#        $PHONOPYplCMD --Action=MakeGOnlyKPOINTS KPOINTS
        $PHONOPYplCMD --Action=MakeKPOINTSforSPOSCAR --aKProduct=$aKProduct KPOINTS

        echo Run [$PhonopyDOVASPCommand in `pwd`]
        SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
                 "$Title" "$HostName: $Title ${i}-th FD VASP started"
        $PhonopyDOVASPCommand

        if [ -s $BaseDir/$WorkDir/vasprun.xml ]; then
          echo ' '
          if [ "$DoSendMail" = "1" -a "$EMail" != "" ]; then
            SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
                  "$Title" "$HostName: $Title ${i}-th FD VASP finished"
          fi
        else
          if [ "$DoSendMail" = "1" -a "$EMail" != "" ]; then
            SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
                  "$Title" "$HostName: $Title ${i}-th FD VASP failed"
          fi
          PrintError "[$BaseDir/$WorkDir/vasprun.xml] does not exist." \
                     "Something wrong in the finite displacement DFT calculation by VASP." 1
        fi
      fi
    else
      echo POSCAR [$POSCARName] does not exist.
      echo Break the loop.
      break
    fi
  done
fi

#===================================
# Run phonopy to make force matrix
#===================================
cd $BaseDir

echo ' '
echo ' '
if [ "$Interface" = "VASPDFPT" ]; then
  cp $DFPTDir/vasprun.xml .
  echo Run [phonopy --fc vasprun.xml] to create FORCE_CONSTANTS.
  phonopy --fc vasprun.xml

  if [ -s FORCE_CONSTANTS ]; then
    echo ' '
    else
      PrintError "[$BaseDir/FORCE_CONSTANTS] does not exist." \
                 "Something wrong in the force matrix calculation by phonopy." 1
  fi
else
  echo Run [phonopy -f $DirList].
  phonopy -f $DirList

  if [ -s FORCE_SETS ]; then
    echo ' '
    else
          PrintError "[$BaseDir/FORCE_SETS] does not exist." \
                     "Something wrong in the force matrix calculation by phonopy." 1
  fi
fi

#=============================================
# Run phonopy to calculate phonon properties
#=============================================
# DOS
if [ $DoDOS -eq 1 ]; then
  echo ' '
  echo Calculate Total DOS
  if [ -f mesh.conf ]; then
    echo 'mesh.conf exists. No update.'
  else
    Option="--Action=MakeMeshConf --PhonopyTarget=$Interface --fConversion=$fConversion \
    	    --CARDir=$RelaxDir/VCRelax"
    echo "Run [$PHONOPYplCMD $Option --nSupercell="$nSupercell" --MeshPoints="$MeshPoints" mesh.conf]."
    $PHONOPYplCMD $Option --nSupercell="$nSupercell" --MeshPoints="$MeshPoints" mesh.conf
  fi

  if [ "$Interface" = "VASPDFPT" ]; then
    echo "Run [phonopy -p -s --dim="$nSupercell" -c POSCAR-unitcell mesh.conf]."
    phonopy -p -s --dim="$nSupercell" -c POSCAR-unitcell mesh.conf
  else
    echo "Run [phonopy -p -s mesh.con]."
    phonopy -p -s mesh.conf
  fi
fi

# Thermal properties
if [ $DoThermalProperties -eq 1 ]; then
  echo ' '
  echo Calculate thermal properties
  if [ -f mesh.conf ]; then
    echo 'mesh.conf exists. No update.'
  else
# Do not use fConversion because the unit is fixed to THz and fConversion must be the default value.
    Option="--Action=MakeMeshConf --PhonopyTarget=$Interface --CARDir=$RelaxDir/VCRelax"
    echo "Run [$PHONOPYplCMD $Option --nSupercell="$nSupercell" --MeshPoints="$MeshPoints" mesh.conf]."
    $PHONOPYplCMD $Option --nSupercell="$nSupercell" --MeshPoints="$MeshPoints" mesh.conf
  fi

  if [ "$Interface" = "VASPDFPT" ]; then
    echo "Run [phonopy -t --dim="$nSupercell" -c POSCAR-unitcell mesh.conf]."
    phonopy -t --dim="$nSupercell" -c POSCAR-unitcell mesh.conf
  else
    echo "Run [phonopy -t mesh.con]."
    phonopy -t mesh.conf
  fi
fi

# PDOS
if [ $DoPDOS -eq 1 ]; then
  echo ' '
  echo Calculate Projected DOS
  if [ -f pdos.conf ]; then
    echo 'pdos.conf exists. No update.'
  else
    Option="--Action=MakePDOSConf --PhonopyTarget=$Interface --fConversion=$fConversion \
    	    --CARDir=$RelaxDir/VCRelax"
    echo "Run [$PHONOPYplCMD $Option  --nSupercell="$nSupercell" --MeshPoints="$MeshPoints" pdos.conf]."
    $PHONOPYplCMD $Option  --nSupercell="$nSupercell" --MeshPoints="$MeshPoints" pdos.conf
  fi

  if [ "$Interface" = "VASPDFPT" ]; then
    echo "Run [phonopy -p -s --dim="$nSupercell" -c POSCAR-unitcell pdos.conf]."
    phonopy -p -s --dim="$nSupercell" -c POSCAR-unitcell pdos.conf
  else
    echo "Run [phonopy -p -s pdos.conf]."
    phonopy -p -s pdos.conf
  fi
fi

# Band
if [ $DoBand -eq 1 ]; then
  echo ' '
  echo "Calculate phonon band"
  if [ -f band.conf ]; then
    echo 'band.conf exists. No update.'
  else
    Option="--Action=MakeBandConf --PhonopyTarget=$Interface --fConversion=$fConversion \
    	    --CARDir=$RelaxDir/VCRelax --KListDir=$KListDir --BandPoints=$BandPoints"
    echo "Run [$PHONOPYplCMD $Option --nSupercell="$nSupercell" band.conf]."
    $PHONOPYplCMD $Option --nSupercell="$nSupercell" band.conf
  fi

  if [ "$Interface" = "VASPDFPT" ]; then
    echo "Run [phonopy -p -s --dim="$nSupercell" -c POSCAR-unitcell band.conf]."
    phonopy -p -s --dim="$nSupercell" -c POSCAR-unitcell band.conf
  else
    echo "Run [phonopy -p -s band.conf]."
    phonopy -p -s band.conf
  fi
fi

