#!/bin/bash

BasePath=/golem/Dirigent;source $BasePath/Commons.sh


DeviceList="ITs/NAS/Golem ITs/RasPi4-c/ControlPanel Infrastructure/Racks/Miscellaneous/Basic Infrastructure/Control/ControlPanel/Basic RelayBoards/Quido16-b/Galvanics"
#Drivers="remote_web_app"
#Analysis="Homepage"


# Session stuff
# **********************************************************







function SetupSession ()
{
      cd $SW;
      #BasePath=../../..;source $BasePath/Commons.sh
      rm -rf $SHM 
      mkdir -p $SHM $SHMS $SHM/Tags $SHM/Production
      cp session.setup $SHM/session.setup
      cp `realpath session.setup` $SHM/
      cp $SW/Dirigent.sh $SW/Commons.sh $SHMS/
       for i in $(grep include session.setup|grep -v '#'|sed 's/source //g');do cp Setups/$i $SHM/;cp Setups/$i .;done
       cp `realpath session.setup` $SHM/
       echo `realpath session.setup |sed 's/\/golem\/Dirigent\/Setups\///g;s/\.setup//g'` > $SHM/session_setup_fullname
       echo `realpath session.setup |xargs basename -s .setup` > $SHM/session_setup_name

      hostname > $SHM/Production/hostname # migration to SuperMicro
      
      
      source session.setup
      Orchestra='Operation Infrastructure Diagnostics_Basic Diagnostics_OnStage Diagnostics_OffStage Analysis'
      Operation="HigherPower/Standard $Operation" # extra Dirigent Power
      echo $Orchestra > $SHM/Production/Orchestra;export Orchestra="$Orchestra"
      echo "$Orchestra Devices" > $SHM/Production/Ensemble;export Ensemble="$Orchestra Devices"
     PrepareEnvironment@SHM $SHMS # Get ready the whole dir struct @SHMS


    echo $((`CurrentShotDataBaseQuerry "shot_no"`)) > $SHM/shot_no 
    echo $Mission > $SHMS/session_mission
    echo $Staff > $SHMS/staff_list

    

    AllInstruments="";AllDevices=""
    rm $SHM/whole.setup
for Family in $Orchestra;
    do
    rm -f $SHM/Production/$Family
    echo \#$Family: >> $SHM/whole.setup
    for Instrument in ${!Family};do
        export $Family="${!Family}"
        echo $Instrument >> $SHM/Production/$Family
        echo $Instrument \\ >> $SHM/whole.setup
        AllInstruments="$AllInstruments ${Family%_*}/$Instrument"
        cd  `dirname $SHMS/${Family%_*}/$Instrument/`; 
        source `dirname $Instrument|xargs basename`.sh
        for Dev in $DeviceList;do
            AllDevices="$AllDevices $Dev"
        done
    done
done


#Remove duplicate onstage diagnostics from offstage:;
cp $SHM/Production/Diagnostics_OffStage $SHM/Production/Diagnostics_OffStage_Original
if [ -e $SHM/Production/Diagnostics_OnStage ]; then grep -vf $SHM/Production/Diagnostics_OnStage $SHM/Production/Diagnostics_OffStage_Original > $SHM/Production/Diagnostics_OffStage ;fi

AllDevices=$(echo $AllDevices | tr ' ' '\n' | awk '!x[$0]++') #remove duplicate rows with awk
AllInstruments=$(echo $AllInstruments | tr ' ' '\n' | awk '!x[$0]++')

export Devices="$AllDevices";echo $AllDevices > $SHM/Production/Devices
export AllInstruments="$AllInstruments";echo $AllInstruments > $SHM/Production/AllInstruments
instrument=Dirigent;

     cd $SHMS;
     Broadcast $SHMS "$Orchestra Devices" PrepareSessionEnv@SHM
    
    mkdir -p $SHMS/Devices/RelayBoards
    cp $SW/Devices/RelayBoards/RelayBoards.sh $SHMS/Devices/RelayBoards/
    Call $RelayBoards Aten@Permanent ON #Switch on monitors & ATEN's stuff
    cp $SW/Devices/Infrastructure/Racks/Universals.sh $SHMS/Devices/Infrastructure/Racks/
    
}

function PrepareSessionEnv@SHM()
{
   PrepareEnvironment@SHM $SHMS
   cp $SHM/*.* $SHMS/
   cp $SHM/* $SHMS/ 1>/dev/null 2>/dev/null
   mkdir -p $SHML; #Logbooks
   mkdir -p $SHMS/Production;touch $SHMS/Production/FunctionTimes
   chmod -R g+rwx $SHM
   mkdir -p $SHMS/SessionLogBook
   SubmitTokamakState "idle" 
   rsync  -r $SW/Operation/Discharge/Parameters/System/ $SHMS/Production/

}	



function OpenSession(){


    echo $((`CurrentShotDataBaseQuerry "shot_no"`+1))> $SHM/session_id 
    cat $SHM/session_id > $SHMS/session_id
    date "$date_format" > $SHMS/session_date
    cp $SHM/session_setup_name $SHML/
    
    

    $LogFunctionStart
    LogIt Date: $(< $SHMS/session_date);
    LogIt "Session setup:"
    LogIt "=================="
    LogIt Session ID: $(< $SHM/session_id);
    LogIt "=================="

    zip -qr $SHMS/GolemCntrl * -x '*.git*'

    # pSQL Database 
    InsertCurrentSessionDataBase "(start_shot_no, start_timestamp, session_mission, session_setup, onstage_wave, offstage_wave, staff_list, infrastructure, analysis) VALUES ($(< $SHM/session_id),'$(< $SHMS/session_date)', '$(<$SHMS/session_mission)', '$(<$SHM/session_setup_fullname)',  '$Diagnostics_OnStage', '$Diagnostics_OffStage','$(<$SHMS/staff_list)','$Infrastructure','$Analysis');" 

      
    EchoItColor 1 "Do not forget to make Test dlouhodobe stability (start Radiometr)"
    EchoItColor 1 "Do not forget to open gas valves at every session beginning! (naprogramuj test rozdilu ocekavani proti realite)"
    EchoItColor 1 "When necessary, do WG calibration !!"
    #FakeWGcalH2 # Fake calibration ToDo ...

    OpenJson
    
    SubmitTokamakState "idle" 
       
    # ssh pi@discharge 'sudo amixer cset numid=1 -- 90' #set volume of the speaker (je to nekde jinde)
  
}

function ResetSession ()
{
    CloseSession
        ssh -Y golem@golem "killall xterm"
        rm -rf /dev/shm/golem;
    if ping -c 1 Chamber.golem &> /dev/null
    then
        ssh -Y golem@Chamber.golem  "sudo umount /dev/shm/golem;killall -u golem"
    fi


}


function OpenJson()
{
    python3 /golem/Dirigent/Operation/RemoteOperation/remote_web_app/json_status4remote.py &
    disown `echo $!`
}

function CloseStuff()
{
    if [ -e $SHM/shot_no ]; then 
        UpdateCurrentSessionDataBase "end_shot_no=`cat $SHM/shot_no`, end_timestamp='`date "$date_format"`', end_chamber_pressure=`cat $SHML/ActualChamberPressuremPa`, end_for_vacuum_pressure=`cat $SHML/ActualForVacuumPressurePa`"
    fi
    
    rsync -a $SHM/ActualSession/ /golem/database/operation/sessions/`CurrentSessionDataBaseQuerry "start_shot_no"`
    rm nohup.out 
    
    SubmitTokamakState "offline" 
}

function CloseSession(){
    CloseStuff
    Relax
    pkill -f json_status4remote.py 
    killall tail >/dev/null
    killall python3 >/dev/null
    rm -rf $SHM; # Final farewell
    

}



function ShutDown ()
{ 
        CloseStuff
        cd $SW/;./Dirigent.sh --chamber pumping='off'
        Broadcast $SHMS "$Ensemble" Sleep-downCall
        KillAllGMtasksEverywhere
        pkill -f json_status4remote.py
        sleep 5
        Call $RelayBoards Aten@Permanent OFF
        Call $RelayBoards Stop@Permanent ON; Relax; Call $RelayBoards Stop@Permanent OFF
        #echo "*B1OS7H"|telnet Quido-Permanent 10001;Relax;echo "*B1OS7L"|telnet Quido-Permanent 10001
        rm -rf $SHM;
}
