#!/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`

#====================================================
# Initialization: No need to edit
#====================================================
ThisScript=$0
BaseDir=`pwd`
OriginalDir=$BaseDir
WorkDir= 
ARGDIR=$BaseDir
ARG1=$ARGDIR/INCAR
Action=$1
Arg1=$2
Arg2=$3
Arg3=$4
Arg4=$5

#####???????????????#########################################
# EMail configuration: Edit  for your e-mail
#####???????????????#########################################
DoSendMail=0
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:${ThisScript}.sh
From=$EMail

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

# Directories
eHTunerDir=$HOME/eHtuner/eHtuner
EHDir=$HOME/eHtuner/yaehmop
EHScriptDir=$TkPerlDir/YAeHMOP

# Execute commands
PerlPATH=/usr/bin/perl
eHTunerPath=$eHTunerDir/eHtuner
BindPATH=$EHDir/tightbind_silent/bind
FitDOSPATH=$EHDir/tightbind_silent/utils/fit_dos
EHScriptCMD="$PerlPATH $EHScriptDir/YAeHMOP.pl"

BindInputFileName=bind.in
DBFileName=eht_parms.dat
EHDBPath=$EHScriptDir/$DBFileName

# Utitlities
TEE=$HOME/bin/ktee

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

#####???????????????#########################################
# Tasks: Choose tasks as you like
#####???????????????#########################################
#Choose from '|MakeFilesFromCIF|eHTuner|YAeHMOP'
StopAfter=

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

MakeFilesFromCIF=1
  CIFFile=auto
#UseConventionalCell={UseConventionalCell}
  UseConventionalCell=No
  #UseConventionalCell=Yes
  aKProduct=2.0

BackUpOriginal=1

DoeHTuner=1
DoYAeHMOP=0

MakeSummary=1
DeleteExtraFiles=1
DeleteLargeFiles=0

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

#====================================================
# MakeCIF command
#====================================================
CMDMakeCIF="$EHScriptCMD --Action=MakeInput --db= --KPOINTS= --IBZKPT= --aKProduct=$aKProduct --Output=$BindInputFileName $CIFFile"


#############################################################################
#############################################################################
# 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 DoEH.sh [init|help]
	echo
	exit
fi

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

	exit;
fi

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

	rm $DBFileName
	cp $EHDBPath .
	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 {$DBFileName,*.cif,*.CIF,*.KPOINTS,*.klist,IBZKPT,*.IBZKPT,*.in} $BackupDir > /dev/null
	fi
fi

#====================================
# eHtuner
#====================================
cd $BaseDir

if [ "$DoeHTuner" = "1" -a  "$BindPATH" != "" ]; then
	BackupDir=eHtuner
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		rm *.out

		echo ' '
		echo '================================================================'
		echo "  YAeHMOP run: [$BindPATH]"
		echo '================================================================'
		echo mkdir $BackupDir

		mkdir $BackupDir
		cp {INCAR,POSCAR,POTCAR,KPOINTS,OUTCAR,IBZKPT,DOSCAR,$DBFileName} $BackupDir > /dev/null

		cd $BackupDir
		$eHTunerPath eHparam $DBFileName gnuplot | $TEE `hostname`-MakeIn.out.txt

		$EHScriptCMD --Action=ModifyeHtunerInput eHparam.ini $BindPATH $FitDOSPATH
		cp eHparam.ini eHparam.original
		cp eHparam.ini.modified eHparam.ini

		$eHTunerPath eHparam $DBFileName gnuplot | $TEE `hostname`-eHtuner.out.txt
	fi
fi

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

#====================================
# YAeHMOP
#====================================
cd $BaseDir

if [ "$DoYAeHMOP" = "1" -a  "$eHTunerPath" != "" ]; then
	BackupDir=YAeHMOP
	if [ "$SkipIfDirectoryExists" = "1" -a -d $BackupDir ]; then
		echo "Dir [$BackupDir] exists."
		echo "Skip."
	else
		rm *.out

		echo ' '
		echo '================================================================'
		echo "  eHtuner run: [$eHTunerPath]"
		echo '================================================================'
		echo mkdir $BackupDir

		mkdir $BackupDir
		cp {$BindInputFileName,$DBFileName} $BackupDir > /dev/null

		cd $BackupDir
		$BindPATH $BindInputFileName | $TEE `hostname`.out.txt
		
		$EHScriptCMD --Action=MakeDOSCSV $BindInputFileName.out DOS.csv
	fi
fi

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



#====================================
# Clean up files
#====================================
cd $BaseDir

if [ "$DeleteExtraFiles" = "1" ]; then
	echo ' '
	echo '================================================================'
	echo "  Clean up files"
	echo '================================================================'
	rm eHtuner/{ref.DOS-temp,temp,eHparam.tmp} > /dev/null
fi


#====================================
# Make Summary
#====================================
if [ "$MakeSummary" = "1" ]; then
	echo ' '
	echo '================================================================'
	echo "  Make summary to Summarize.txt"
	echo '================================================================'
#	perl eHtuner/{ref.DOS-temp,temp,eHparam.tmp} ./ > Summarize.txt
fi

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

