#!/bin/bash
if [ -z ${1+x} ]; then
    echo "at least one argument needed: chipnum";
    exit
fi

if [ -z ${2+x} ]; then
    echo "second argument (station) not supplied; assuming station 1";
    station=1
else
    station=$2
fi
cd /home/tpc/sampa-test-stand/script

mask=$(printf "%#x\n" ${station})
chip=$1
echo chip ${chip} mask ${mask} station ${station} 
calltime=`date +%s` #epoch
echo "chip ${chip} mask ${mask} ${calltime}" > sta${station}.log 

today=`date +%Y%m%d` #YearMonthDay
outdir="/home/tpc/robot/${today}"
hms=`date +%H%M%S` #HourMinSec
prefix="${hms}_sta${station}_sampa"

chipstr=$(printf "%#06d" ${chip})
dir="${outdir}/${prefix}${chipstr}"
echo dir ${dir}

# check that DFT is not running in other station; wait maximum 120 sec
./waitOther.sh ${station} 120 
starttime=`date +%s` #epoch
echo "station ${station} chip ${chip} DAQ START ${starttime}" >> sta${station}.log  

time run.py -m ${mask} --nr ${chip} --output-dir $outdir --nr-prefix ${prefix} --init --logname init.log
sleep 3 # a little extra wake-up time; read voltages before and after taking all test data
time run.py -m ${mask} --nr ${chip} --output-dir $outdir --nr-prefix ${prefix} --test-dc --logname dc0.log
time run.py -m ${mask} --nr ${chip} --output-dir $outdir --nr-prefix ${prefix} --test-readall --logname run.log
time run.py -m ${mask} --nr ${chip} --output-dir $outdir --nr-prefix ${prefix} --test-dc --logname dc.log

# misc and jtag tests
time run.py -m ${mask} --nr ${chip} --output-dir $outdir --nr-prefix ${prefix} --test-misc --logname misc.log
time run.py -m ${mask} --nr ${chip} --output-dir $outdir --nr-prefix ${prefix} --test-jtag --logname jtag.log

# do DFT last...
time run.py -m ${mask} --nr ${chip} --output-dir $outdir --nr-prefix ${prefix} --test-dft --logname dft.log
#

# power-off when finally done for robot
time run.py -m ${mask} --nr ${chip} --output-dir $outdir --nr-prefix ${prefix} --off --logname off.log

endtime=`date +%s` #epoch
echo "station ${station} chip ${chip} DAQ DONE ${endtime}" >> sta${station}.log  

perl checklog.pl ${dir} ${station} > ../logs/testchip${chip}.log

# get return code for robot
RETCODE=`grep Return ../logs/testchip${chip}.log | awk '{print $NF}'`
# store checklog summary in the exe dir also
cp ../logs/testchip${chip}.log ${dir}/.
cd -
exit ${RETCODE}

