#!/bin/bash

BasePath=../..;source $BasePath/Commons.sh
source Universals.sh

#SHM="/dev/shm/golem"
#source $SHM/Commons.sh
rPi=RasPi3-e
shot_no=`CurrentShotDataBaseQuerry shot_no`
#shot_no=31839 # just for testing


DAS="ITs/RasPi3-e/StripDetector"
DeviceList="$DAS"


function DefineDiagTable()
{
    CreateDiagnosticsTable $diag_id
    AddColumnToDiagnosticsTable $diag_id r_sensor integer
    AddColumnToDiagnosticsTable $diag_id phi_sensor integer
}


function GetReadyTheDischarge ()
{
	GeneralTableUpdateAtDischargeBeginning diagnostics.$instrument #@Commons.sh

	ssh pi@$rPi 'rm last_shot/*'
	
	armCommand="./arming.sh --shotNo $shot_no"
        paramDir="./Parameters"
	# use paremeters if availible
	if [ -s "$paramDir/acq_time" ] && [ ! `grep -q '[^[:space:]]' < "$paramDir/acq_time"` ]; then
		armCommand+=" --acqTime `cat $paramDir/acq_time`"
	fi

	if [ -s "$paramDir/acq_delay" ] && [ ! `grep -q '[^[:space:]]' < "$paramDir/acq_delay"` ]; then
		armCommand+=" --delay `cat $paramDir/acq_delay`"
	fi

	if [ -s "$paramDir/acq_mode" ] && [ ! `grep -q '[^[:space:]]' < "$paramDir/acq_mode"` ]; then
		armCommand+=" --mode `cat $paramDir/acq_mode`"
	fi

	armCommand+="  >/dev/null 2>/dev/null &"
        #echo "calling $armCommand for StripDetector"
	ssh pi@$rPi "$armCommand"
}

function Arming()
{

    ssh pi@$rPi "touch callToArm"

}



function getdata ()
{
    timeout=10
    while ssh  pi@$rPi "! test -s last_shot/PH32Det0_$shot_no.log -a -s last_shot/PH32Det1_$shot_no.log";
    do
        if [ "$timeout" == 0 ]; then
        LogItColor 1 "ERROR: Timeout while waiting for the file from $rPi"
        exit 1
    fi
    sleep 1
    echo "$timeout s to wait for $rPi files"
    ((timeout--))
    done

    scp pi@$rPi:last_shot/PH32Det0_$shot_no.log .
    scp pi@$rPi:last_shot/PH32Det1_$shot_no.log .
}


function PostDischargeAnalysis()
{
    getdata
    if [[ ! -d DAS_raw_data_dir ]]; then ln -s $BasePath/Devices/`dirname $DAS` DAS_raw_data_dir; fi

    sed -i "s/shot_no\ =\ 0/shot_no\ =\ `cat /dev/shm/golem/shot_no`/g" notebook.ipynb
    jupyter-nbconvert --execute notebook.ipynb --to html --output analysis.html 2>ErrorLog

    convert -resize $icon_size icon-fig.png graph.png
    notebook=notebook.ipynb
    GenerateDiagWWWs $instrument $setup $DAS $notebook $port $DropBox
    
    cp rawdata.png DAS_raw_data_dir/ScreenShotAll.png
    convert -resize $icon_size rawdata.png DAS_raw_data_dir/rawdata.jpg
}

function OpenSession()
{
    echo Strip Open session
    ssh pi@$rPi "./openSession.sh   >/dev/null 2>/dev/null &"
	echo OK
}


function CloseSession()
{
	ssh pi@$rPi "./closeSession.sh  >/dev/null 2>/dev/null &"
    echo OK
}
