#!/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  04/2009 <mailto:daniela.dorner@unige.ch>
#
#   Copyright: MAGIC Software Development, 2000-2009
#
#
# ========================================================================
#

rootsys=/opt/root5.20.x86_64
source `dirname $0`/sourcefile
printprocesslog "INFO starting $0"
program=chimp
column=fChimp
chimpdir=/home/dorner/Chimp
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$chimpdir/hessioxxx/lib:.

set -C

node=`echo $HOSTNAME | sed -e 's/compute-0-//' -e 's/[.]local//'`
#printprocesslog "INFO $program is running on node $node"
# get run # 
gettodo "1" $node
run=${primaries[0]}

# lock sequ
lockfile=$lockpath/lock-$table-$column-$run.txt
checklock 

printprocesslog "INFO starting $program for run $run"

#get particle for file name
particles[1]="gamma"
particles[14]="proton"
particles[6]="muon"
particles[3]="electron"
query="select fParticleTypeKEY from MCRunData where fMCRunNumber=$run"
key=( `mysql -P 3306 -u operator --password=Ics+eMM! --host=mysql.isdc.unige.ch CTA_MC -s -e "$query"` )
particle=${particles[$key]}
infile=$mcpath/simtel/cta-ultra3/0.0deg/Data/${particle}_20deg_90deg_run`printf '%06d' ${run}`___cta-ultra3_desert.simtel.gz
outfile=$mcpath/chimp/cta-ultra3/0.0deg/Data/${particle}_20deg_90deg_run`printf '%06d' ${run}`___cta-ultra3_desert.root
outpath=$mcpath/chimp/cta-ultra3/0.0deg/Data
logfile=$outpath/chimp_run`printf '%06d' ${run}`.log
makedir $outpath
chimppath=/home/dorner/data/chimp
clusterchimppath=/state/cta/chimp
makedir $chimppath


setstatus "start" 

cd $chimpdir

printprocesslog "INFO ./chimp $infile >| $logfile 2>&1 "
./chimp $infile >| $logfile 2>&1 
check1=$?

case $check1 in
   0)   printprocesslog "INFO $program finished successfully for run $run (check1=$check1)"
#        if ! cp $outfile $chimppath
        if ! scp $outfile $clusterchimppath
        then
           printprocesslog "ERROR copying $outfile to $chimppath failed"
           com=$Fchimpcp
           check=2
        else
           printprocesslog "INFO copied $outfile successfully to $chimppath"
        fi
        ;;
   *)   printprocesslog "ERROR $program failed for run $run (check1=$check1)"
        com=$Fchimp
        check=$check1
        ;;
esac

setstatus "stop"

finish

