#!/bin/bash
# use -x option for debug

# NOTE: For users who use this script first time
#   DO MIND TO Check '###?????###' sections and '#******** IMPORTANT *********' lines

HostName=`hostname`

#####???????????????#########################################
# EMail configuration: Edit  for your e-mail
#####???????????????#########################################
#******** IMPORTANT *********
DoSendMail=0
Title=`pwd`
Title=${Title##*/}
EMail=
SMTPServer=
Domain=
MailerName=SendMail.pl:${ThisScript}.sh
From=$EMail

#####???????????????#########################################
# Parallelization configurations: Edit for your PC
#####???????????????#########################################
#******** IMPORTANT *********
if [ "$HostName" = "csrv7" -o "$HostName" = "csrv8" ]; then
  nCPU=16
  NPAR=4
else
  nCPU=16
  NPAR=16
#  NPAR=4
fi
#KPAR=4
nCPUForMKL=1
MKL_NUM_THREADS=1

#==========================================
# Define programs: Usually no need to edit
#==========================================
# Remote control daemon
rsysd="perl $HOME/bin/Perl/rsys/rsysdaemon.pl"

# Directories
nCore=16
MPIRun=mpirun
PerlPATH=/usr/bin/perl
PythonPATH=python

QERoot=$HOME/espresso/bin
QEPerlDir=$TkPerlDir/QE

#CMD=$QERoot/pw.x
#CMD="$MPIRun -machinefile hosts -n $nCore $QERoot/pw.x"
CMD="$MPIRun -n $nCore $QERoot/pw.x"

VASPDir=$TkPerlDir/VASP
VASPScriptDir=$VASPDir/script
export "VASPplCMD=$PerlPATH $VASPDir/VASP.pl"

# Utitlities
TEE=$HOME/bin/ktee


#====================================================
# Initialization: No need to edit
#====================================================
ThisScript=$0
BaseDir=`pwd`
OriginalDir=$BaseDir
WorkDir= 
ARGDIR=$BaseDir

SampleName=$1
if [ "$SampleName" = "" ]; then
	echo "Usage: DoPWSCF.sh SampleName"
	echo "Usage: DoPWSCF.sh SampleName init"
	echo "Usage: DoPWSCF.sh scratch"
	exit;
fi
Action=$2
Arg1=$3
Arg2=$4
Arg3=$5
Arg4=$6

if ["$SampleName" = "scratch" ]; then
	Action=scratch
fi

#====================================================
# Invoke remote control daemon: No need to edit
#====================================================
$rsysd

#####???????????????#########################################
#####???????????????#########################################
#####???????????????#########################################
# MakeCIF parameters: Read carefully the 'IMPORTANT' lines and edit
#####???????????????#########################################
#####???????????????#########################################
#####???????????????#########################################
#******** IMPORTANT *********


#####???????????????#########################################
# Tasks: Choose tasks as you like
#####???????????????#########################################
#Choose from '|FindPP|MakeFilesFromCIF|MD|VCMD|VCRelaxRough|VCRelax|DFTSCF|SCF
#             |DOS|Band|EffectiveMass|ElectronDensity|FermiSurface|Phonon|Phonopy|IR|Raman'
StopAfter=

# Set SkipIfDirectoryExists=1 if you do not want to repeat finished tasks
SkipIfDirectoryExists=1

FindPP=0

BackUpOriginal=1

MakeFilesFromCIF=1
  CIFFile=auto
#scf nscf relax vc-relax md phonon
  Function=vc-relax
#USPP NC PAW SL 1/r
  PPType=USPP
#LDA SLA PZ PBE PBESOL LYP B88 P86 BLYP PW TPSS GGC GGX NOG NOGC NOGX PBC PBX PSC PSX
  Functional=PBE
#All, Selected, No
  PPCopyMode=Selected
  aKProduct=1.5
  ecutwfc=x1.0,30.0
  ecutrho=x1.0,140.0
  nbnd=x1.2
  SpinPolarized=1
DoMD=0
DoVCRelaxRough=0
DoVCRelax=1
DoSCF=0
CalculateBand=0
# Use *.klist file to plot band, specify 'File'
  BandKPoints1Common=File
  #BandKPoints1Common=XG
CalculateEffectiveMass=0
CalculateElectronDensity=0
CalculateFermiSurface=0
CalculatePhonon=0
CalculateIR=0
CalculateRaman=0
MakeSummary=1


#####???????????????#########################################
# MakeCIF
#####???????????????#########################################
CMDMakeCIF="perl $QEPerlDir/QE.pl --Action=MakeInputFiles --PPType=$PPType --Functional=$Functional --PPCopyMode=$PPCopyMode --Function=$Function --UseBravaisLattice=1 --UseCELLDM=1 --aKProduct=$aKProduct --ecutrho=$ecutrho --ecutrho=$ecutrho --nbnd=$nbnd --SpinPolarized=$SpinPolarized --DebugMode=0 $SampleName.cif $SampleName.pwin"

#############################################################################
#############################################################################
# No need to edit below
#############################################################################
#############################################################################

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

	if [ "$DoSendMail" = "1" -a "$EMail" != "" ]; then
		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"
	fi
}

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
}

#====================================
# Set command line parameters
#====================================
echo ' '
echo '================================================================'
echo '  Change parameters from command line arguments'
echo '================================================================'
while [ $# -gt 0 ]
do
  ARG=$1
  Val=${ARG#*=}
  Key=${ARG%%=*}
  shift
  echo Change parameter $Key to $Val
  eval `echo $Key=$Val`
done

#====================================
# Show help
#====================================
if [ "$Action" = "help" ]; then
	echo DoPWSCF.sh [init|scratch|super|help]
	echo
	exit
fi

#====================================
# Find Pseudopotential files
#====================================
if [ "$FindPP" = "1" ]; then
	perl $QEPerlDir/QE.pl --Action=FindPP --PPType=$PPType --Functional=$Functional --DebugMode=1 $SampleName.cif
fi

if [ "$StopAfter" = "FindPP" ]; then
	exit;
fi

#====================================
# Make CIF
#====================================
if [ "$Action" = "init" ]; then
	echo ' '
	echo '================================================================'
	echo "  Make Input Files from CIF [$CIFFile]"
	echo '================================================================'
	if [ "$CIFFile" = "auto" -o -f $CIFFile ]; then
		echo
	else
		echo Error: [$CIFFile] does not exist.
		exit
	fi
	echo run [$CMDMakeCIF]
	$CMDMakeCIF
	exit;
fi

if [ "$Action" = "scratch" ]; then
	echo ' '
	echo '================================================================'
	echo "  Restore initial files from Original and clean up"
	echo '================================================================'
	chmod -w DoPWSCF.sh
	rm -rif MD VCRelax* DFTSCF SCF DOS Band* Mass* eDensity Phonon* IR* Raman*
	rm *
	chmod +w DoPWSCF.sh
	mv Original/* .
	rm -rif Original
	rm *-Primitive.cif
	exit;
fi

if [ "$Action" = "super" ]; then
	echo ' '
	echo '================================================================'
	echo "  Make Supercell from CIF [$CIFFile]"
	echo '================================================================'
	cmd="$VASPDir/MakeStructureModel.pl --Action=shift --Shift=0,0,0 --OutputFile=supercell${Arg2}x${Arg3}x${Arg4}.cif $Arg1:$Arg2,$Arg3,$Arg4"
	echo run [$cmd]
	if [ "$Arg4" = "" ]; then
		echo usage: DoPWSCF.sh super CIF_FileName nx ny nz
		exit
	fi

	$cmd

	exit;
fi

if [ "$MakeFilesFromCIF" = "1" -a "$CMDMakeCIF" != "" ]; then
	echo ' '
	echo '================================================================'
	echo "  Make Input Files from CIF [$CIFFile]"
	echo '================================================================'
	if [ "$CIFFile" = "auto" -o -f $CIFFile ]; then
		echo
	else
		echo Error: [$CIFFile] does not exist.
		exit
	fi
	echo run [$CMDMakeCIF]
	$CMDMakeCIF
fi

if [ "$StopAfter" = "MakeFilesFromCIF" ]; then
	exit;
fi

#====================================
# Send EMail
#====================================
SendMail "$EMail" "$SMTPServer" "$MailerName" "$Domain" "$From" \
	 "$Title" "$HostName: $Title started"

#====================================
# Backup to Original directory
#====================================
if [ "$BackUpOriginal" = "1" ]; then
	BackupDir=Original
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		echo ' '
		echo '================================================================'
		echo "  Backup original files to ./$BackupDir"
		echo '================================================================'
		mkdir $BackupDir
		cp {*.sh,hosts,*.pwin} $BackupDir > /dev/null
		cp {*.KPOINTS,*.klist,*.mass} $BackupDir > /dev/null
		cp {*.cif,*.CIF,*.pl,*.ini} $BackupDir > /dev/null
		cp -r PP $BackupDir > /dev/null
	fi
fi


$CMD < $SampleName.pwin | tee $SampleName.pwout

perl $QEPerlDir/QE.pl --Action=MakeCIFFilesFromOutput --DebugMode=0 $SampleName.pwin $SampleName.pwout $SampleName-initial.cif $SampleName-final.cif

perl $QEPerlDir/QE.pl --Action=MakeXSF --nLastStep=-1 --nOutputInterval=1 --iAvrFirstStep=0 --iAvrLastStep=-1 --DebugMode=0 $SampleName.pwin $SampleName.pwout $SampleName.xsf

#perl $QEPerlDir/QE.pl --Action=UpdateInput --DebugMode=0 $SampleName.pwin $SampleName.pwout $SampleName.pwin.new
