#!/bin/bash
#$ -S /bin/bash
#$ -N Vasp_PU3
#$ -cwd 
#$ -V
#$ -o Vasp_para.batch-log
#$ -j y
#$ -q r410lin24ibcourt
#$ -pe mpi32 32


echo "============================================================================================="
echo "=                                                                                           ="
echo "=                        Vasp Parallel with unique machine                                  ="
echo "=                                                                                           ="
echo "=                           `date`                                          ="
echo "=                                                                                           ="
echo "============================================================================================="
HOMEDIR=$SGE_O_WORKDIR
SCRATCHDIR=`echo $HOMEDIR | awk -F "/" '{$2="scratch"; for(j=2;j<=NF;j++) {printf("/%s",$j);} print ""} ' `

echo "SCRATCHDIR=$SCRATCHDIR"

#Iter is the index for storing files as POSCAR_runXX
Iter=1
echo $Iter > Path.iter

######################################
#
# you might have to change the following variables
#
######################################
#
# Name of the Path Input file
#
Job=Test_Vasp_Para
#
#
# Where is Path.exe ??
#
PathExe=~/Programs/optnpath/src/Path.exe
#
# Where is VASP ?
#
export VASPDIR=~/Programs/VASP
export VASPEXEC=VASP4635_R410_STD
#
# Whre is mpirun ?
#
export MPIDIR=/softs/openmpi-1.4.1-intel/
export MPIRUN=$MPIDIR/bin/mpirun
#
#
# Machine where the files are
#
RUNNINGMACHINE=r410comp1-pub

# Some libraries... 
#
#For intel 11.1.069
source /softs/intel/v11.1.069/bin/intel64/ifortvars_intel64.sh
export LD_LIBRARY_PATH=/softs/fftw/2.1.5/ps-gb/lib:$LD_LIBRARY_PATH:/usr/lib
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/softs/intel/v11.1.069/mkl/lib/em64t/:$MPIDIR/lib/:/softs/intel/v11.1.069/lib/intel64
export LANG=C
#
#Usually nothing has to be changed after this line
#
#################################################

#
# Machinefile
#
HOSTFILE=$TMPDIR/machines


#################################
#
#! we create the 00, 01... and 0x directorires
# First we get the number of images in the INCAR file:
NbIm=`grep -i IMAGES INCAR | awk -F"=" '{n=$2*1+1; print n}' `
#
#
#################################
#
# We go to the Work Directory
cd $HOMEDIR

# A small test to see if everything matches
NbImP=` sed 's/,/^M/g' ${Job}.path | grep -i ngeomf | awk -F"=" '{n=$2*1-1; print n}' `
if [ $NbImP -ne $NbIm ]; then
 echo "WARNING WARNING WARNING WARNING WARNING WARNING"
 echo "IMAGES in INCAR and NGeomF in " ${Job}.path
 echo "Do Not Match... problems might be expected..."
 echo "Check it !!!"
 echo "WARNING WARNING WARNING WARNING WARNING WARNING"
fi

if [ $NbIm -le 9 ]; then
 Pref="0"
else
 Pref=""
fi

cp $HOSTFILE  $HOMEDIR/tmp
cp $PE_HOSTFILE $HOMEDIR/local_PE_HOSTFILE
Master="`head -1 $HOSTFILE`"
echo $Master > $HOMEDIR/Master

FUniq=`which uniq`
Uniq=${FUniq:-"sort -u"}
$Uniq $HOSTFILE > $HOMEDIR/machines_unique
grep -v $Master $HOMEDIR/machines_unique > $HOMEDIR/machines_other


#### We create the directories and copy files to other machines
for server in `cat $HOMEDIR/machines_other`
do
#### We create the images directory on all nodes
  for n in `seq -w 0 $NbIm`
  do
    ndir=$Pref$n
    ssh $server mkdir -p ${SCRATCHDIR}/${ndir}
  done

#### we copy the Vasp executable to all nodes
   scp ${RUNNINGMACHINE}:${VASPDIR}/${VASPEXEC} $server:${SCRATCHDIR}/${VASPEXEC}

#### we copy the files to all nodes
   for FILE in INCAR KPOINTS POTCAR 
   do
     scp $RUNNINGMACHINE:$HOMEDIR/$FILE $server:${SCRATCHDIR}/.
   done

done

#### We create the directories and copy files on Master
for n in `seq -w 0 $NbIm`
do
  ndir=$Pref$n
  mkdir -p ${SCRATCHDIR}/${ndir}
  mkdir -p ${HOMEDIR}/${ndir}
done

#### we copy the Vasp executable to Scratch
cp ${VASPDIR}/${VASPEXEC} ${SCRATCHDIR}/${VASPEXEC}

#### we copy the files to SCRATCHDIR
for FILE in INCAR KPOINTS POTCAR
do
  cp $HOMEDIR/$FILE ${SCRATCHDIR}/.
done


# ###########################
#
#  We create the 'VaspExe' file that Path will use to run the
# actual VASP calculations of E and forces
#
#############################
# we test if we run on one machine (ie only Master or on many)
NOther=`wc -l  $HOMEDIR/machines_other | awk '{print $1}'`
if [ $NOther -ge 1 ]; then
cat << EOF > ./RunVasp
#!/bin/bash

#set -x
HOMEDIR=$HOMEDIR
SCRATCHDIR=$SCRATCHDIR
Pref=$Pref

#### We copy files to other machines
for server in \`cat \$HOMEDIR/machines_other\`
do
  for n in \`seq -w 0 $NbIm\`
  do
    ndir="$Pref\$n"
# we copy the POSCAR file
    scp \$HOMEDIR/\${ndir}/POSCAR \$server:\${SCRATCHDIR}/\${ndir}/.
  done
done

#### We copy files on Master
for n in \`seq -w 0 $NbIm\`
do
  ndir="$Pref\$n"
# we copy the POSCAR file
  cp \$HOMEDIR/\${ndir}/POSCAR \${SCRATCHDIR}/\${ndir}/.
done

cd \$SCRATCHDIR

$MPIRUN -v -prefix $MPIDIR -mca pls_rsh_agent "ssh" -mca btl openib,self -np $NSLOTS \${SCRATCHDIR}/${VASPEXEC} > \${SCRATCHDIR}/out

Iter=\`cat \$HOMEDIR/Path.iter\`
RUNNEW=run\${Iter}

#### We copy files from other machines
for server in \`cat \$HOMEDIR/machines_other\`
do
  for n in \`seq -w 0 $NbIm\`
  do
    ndir="$Pref\$n"
    for FILE in  OUTCAR POSCAR OSZICAR XDATCAR CONTCAR
    do
      scp \$server:\${SCRATCHDIR}/\$ndir/\$FILE \$HOMEDIR/\$ndir/\${FILE}_\${RUNNEW}
      cp \$HOMEDIR/\$ndir/\${FILE}_\${RUNNEW}  \$HOMEDIR/\$ndir/\${FILE}
    done
  done
done

#### We copy files on Master
for n in \`seq -w 0 $NbIm\`
do
  ndir=$Pref\$n
  for FILE in  OUTCAR POSCAR OSZICAR XDATCAR CONTCAR
  do
   cp \${SCRATCHDIR}/\$ndir/\$FILE \$HOMEDIR/\$ndir/\${FILE}_\${RUNNEW}
   cp \$HOMEDIR/\$ndir/\${FILE}_\${RUNNEW}  \$HOMEDIR/\$ndir/\${FILE}
  done
done

cp \${SCRATCHDIR}/out  \$HOMEDIR/out_\${RUNNEW}

let Iter=Iter+1
echo \$Iter > \$HOMEDIR/Path.iter

cd \$HOMEDIR
EOF
else
# We have only one node, so that everything is store on master
cat << EOF > ./RunVasp
#!/bin/bash

#set -x

HOMEDIR=$HOMEDIR
SCRATCHDIR=$SCRATCHDIR
Pref=$Pref

cd \$SCRATCHDIR
# We copy files from HOMEDIR to SCRATCHDIR
for n in \`seq -w 0 $NbIm\`
do
  ndir=$Pref\$n
  cp \$HOMEDIR/\$ndir/POSCAR \${SCRATCHDIR}/\$ndir/POSCAR
done

$MPIRUN -v -prefix $MPIDIR -mca pls_rsh_agent "ssh" -mca btl openib,self -np $NSLOTS \${SCRATCHDIR}/${VASPEXEC} > \${SCRATCHDIR}/out

Iter=\`cat \$HOMEDIR/Path.iter\`
RUNNEW=run\${Iter}


for n in \`seq -w 0 $NbIm\`
do
  ndir=$Pref\$n
  for FILE in  OUTCAR POSCAR OSZICAR XDATCAR CONTCAR
  do
   cp \${SCRATCHDIR}/\$ndir/\$FILE \$HOMEDIR/\$ndir/\${FILE}_\${RUNNEW}
   cp \${SCRATCHDIR}/\$ndir/\$FILE \$HOMEDIR/\$ndir/\${FILE}
  done
done
cp \${SCRATCHDIR}/out  \$HOMEDIR/out_\${RUNNEW}

let Iter=Iter+1
echo \$Iter > \$HOMEDIR/Path.iter

cd \$HOMEDIR
EOF
fi
chmod u+x ./RunVasp

###############################
#
# We launch PATH
#
###############################
ln -fs ${PathExe} .

./Path.exe ${Job}.path > ${Job}.out 2> ${Job}.err
 
#### We delete SCRATCHDIR on all machines
for server in `cat $HOMEDIR/machines_other`
do
 ssh $server rm -rf ${SCRATCHDIR}
done

rm -rf ${SCRATCHDIR}
