#!/bin/bash

anode=25
run=""
ManipFolder="/opt/data/GANIL/e676/Replay"
ReplayFolder="/opt/data/GANIL/e676/Replay"
TopologyFolder="${ReplayFolder}/Topology"

Topology="${TopologyFolder}/Topology_Global.conf"

for i in $*
do
	if [[ $i == "-run" ]]
        then Mode="RunMode"
             continue
    fi
    if [[ $i == "-anode" ]]
        then Mode="AnodeMode"
             continue
    fi
    if [[ $i == "-topology" ]]
        then Mode="TopologyMode"
             continue
    fi
	if [[ $Mode == "" ]]
    then
         echo -e "\e[1;34m[\u2714]Usage manual:"
         echo -e "-run RunNr => for the run number"
         echo -e "-topology TopologyPath => to select a specific topology file, default is TopologyGlobal.conf \e[0m"
         exit 2
    else
	if [[ ${Mode} == "RunMode" ]]
            then
				if [ -d ${ManipFolder}/run${i}_LOCAL ]
                	then run=$i
					else echo -e "\e[1;31m[\u2717]run_$run_LOCAL not found in ${ManipFolder}/\e[0m"
						 exit 2
				fi
        fi
		if [[ ${Mode} == "AnodeMode" ]]
			then
				anode=${i}
		fi
		if [[ ${Mode} == "TopologyMode" ]]
			then
				if [ -f ${i} ]
                	then Topology=${i}
						 #abspath=`echo ${PWD}/"${Topology##*/}"`
						 abspath=`echo "$(dirname $(readlink -e ${Topology}))/$(basename ${Topology})"`
					 	 Topology=$abspath
					else echo -e "\e[1;31m[\u2717]${i} not found\e[0m"
						 exit 2
				fi	
		fi
	fi
done

if [[ ${run} == "" ]]
then
     echo -e "\e[1;31m[\u2717]You at least need to specify the run number"
     echo -e "Usage manual: "
     echo -e "-run for the run number"
     echo -e "-anode if you want to specify the anode to process the replay, default is 25"
     echo -e "-topology to select a specific topology file, default is Topologies/Topology_Prod_PSA_Cons_Builder.conf\e[0m"
     exit 2
fi

echo -e "\e[1;34mSettings are"
echo -e "Replay will be created in run_${run}"
#echo -e "Replay will be processed on anode ${anode}"
echo -e "Topology loaded is ${Topology}\e[0m"

echo
echo "Press any key to continue"
read
			
echo " will copy template directory in run_${run}"
cp -rp ${ReplayFolder}/template run_${run}
cd run_${run}
ln -s ${ManipFolder}/run${run}_LOCAL/Out Data
./gen_conf.py
/opt/analysis-tools/GANIL/AgataSoftware/agapro/WinCtest/femul ${Topology} -nothr | tee log_glob


#echo "will make replay of data from run ${run} on anode${anode}"
#echo "ssh anode${anode} \"cd ${ReplayFolder}/run_${run}; ./gen_conf.py; /agata/prototype/AgataSoftware/agapro_new4/WinCtest/femul ${Topology} | tee log_glob  ; wait;\"&"

#ssh anode${anode} "cd ${ReplayFolder}/run_${run}; ./gen_conf.py; /agata/prototype/AgataSoftware/agapro_new4/WinCtest/femul ${Topology} | tee log_glob  ; wait;"&
#wait %1
