#!/bin/sh

# Copyright CERN, 2011
# Author: Matthieu Cattin <matthieu.cattin@cern.ch>
# Licence: GPL v2 or later.
# Website: http://www.ohwr.org


sudo rmmod cp210x
cd ~/fmc-tdc-1ns-5cha-tst/pts
sudo insmod ./cp210x-driver/cp210x.ko
cd usbdriver
sudo ./usbtmc_load
cd ..
cd ~/fmc-tdc-1ns-5cha-tst/pts

LOGDIR_CALIB=./logs/calib
mkdir -p $LOGDIR_CALIB
sudo rm -fr $LOGDIR_CALIB/fmc-tdc-1ns-5cha-tst*
LOGDIR_FUNC=./logs/func
mkdir -p $LOGDIR_FUNC
sudo rm -fr $LOGDIR_FUNC/fmc-tdc-1ns-5cha-tst*

serial=$1
if [ x$1 = x"" ]; then
	echo -n "Please scan CERN serial number bar-code, then press [ENTER]: "
        read serial
fi

if [ x$serial = x"" ]; then
	serial=0000
fi

if [ -e serial.txt ]; then
    sudo rm -f serial.txt
fi

echo $serial >> serial.txt

extra_serial=$2
if [ x$2 = x"" ]; then
	echo -n "If needed input extra serial number and press [ENTER] OR just press [ENTER]: "
        read extra_serial
fi

if [ x$extra_serial = x"" ]; then
	extra_serial=0000
fi

echo " "

nb_test_limit=2
nb_test=1

while [ "$nb_test" -le "$nb_test_limit" ]
do
    echo "--------------------------------------------------------------"
    echo "Test series run $nb_test out of $nb_test_limit"
    echo " "

    echo "--- Functionality tests ---"

    sudo ./pts.py -b FmcTdc1ns5cha_funct -s $serial -e $extra_serial -t ../test/fmctdc1ns5cha/functionality/python -l $LOGDIR_FUNC 00 01 02 03 04 05 06 07 08 09 10 11 12

    echo -n "Do you wish to continue with the calibration tests [y,n]? "
    read reply
    if [ "$reply" = "y" ]
    then
        echo "---  Calibration tests  ---\n"
        sudo ./pts.py -b FmcTdc1ns5cha_calib -s $serial -e $extra_serial -t ../test/fmctdc1ns5cha/calibration/python -l $LOGDIR_CALIB 13 14 15 16 17 18
    fi

    if [ "$nb_test" != "$nb_test_limit" ]
    then
        echo " "
        echo -n "Do you want to run the test series again [y,n]? "
        read reply
        if [ "$reply" != "y" ]
        then
            break
        fi
    fi
    nb_test=$(($nb_test+1))
done

echo "--------------------------------------------------------------"
echo " "
echo -n "End of the test, do you want to switch the computer OFF? [y,n]"
read reply
if [ "$reply" = "y" ]
then
    sudo poweroff
fi
