#!/bin/bash
# Author: Jeff Comer <jeffcomer at gmail>

if [ $# -ne 2 -a $# -ne 3 ]
then
  echo "Usage: $0 jobName config.namd [dependJobName]"
  exit
fi

namdDir=/homes/jeffcomer/Software/NAMD_2.10_Linux-x86_64-multicore

jobName=$1
namd=$2


# Set the SGE options.
out=$jobName.qsub
echo '#!/bin/bash' > $out
echo "#$ -N $jobName" >> $out
echo "#$ -S /bin/bash" >> $out
echo "#$ -cwd" >> $out
echo "#$ -o $jobName" >> $out
echo "#$ -j y" >> $out
echo "" >> $out
echo "#$ -l h_rt=72:00:00" >> $out
echo "#$ -l mem=512M" >> $out
echo "#$ -l killable" >> $out
# Avoid mages and paladins
echo "#$ -l cpu_flags=*avx*" >> $out
echo "#$ -pe single 16-24" >> $out
echo "#$ -binding linear" >> $out
#echo "#$ -q '*@@elfs'" >> $out
# Add dependency.
if [ $# -eq 3 ]; then
    echo "Depends on $3"
    echo "#$ -hold_jid $3" >> $out
fi

# Check for the log.
log=${namd%.*}.log
if [ -f $log ]; then
    echo "ERROR $log already exists"
    exit
fi


# Host files and mpirun.
echo "" >> $out
echo 'cd $SGE_O_WORKDIR' >> $out
echo 'echo -n "" > host.$JOB_ID'  >> $out
echo ""  >> $out
echo "if [ ! -f $log ]; then" >> $out
echo "$namdDir/namd2 +p \$NSLOTS +isomalloc_sync $namd &> $log"  >> $out
echo "fi" >> $out
echo "Submitted $jobName $namd"

sleep 0.2
qsub $out
