#!/bin/bash


if [ -e /dev/shm/golem/session.setup ]; 
    then 
        #setup available ...
        source /dev/shm/golem/session.setup
        SHOT_NO=`cat /dev/shm/golem/shot_no`
    fi

SessionManagement="Operation/Session/Operator Operation/Session/Monitoring"
DischargeBasicManagement="Operation/Discharge/Discharge Diagnostics/BasicDiagnostics/DetectPlasma" 
DischargeManagement="$DischargeBasicManagement $OnStage_wave $Others_wave $Analysis $Infrastructure $DataProcessing"
BasicWave="Diagnostics/BasicDiagnostics/StandardDAS"
OffStage_wave="$Others_wave $Analysis $Infrastructure $DataProcessing"
Everywhere="$SessionManagement $DischargeManagement"

RASPs="Operator Chamber Charger Discharge"




GM="golem@golem"
sshGM="ssh $GM"
XTERM="xterm -T $Dev -e ssh golem@$Dev"
SHM="/dev/shm/golem"
SHM0="$SHM/ActualShot"
SHMS="$SHM/ActualSession"
SHML="$SHMS/SessionLogBook"
SHMCLP="$SHM/CommandLineParameters"
SHMP="$SHM0/Production/Parameters" #Parameters
shot_dir="/golem/database/operation/shots"
Tek_mount_path="/home/golem/tektronix_drop"
date_format="+%y-%m-%d %H:%M:%S"
psql_password="export PGPASSWORD=`cat /golem/production/psql_password`"
#DirigentServer="golem-new" 
DirigentServer="golem" 
SW_dir="/golem/Dirigent"


#WWW stuff:
linkiconsize="30px"
icon_size="200x150" 
ScreenShotAllSize="1600,1000"
namesize=100
iconsize=200
imgpath="http://golem.fjfi.cvut.cz/_static"
gitlabpath="https://gitlab.com/golem-tokamak/dirigent/-/tree/master"
gitlabicon="<img src=$imgpath/gitlab.png  width='$linkiconsize'/>"
googlephotosicon="<img src=$imgpath/GooglePhotos.png  width='$linkiconsize'/>"
manualicon="<img src=$imgpath/manual.png  width='$linkiconsize'/>"
diricon="<img src=$imgpath/direct.png  width='$linkiconsize'/>";
gnuploticon="<img src=$imgpath/gnuplot.png  width='$linkiconsize'/>";
pythonicon="<img src=$imgpath/python.png  width='$linkiconsize'/>";
resultsicon="<img src=$imgpath/results.png  width='$linkiconsize'/>";
parametersicon="<img src=$imgpath/parameters.png  width='$linkiconsize'/>";
psqlicon="<img src=$imgpath/postgresql.webp  width='$linkiconsize'/>";
underconst="<img src=$imgpath/UnderConstruction.png  width='$linkiconsize'/>";
#rightarrowicon="<img src=$imgpath/rightarrow.png  width='10px'/>";
rightarrowicon="&#9755;"
doubledoticon="<img src=$imgpath/dots-horizontal-double-512.webp  width='$linkiconsize'/>";




dbpath="http://golem.fjfi.cvut.cz/dbase"



NULL="1>/dev/null"
Everything2NULL="1>/dev/null 2>/dev/null"
ThisEntity=`basename $PWD`
dirigent_dir="/golem/Dirigent" #to be fixed, sorry


RSYNC="rsync --exclude '.*' --exclude '.*.*.kate-swp' --exclude Depository"


# Logs layouts:
LogFunctionStart="LogIt Diving into .."
LogFunctionEnd="LogIt Ascending from .."
#Let us try it simple way ..
#LogFunctionPassing="LogIt Passing by .."
LogFunctionPassing=""
LogFunctionGoingThrough="LogIt Going through .." 



# General access to general functions
# **********************************************************

#function VacuumFunction(){
#LogIt "General Calling $@"
#cd $SHMS/Infrastructure/Vacuum/; source Vacuum.sh; $@; cd $OLDPWD; 
#}

function CallFunction(){
local where=$1
local what=$2

  bash -c "source $SW_dir/$where.sh;$what"
}

function DischargeFunction(){ 
LogIt "General Calling $@"
bash -c "cd $SHM0/Operation/Discharge/;source Discharge.sh; $@"
}

function OperatorFunction(){
LogIt "General Calling $@"
bash -c "cd $SHM0/Operation/Session/;source Operator.sh; $@"
}

function TriggerManagement(){ ssh -Y golem@Discharge.golem  "source Trigger.sh; $@"; }
function Bt_Ecd_Management(){ ssh -Y golem@Charger.golem  "source Bt_Ecd.sh; $@"; }
function WorkingGasManagement(){ ssh -Y golem@Chamber.golem  "source WorkingGas.sh; $@"; }
function PreionizationManagement(){ ssh -Y golem@Discharge.golem  "source Preionization.sh; $@"; }
function VacuumManagement(){ ssh -Y golem@Chamber.golem  "source Vacuum.sh; $@"; }

function GeneralDAScommunication()
{
local DAS=$1
local function=$2
local where="$SHM0/Devices"

    if grep -qsic "function $what" $where/$DAS.sh ; 
        then 
        LogItColor 5 "DAS Calling $function@$DAS"
        bash -c "cd $where/`dirname $DAS`; source $SHM/Commons.sh;source `basename $DAS`.sh;$function $3 $4 $5"
        LogItColor 5 "Return from  $function@$DAS"
    fi    
}


# Devices issues
# **********************************************************




function DischargeExecute()
{
local where=$1
local what=$2

    LogItColor 5 "Executing Discharge function $what@$where"
    bash -c "cd $SHM0/`dirname $where`;source `basename $where`.sh; $what"
}

function SessionExecute()
{
local where=$1
local what=$2

    bash -c "cd $SHMS/`dirname $where`;source `basename $where`.sh; $what"
}

# Ping issues
# **********************************************************

function PingCheck ()
{
    if  [[ $whoami == Devices* ]] ;
    then
        dir=`dirname $whoami`
        timeout 50s bash -c "source `basename $whoami`.sh;WaitForDevice `basename $dir` `basename $whoami` $whoami" #New
    fi
}
    

function WaitForDevice()
{
Dev=$1
Task=$2
while ! timeout 1 ping -c 1 -n $Dev.golem &> /dev/null
do
    printf "%s\n" "waiting for $Task $Dev"
    Relax
done
printf "%s\n"  "$Dev for $Task is online"
}

function PingCheckNotEthDevice ()
{
  dir=`dirname $whoami`
  echo "Ping" not an ETH device: `basename $dir` for `basename $whoami`
}
    
# Sessions issues
# **********************************************************


function SubmitTokamakState ()
{
local what=$1
   echo -n $what > $SHML/tokamak_state
   echo -n $what > /golem/production/tokamak_state
   echo "`date '+%H:%M:%S'` $SHOT_NO:$what" >> $SHML/tokamak_state_log
}

function PrepareSessionEnv@SHM ()
{
    PrepareEnvironment@SHM $SHMS
}

function PrepareDischargeEnv@SHM ()
{
    PrepareEnvironment@SHM $SHM0
}

function PrepareEnvironment@SHM ()
{
local where=$1

    PrepareFilesToSHMs $where `dirname $whoami` $whoami
    
    for Dev in $Devices; do
    if  [[ $Dev == RASPs* ]] ;
    then
        PrepareFilesToSHMs $where Devices/`dirname $Dev`
        RaspName=`dirname $Dev|xargs basename`
        echo Copy stuff to $RaspName :
        echo ==========================
        #scp $SW_dir/Commons.sh $SW_dir/Devices/$Dev.sh $RaspName.golem:
    fi
    
    done
}
 
    
    
function PrepareFilesToSHMs() {
    local where=$1
    local what=$2
    local whoami=$3
    #echo $SW_dir/$what
    if [[ -d $SW_dir/$what ]]; then
        cd $SW_dir
  #      LogIt Copying files  $what .. to .. $where
        mkdir -p $where/$what
        $RSYNC -r $what/* $where/$what/
        #cp $whoami.* $where/$what/
        #cp *.png *.jpg *.html $where/$what/
        cd $OLDPWD;
    fi
    } 
  
function PrepareDriversToSHMS()
{
    : #ToDo
}    

    
    
    







# Log functions
# **********************************************************


LogTheDeviceAction()
{
    LogIt The `basename $whoami` action on stage with ${FUNCNAME[1]}
}

function TrackIt()
{
:
    #LogIt Tracking .... $1
}


function LogItColor() 
{
    #https://en.wikipedia.org/wiki/ANSI_escape_code#Colors 
    #0 – Black.1 – Red.2 – Green.3 – Yellow.4 – Blue.5 – Magenta.6 (purpur) – Cyan.7 (azur) – White.
    tput setaf $1
    if [ -e $SHMS/session_date ]; then # check if session has been opened 
        echo  `date '+%H:%M:%S'`\\t  ${FUNCNAME[1]} $2 >> $SHML/LocalLogBook
        printf "`date +%H:%M:%S` #`cat $SHM/shot_no` $ThisDev/${FUNCNAME[1]}:\t%s\n" "$2 $3 $4 $5 $6 $7 $8 $9  ${10} ${11} ${12} ${13} ${14} ${15}"|tee -a $SHML/GlobalLogbook 
    else 
        printf "`date +%H:%M:%S` $ThisDev/${FUNCNAME[1]}:\t%s\n" "$2 $3 $4 $5 $6 $7  $8 $9  ${10} ${11} ${12} ${13} "
	fi
	
    if [ -e $SHM0/ShotLogBook/SessionDate ]; then # check if shot 
        printf "`date +%H:%M:%S` #`cat $SHM/shot_no`   $ThisDev/${FUNCNAME[1]}:\t%s\n" "$2 $3 $4 $5 $6 $7  $8 $9  ${10} ${11} ${12} ${13} ">> $SHM0/ShotLogbook 
#	else 
#        printf "`date +%H:%M:%S` $ThisDev/${FUNCNAME[1]}:\t%s\n" "$1 $2 $3 $4"
	fi	
    tput sgr0
}


function EchoItColor() 
{
    tput setaf $1
        echo $2
    tput sgr0

}

function LogIt() 
{
    if [ -e $SHMS/session_date ]; then # check if session has been opened 
        echo  `date '+%H:%M:%S'`\\t  ${FUNCNAME[1]} $1 >> $SHML/LocalLogBook
        printf "`date +%H:%M:%S` #`cat $SHM/shot_no` $ThisDev/${FUNCNAME[1]}:\t%s\n" "$1 $2 $3 $4 $5 $6 $7 $8 $9  ${10} ${11} ${12} ${13} ${14} ${15}"|tee -a $SHML/GlobalLogbook 
    else 
        printf "`date +%H:%M:%S` $ThisDev/${FUNCNAME[1]}:\t%s\n" "$1 $2 $3 $4 $5 $6 $7  $8 $9  ${10} ${11} ${12} ${13} "
	fi
	
    if [ -d $SHM0 ]; then # check if shot 
        printf "`date +%H:%M:%S` #`cat $SHM/shot_no`   $ThisDev/${FUNCNAME[1]}:\t%s\n" "$1 $2 $3 $4 $5 $6 $7  $8 $9  ${10} ${11} ${12} ${13} ">> $SHM0/ShotLogbook 
#	else 
#        printf "`date +%H:%M:%S` $ThisDev/${FUNCNAME[1]}:\t%s\n" "$1 $2 $3 $4"
	fi	
	
}	

function LogItnewline() 
{
    printf "\n"|tee -a $SHML/GlobalLogbook
}


# Error management
# **********************************************************

function critical_error()
{
    LogIt  "Critical error: $1 ... Stopped"
    if xhost >& /dev/null ; then 
        echo pack [label .error -text {Critical error: $1 ... stopped}]|wish
    fi
}	

# Database management
# **********************************************************

# e.g.: golem@Dirigent>source Commons.sh ;CreateDiagnosticsTable MHDring_T

function CreateDiagnosticsTable ()
{
local diag_id=${1,,} #tolowercase

    $sql_password;psql -c 'CREATE TABLE diagnostics.'$diag_id' (shot_no integer UNIQUE, session_mission text, start_timestamp text, setup_id text, comment text, das text, X_discharge_command text)' -q -U golem golem_database
}

#e.g.: golem@Dirigent>source Commons.sh ;GeneralDiagnosticsTableUpdateAtDischargeBeginning PetiProbe


function GeneralDiagnosticsTableUpdateAtDischargeBeginning ()
{
local diag_id=${1,,} #tolowercase

    $psql_password;psql -c "INSERT INTO diagnostics.$diag_id (shot_no, session_mission, start_timestamp, setup_id, das, comment, X_discharge_command) VALUES ($SHOT_NO,'`cat $SHM/session_setup_name`','`date "$date_format"`','$setup_id','`dirname $DAS`','`cat $SHMP/comment`','`cat $SHMP/CommandLine`')" -q -U golem golem_database
    
    local WhatToDo=`cat $SHMP/diagnostics_$diag_id`
    if [[ -f $SHMP/diagnostics_$diag_id ]]; then
        psql -c "UPDATE  diagnostics.$diag_id SET $WhatToDo WHERE shot_no IN(SELECT max(shot_no) FROM diagnostics.$diag_id)" -q -U golem golem_database
    fi
    
    #mkdir -p $SHM0/Diagnostics/$1/Parameters
    #mkdir -p $SHM0/Diagnostics/$1/Results
    #psql -c "SELECT * FROM  diagnostics.$diag_id  WHERE shot_no IN(SELECT max(shot_no) FROM diagnostics.$diag_id)" -x -q -U golem golem_database > $SHM0/Diagnostics/$1/AllParameters;
    #grep -v RECORD AllParameters|awk -F "|" '{print "echo "$2" > '$SHM0'/Diagnostics/'$1'/Parameters/"$1}' -|bash;
    mkdir -p Parameters
    mkdir -p Results
    psql -c "SELECT * FROM  diagnostics.$diag_id  WHERE shot_no IN(SELECT max(shot_no) FROM diagnostics.$diag_id)" -x -q -U golem golem_database > AllParameters;
    grep -v RECORD AllParameters|awk -F "|" '{print "echo "$2" > Parameters/"$1}' -|bash;
}

function AddColumnToDiagnosticsTable ()
{
local diag_id=${1,,} #tolowercase

     $psql_password;psql -c 'ALTER TABLE diagnostics.'$diag_id' ADD COLUMN '$2' '$3';' -q -U golem golem_database
}



#./Dirigent.sh -r DataBaseQuerry shot_no
function CurrentShotDataBaseQuerry
{
    $psql_password;echo "SELECT $1 FROM shots ORDER BY shot_no  DESC LIMIT 1;"|psql -qAt -U golem golem_database 
}

# shot_no=`CurrentShotDataBaseQuerry shot_no` # Nefunguje na RASPs

function UpdateCurrentShotDataBase
{
    $psql_password;echo "UPDATE shots SET $1 WHERE shot_no IN(SELECT max(shot_no) FROM shots)"|psql -q -U golem golem_database 
}

function DistanceUpdateCurrentShotDataBase
{
    #echo "UPDATE shots SET $1 WHERE shot_no IN(SELECT max(shot_no) FROM shots)"|ssh golem "export PGPASSWORD='XY';cat - |psql -q -U golem golem_database" 2>/dev/null
    echo "UPDATE shots SET $1 WHERE shot_no IN(SELECT max(shot_no) FROM shots)"|ssh golem "$psql_password;cat - |psql -q -U golem golem_database" 2>/dev/null
}

function RemoteUpdateCurrentSessionDataBase
{
    #ssh Dirigent 'export PGPASSWORD='XY';psql -c "UPDATE sessions SET '$1' WHERE start_shot_no IN(SELECT max(start_shot_no) FROM sessions)" -q -U golem golem_database'
    ssh Dirigent ''$psql_password';psql -c "UPDATE sessions SET '$1' WHERE start_shot_no IN(SELECT max(start_shot_no) FROM sessions)" -q -U golem golem_database'
}

function InsertCurrentShotDataBase()
{
    $psql_password;echo "INSERT INTO shots $1" | psql -q -U golem golem_database
    
}

function InsertCurrentSessionDataBase()
{
    $psql_password;echo "INSERT INTO sessions $1" | psql -q -U golem golem_database
    
}

function UpdateCurrentSessionDataBase()
{
    $psql_password;echo "UPDATE sessions SET $1 WHERE start_shot_no IN(SELECT max(start_shot_no) FROM sessions)"|psql -q -U golem golem_database 
}

function CurrentSessionDataBaseQuerry()
{
    $psql_password;echo "SELECT $1 FROM sessions ORDER BY start_shot_no  DESC LIMIT 1;"|psql -qAt -U golem golem_database 
}

function WebShotDataBaseQuerry()
{
    WebRec $1: `export PGPASSWORD='rabijosille';echo "SELECT $2 FROM shots ORDER BY shot_no  DESC LIMIT 1;"|psql -qAt -U golem golem_database` $3
}

#Problem lowercase etc.:
#psql -q -U golem golem_database -c 'UPDATE shots SET "Ip_mean"=3 WHERE shot_no IN(SELECT max(shot_no) FROM shots)'

#CurrentShotDataBaseQuerry '"D_integral_dose"'

# Time management
# **********************************************************
function mRelax() { sleep 0.1; }

function uRelax() { sleep 0.01; }

function Relax() { sleep 1; }


# RASPs issues: (to be executed at RASPs)
# **********************************************************
function MountCentralSHMEnvironment()
{

    mkdir -p $SHM
    sshfs golem@$DirigentServer:$SHM/ $SHM/
    LogIt "Mount result: `df|grep golem`"
}   


# Audio
# **********************************************************

mplayer="ssh pi@Discharge.golem cvlc --play-and-exit "
#volume@Discharge: sudo amixer cset numid=1 -- 90 OR sudo alsamixer 
# files now locally at RASP
#sudo scp golem@golem:/golem/tools/sound_fx/*.mp3 /golem/tools/sound_fx/
#ssh pi@discharge 'sudo amixer cset numid=1 -- 90'
#mplayer="ssh golem@192.168.2.117 mplayer"
#mplayer=":"


function Speaker_CountDownVoice(){
#    if [ "$comment" != "Dummy test discharge" ]; then
        $mplayer /golem/tools/sound_fx/discharge_long.mp3 1>/dev/null 2>/dev/null 
#    fi
}


function Speaker_ChargingInstructionVoice(){
    if [ "$comment" != "Dummy test discharge" ]; then
        $mplayer /golem/tools/sound_fx/charging_instructions.mp3 1>/dev/null 2>/dev/null &
    fi
}


function DataReadyVoice(){
        $mplayer /golem/tools/sound_fx/The-end-of-the-discharge-proce.mp3 1>/dev/null 2>/dev/null
}

function HomepageReadyVoice(){
        $mplayer /golem/tools/sound_fx/HomepageReady.mp3 1>/dev/null 2>/dev/null
}

# WWWs
# **********************************************************


function GenerateDiagWWWs  
{
local diag_id=$1
local setup_id=$2
local DASId=$3
local GWdiagpath="http://golem.fjfi.cvut.cz/wiki/$4"
local googlephotospath="https://photos.app.goo.gl/$5"

#local diagpath="http://golem.fjfi.cvut.cz/shots/$SHOT_NO/Diagnostics/$diag_id"
local diagpath="Diagnostics/$diag_id"
local devicepath="Devices/$DASId"
      
    echo "<tr>
    <td valign=bottom><a href=$diagpath/><img src=$diagpath/name.png  width='$namesize'/></a>&nbsp;</td>
    
    <td valign=bottom>&nbsp;<a href=$diagpath/expsetup.svg><img src=$diagpath/setup.png /></a></td>
    <td>
    <!--<a href=$GWdiagpath title="GW path"><img src=$imgpath/logos/golem.png  width='$linkiconsize'/></a><br></br>
    <a href=$googlephotospath title="Photogallery@Google">$googlephotosicon</a><br></br>-->
    </td>
    
    <td valign=bottom>&nbsp;<a href=$devicepath/das.html><img src=$devicepath/das.jpg  width='$iconsize'/></a></td>
    <td>
    <!--<a href=$devicepath/das.html title="Manual$devicepath">$manualicon</a><br></br>-->
    </td>
    
    <td valign=bottom>&nbsp;<a href=$devicepath/ScreenShotAll.png><img src=$devicepath/rawdata.jpg  width='$iconsize'/></a></td>
    <td>&nbsp;
    <a href=$gitlabpath/$devicepath/ title="Gitlab4$devicepath">$gitlabicon</a><br></br>
    <a href=$devicepath/ title="Data directory">$diricon</a><br></br>
    </td>
    
    <!--Analysis start-->
    
    <td valign=bottom><a href=$diagpath/icon-fig.png><img src=$diagpath/graph.png  width='$iconsize'/></a></td>
    <td>&nbsp;<a href=$diagpath/Parameters/ title="Parameters">$parametersicon</a><br></br>
    
    <a href=$gitlabpath/Diagnostics/$diag_id/$setup_id.ipynb title="JupyterNotebook$diagpath">$pythonicon</a>
    $rightarrowicon
    <a href=$diagpath/analysis.html title="Analysis$diagpath">$resultsicon</a><br></br>
    <a href=$gitlabpath/$diagpath/ title="Gitlab4$diagpath">$gitlabicon</a>
    
    <a href=$diagpath/ title="Directory">$diricon</a>
    <a href=$dbpath/Diagnostics/$diag_id/ title="Database">$sqlicon</a>
    </td>
    
    <!--Analysis end-->
    
    </tr>" >diagrow_$setup_id.html;
    
    
    echo "<center><h1>The GOLEM tokamak Basic Diagnostics setup</h1>
    <h2>Photo</h2>
    <img src="/_static/figs/DAS-d_s.jpg" width="25%"></img><br/>
    <h2>Relevant excerpt from the manual</h2>" > setup.html;
    for j in `seq 0 2`; do
        echo "<img src=http://golem.fjfi.cvut.cz/wiki/Education/GMinstructions/extracts/Extracts/Diagnostics/output-$j.jpg width='50%'></img>" >> setup.html;
    done
    
    
}

function GenerateAnalysisWWWs  
{
local forwhom=$1

local diagpath=`dirname $forwhom`
      
    echo "<tr>
    <td valign=bottom><a href=$diagpath/><img src=$diagpath/name.png  width='$namesize'/></a></td>
    
    <td valign=bottom><a href=$diagpath/analysis.html><img src=$diagpath/graph.png  width='$iconsize'/></a></td>
    <td>
    <a href=$gitlabpath/$forwhom.ipynb title="JupyterNotebook$diagpath">$pythonicon</a>
    $rightarrowicon
    <a href=$diagpath/analysis.html title="Analysis$diagpath">$resultsicon</a><br></br>
    <a href=$diagpath/ title="Directory">$diricon</a>
    <a href=$dbpath/Diagnostics/$diag_id/ title="Database"><img src=$imgpath/postgresql.webp  width='$linkiconsize'/></a>
    </td></tr>" >diagrow_`basename $forwhom`.html;
    
    
}





# Workarrounds
# **********************************************************



function FakeWGcalH2 # nouzova stara kalibrace plynu
{
    LogIt "Fake WG calibration ... "
    cp /golem/Dirigent/Management/WGcalibration/100620_WG_calibration_table4H2 /dev/shm/golem/ActualSession/SessionLogBook/WG_calibration_table4H2
}

# Others
# **********************************************************

function WebRecDas()
{
    echo $1 >> das.html
}

function Flag() # Just for SW tuning
{
    echo Waving from ${FUNCNAME[2]} 
}


function ResetRASPs()
{

    for Dev in `ls /golem/Dirigent/Devices/RASPs/`;do echo Doing: $Dev;ssh pi@$Dev 'echo raspberry | sudo shutdown -r now';done
}

function KillAllGMtasksEverywhere()
{

    for Dev in $RASPs; do
          ssh -Y golem@"$Dev".golem  "killall -u golem"
          #ssh -Y golem@"$Dev".golem  "ps -Af|grep golem|grep -v sshfs|grep -v sftp|grep -v sshd|awk '{print \$2}'|xargs  kill" 
    done
}


function rsyncRASPs()
{
local cesta="/golem/Dirigent/Devices/RASPs"
       for Dev in `ls $cesta/`;do 
       if timeout 1 ping -c 1 -n $Dev.golem &> /dev/null
        then
          echo Doing: $Dev
          scp $cesta/$Dev/*.sh golem@"$Dev".golem:  
          #scp $SHM/Commons.sh golem@"$Dev".golem:   #????
          scp Commons.sh golem@"$Dev".golem:  
        fi
    done
}

function KillAllGMs(){
#./Dirigent.sh -k
    killall -u golem
}



function NothingToDo(){ :; }      


sanb()
{
sleep 3;ls
}

# source Commons.sh ;DischargeEntityTest /golem/Dirigent/Diagnostics/BasicDiagnostics/DetectPlasma.sh

DischargeEntityTest()
{
local SW_dir=/golem/Dirigent
#local Where=`dirname $1|sed 's/\/golem\/svoboda\/Dirigent\///g'`
local Where=${1#*"Dirigent/"}
local Where=${Where#*"ActualShot/"}
local Where=`dirname $Where`
local What=`basename $1`


cd $SHM0/$Where
echo pwd: `pwd`
echo Copying $What $Where ...
echo ====================
cp -v $SW_dir/$Where/*.* .
source $What
echo "Copy DAS $DAS ... (in case)"
echo ====================
cp -v $SW_dir/Devices/`dirname $DAS`/*.* $SHM0/Devices/`dirname $DAS`/

GetReadyTheDischarge
TriggerManagement GetReadyTheDischarge
Relax
GeneralDAScommunication $DAS Arming
Arming
Relax
for i in `seq 1 10`; do echo wait $i;sleep 1;done # in NI case
TriggerManagement Trigger
Relax
TriggerManagement SecurePostDischargeState
PostDischargeAnalysis;
ll /dev/shm/golem/ActualShot/Devices/`dirname $DAS`/; 
ll

cd $OLDPWD
echo pwd: `pwd`
}

#including ".sh"
# e.g. source Commons.sh ;OpenSessionSomewhere /golem/Dirigent/Devices/Oscilloscopes/RigolMSO5104-a/Stabilization.sh
# e.g. source Commons.sh ;OpenSessionSomewhere /golem/Dirigent/Devices/Oscilloscopes/TektrMSO56-a/BasicDiagnostics.sh 
# e.g. source Commons.sh ;OpenSessionSomewhere /golem/Dirigent/Devices/Oscilloscopes/TektrMSO58-a/21_RunAways_JCetal.sh 
OpenSessionSomewhere()
{
local SW_dir=/golem/Dirigent
local Where=${1#*"Dirigent/"}
local Where=${Where#*"ActualShot/"}
local Where=`dirname $Where`
local What=`basename $1`
#local Where=`dirname $1|sed 's/\/golem\/svoboda\/Dirigent\///g'`
#local What=`basename $1`

echo $Where
echo $What
#return

cd $Where
source $What;OpenSession;

cd $OLDPWD

}

#source Commons.sh ;PostDischargeAnalysisTest file:///golem/shm_golem/ActualShot/Diagnostics/BasicDiagnostics4TrainCourses/StandardDAS-b.sh

PostDischargeAnalysisTest()
{
local SW_dir=/golem/Dirigent
local Where=${1#*"Dirigent/"}
local Where=${Where#*"ActualShot/"}
local Where=`dirname $Where`
local What=`basename $1`

cd $SHM0/$Where
#echo pwd: `pwd`
echo Copying $What $Where ...
echo ====================
cp -v -r $SW_dir/$Where/* .
source $What

PostDischargeAnalysis;
ll

cd $OLDPWD
#echo pwd: `pwd`
}


#e.g. source Commons.sh ;AnalysisReconstruction Diagnostics/PetiProbe/21_PetiProbe_KHetal.sh 35468

function AnalysisReconstruction()
{
    cd $SW_dir

    local SW_dir=/golem/Dirigent
    local What=$1
    local shot_no=$2
    
    local PureWhat=${What#*"Dirigent/"}
    echo $PureWhat
    
    cd /golem/database/operation/shots/$shot_no/`dirname $PureWhat`
    echo cd /golem/database/operation/shots/$shot_no/`dirname $PureWhat`
    cp -r $SW_dir/`dirname $PureWhat`/* .
    source `basename $PureWhat`; Analysis
    
    cd $SW_dir




}



#cd /golem/database/operation/shots/`cat /golem/database/operation/shots/0/shot_no`/Devices/Oscilloscopes/RigolMSO5104-a/;source Stabilization.sh ;GetOscScreenShot ;ll
