#!/bin/bash
#$ -P P_virgo_prod
#$ -l os=cl7,h_cpu=100000,fsize=4000M,h_rss=4G,sps=1,xrootd=1
#$ -N virgo.prod.o3.detchar.transient.omicron

source /pbs/home/f/frobinet/Env7.sh

# get segments
segments=$1

# get parameter file
parameters=$2

# channel outdir
channel_outdir=$3

# start - stop
start=`head -n 1 $segments | awk '{print int($1)}'`
end=`tail -n 1 $segments | awk '{print int($2)}'`
start_root=$(( $start / 100000 ))
end_root=$(( $end / 100000 ))

# output directory
outdir=$TMPDIR/outdir
mkdir -p $outdir

# input parameters
sed 's|\[outdir\]|'$outdir'|g' $parameters > $TMPDIR/param.txt

# channel
channel=`grep "DATA  CHANNELS" $parameters | awk '{print $3}'`
channel2=`echo $channel | sed 's|:|-|g'`

# segments
segexpr 'union('$segments')' > $TMPDIR/seg.txt

# ffl
cp -f /sps/virgo/BKDB/O3/O3_raw.ffl .

################### LOCAL ###################
# xrootd
#source /pbs/software/centos-7-x86_64/xrootd/ccenv.sh 4.8.1
LD_PRELOAD=/usr/lib64/libXrdPosixPreload.so
XROOTD_VMP=ccxrdrli03:1999:/hpss/=/hpss/
export XROOTD_VMP LD_PRELOAD

# get list of files
#awk '$2>='$start'&&$2<'$end' {print}' /sps/virgo/BKDB/O3/O3_raw.ffl | awk '{print $1}'> ./files.tmp
#while read line; do
#    ls -l $line
#    stat $line
#done < ./files.tmp

# processing
omicron $TMPDIR/seg.txt $TMPDIR/param.txt

# remove xrootd posix
unset LD_PRELOAD
#############################################

# merge root files and mv to sps
i=$start_root; 
while [ $i -le $end_root ]; do # loop over GPS
    triggermerge . "${outdir}/${channel}/${channel2}_OMICRON-${i}*.root"
    mkdir -p ${channel_outdir}/$i
    mv ./*_OMICRON-${i}*.root ${channel_outdir}/$i
    let "i+=1"
done
