#!/bin/sh
#
# ========================================================================
#
# *
# * This file is part of MARS, the MAGIC Analysis and Reconstruction
# * Software. It is distributed to you in the hope that it can be a useful
# * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
# * It is distributed WITHOUT ANY WARRANTY.
# *
# * Permission to use, copy, modify and distribute this software and its
# * documentation for any purpose is hereby granted without fee,
# * provided that the above copyright notice appear in all copies and
# * that both that copyright notice and this permission notice appear
# * in supporting documentation. It is provided "as is" without express
# * or implied warranty.
# *
#
#
#   Author(s): Daniela Dorner  08/2006 <mailto:dorner@astro.uni-wuerzburg.de>
#
#   Copyright: MAGIC Software Development, 2000-2007
#
#
# ========================================================================
#
# This a script, which launches other scripts
#

source `dirname $0`/sourcefile
printprocesslog "INFO starting $0 $@"

makedir $listpath
makedir $lockpath

errorlog=$runlogpath/scriptlauncher-error`date +%F`.log
scriptlog=$runlogpath/scriptlauncher`date +%F`.log

echo `date`": starting $0 $@" >> $scriptlog 2>&1

path=`dirname $0`
date=`date +%Y-%m-%d`

scripts=( `echo $@ | sed -e 's/allatthesametime//'` )
num=${#scripts[@]}
echo "$num scripts have to be launched" >> $scriptlog 2>&1
i=0

while [ $i -lt $num ]
do 
   echo " launching ${scripts[$i]}..." >> $scriptlog 2>&1
   pid=`/usr/local/bin/condor_submit -a path=$path -a prog=${scripts[$i]} -a date=$date -a dir=$runlogpath $path/run.condor 2>> $errorlog | grep 'submitted to cluster' | cut -dr -f2`
   if [ "$pid" = "" ]
   then 
      echo `date`" WARN condor is not working " >> $errorlog 2>&1
      printprocesslog "WARN submitting ${scripts[$i]} to condor failed"
      continue
   fi
   if ! echo $@ | grep "allatthesametime" >/dev/null 2>$errorlog
   then
      echo "  waiting for ${scripts[$i]} to be done..." >> $scriptlog 2>&1
      /usr/local/bin/condor_wait $runlogpath/condor-$date.log $pid >/dev/null 2>$errorlog
   fi
   i=`expr $i + 1`
done
echo `date`": all done/submitted." >> $scriptlog 2>&1
echo "" >> $scriptlog 2>&1

printprocesslog "INFO finished $0 $@"

