#!/bin/bash

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


Drivers="uControllers/Arduino8relayModul uControllers/UniPi"

DeviceList="ITs/RasPi3-c/Bt_Ecd PowerSupplies/GWInstekPSW-a/Working_Gas   Oscilloscopes/RigolMSO5204-c/Bt_Ecd_Monitor PowerSupplies/DIN12-24V-a/Basic  PowerSupplies/GWInstekPSW-b/Preionization PowerSupplies/AC250Kxxx-a/Preionization Infrastructure/Signalization/RedBeacon-a/Discharge Infrastructure/Signalization/SignalTower-a/Admittance" 
#PowerSupplies/RigolPS831A-a/HVsubstitute" # in case LV substitute



function PrepareDischargeEnv@SHM() {


    # Maintain Default/Actual/Submitted Parameters
    
   PrepareEnvironment@SHM $SHM0 # Get ready the whole dir struct
      
   cp $SW/Dirigent.sh $SW/Commons.sh $SHM0/
   cp $SHM/* $SHM0/ 2>/dev/null

# And Dirigent extras:   
#       mkdir -p $SHM0/Operation/Dirigent/Flags
#       rsync -v $SW/Operation/Dirigent/Flags/* $SHM0/Operation/Dirigent/Flags/ &>/dev/null # Dirigent force

       
   chmod -R g+rwx $SHM
   rm -rf $SHM0/Production/Parameters
   for i in Parameters Performance;do mkdir  -p $SHM0/Production/$i;done
   cp $SHM/Production/hostname $SHM0/Production/
   echo "Times" > $SHM0/Production/FunctionTimes
   cp $SHM/Production/* $SHM0/Production/Performance/
   cp $SHM/whole.setup $SHM0/


   cp $SHMCLP/* $SHMP/
   cp $SHMP/comment $SHM0/

#   Call $SHM0/Operation/Dirigent/Flags PutDirigentParametersIntoGame # Dirigent force

   
    # and defaults:
   FullCommandLine="./Dirigent.sh \\ \\n--discharge "
   for i in $(<$SHM0/Production/Performance/AllInstruments);
        do 
            item=$(dirname $i|sed 's/\//\./g'| tr '[:upper:]' '[:lower:]');
            #Default parameters management
            if [[ ! -f $SHMP/$item ]] && [[ -f $SW/$i/$item.default ]];then
                LogIt "Copying Default $item to $SHMP .."
                cp $SW/$i/$item.default $SHMP/$item
            fi
            #Full command line management
            if [[ -f $SHMP/$item ]];then
            FullCommandLine="$FullCommandLine--$item \"$(<$SHMP/$item)\"  \\\\n"
            fi
        done
    FullCommandLine="$FullCommandLine--comment '$(<$SHM0/comment)' "
    echo  "Well-arranged command line form:" >>$SHMP/FullCommandLine
    echo "========================" >>$SHMP/FullCommandLine
    echo  "" >>$SHMP/FullCommandLine
    echo -ne $FullCommandLine >>$SHMP/FullCommandLine
    echo  "" >>$SHMP/FullCommandLine
    echo  "" >>$SHMP/FullCommandLine
    echo  "Classical command line form:" >>$SHMP/FullCommandLine
    echo "========================" >>$SHMP/FullCommandLine
    echo  "" >>$SHMP/FullCommandLine
    cat $SHMP/CommandLine >>$SHMP/FullCommandLine
    LogIt $FullCommandLine
   #cp -u $SW/Management/DefaultParameters/* $SHMP/
   
   
   
   cp $SHML/WG_calibration_table4H2 $SHMP/
   # and now actuals from command line:


   #cp $SHMTAGS/* $SHM0/Production/Tags/
   
   date "+%y-%m-%d" > $SHM0/shot_date
   date "+%H:%M:%S" > $SHM0/shot_time

   
   mkdir -p $SHM0/Production/Parameters/SystemParameters
   cp $SW/Operation/Discharge/Parameters/System/* $SHM0/Production/Parameters/SystemParameters/ 2>/dev/null
   
 


     
    for Collection in $Ensemble; 
    do 
      echo ${!Collection} > $SHM0/Production/$Collection
    done  

        
    #echo "<meta http-equiv='Refresh' content='0; url=\"http://golem.fjfi.cvut.cz/shots/$((`cat $SHM/shot_no`+1))\"'/>" >$SHM/previous_discharge.html
    
    echo "This shot number" >$SHM0/$((`cat $SHM/shot_no`+1))
    
    echo "<meta http-equiv='Refresh' content='0; url=\"http://golem.fjfi.cvut.cz/shots/$((`cat $SHM/shot_no`))\"'/>" >$SHM0/$((`cat $SHM/shot_no`)).html

    shot_no=$((`cat $SHM/shot_no`+1));echo $shot_no>$SHM/shot_no; echo $shot_no>$SHMS/shot_no;echo $shot_no>$SHM0/shot_no
    SetCurrentStatus shot_no $shot_no
	LogItColor 11 "########################################################"
    LogItColor 11 "################# Discharge #$shot_no ##################"
    LogItColor 11 "########################################################"
    LogIt "Command Line Request: `cat $SHMS/session_mission`"

    wget http://192.168.2.244/set.xml?type=v\&val="$shot_no" #Numerical display
    
   
    InsertCurrentShotDataBase "(shot_no, start_timestamp, pre_comment, dirigent_server_loadavg, session_id, session_mission, session_date, session_setup) VALUES ($((`cat $SHMS/shot_no`)), '`date "$date_format"`', '$(<$SHMP/comment)','`cat /proc/loadavg`',`cat $SHMS/session_id`, '`cat $SHMS/session_mission`','`cat $SHMS/session_date`','`cat $SHMS/session_setup_fullname`')"
    
    InsertCurrentShotDataBaseDischCommand
 
    
    currshot=/golem/database/operation/shots/$shot_no
    ln -s $SHM0 $currshot # we need to provide data even within the discharge temporally
    unlink /golem/database/operation/shots/0
    ln -s $currshot /golem/database/operation/shots/0
    
    #cp $SW/Infrastructure/Homepage/DynamicIndex/* $SHM0/  # PM removed until fixing SSE
    #echo -n preparing_discharge > $SHML/tokamak_state    
    
    }
    


  
function CheckAbilityToMakeDischarge
{

        if [[ ! -d $SHMS ]]; then echo "DISCHARGE INITIATION PROBLEM:$SHMS does not exist. First open session, we guess!";exit;fi
             
        ActualChamberPressuremPa=$(<$SHM/ActualSession/SessionLogBook/ActualChamberPressuremPa);
        if  (( $(bc -l <<< "${ActualChamberPressuremPa/e/E} > 100") ))   && ! grep -q 'dummy' $SHMCLP/operation.discharge 2>/dev/null; 
        then 
            echo "DISCHARGE INITIATION PROBLEM: The pressure in the chamber is over 100 mPa"; 
            Speaker Problems/ChamberPressureOver100mPa;exit;
        fi 
        
        if PingAllDevices;
        then LogIt Ping OK; 
        else 
            Speaker Problems/PingCheckFailed;exit;
        fi
        
            # Check if requested parameters are within allowed range
        $psql_password;psql -c "UPDATE infrastructure.bt_ecd SET $(</golem/shm_golem/CommandLineParameters/infrastructure.bt_ecd) WHERE shot_no=0" -q -U golem golem_database

        if [ `SelectDataBaseQuerry 0 infrastructure.bt_ecd u_cd` -gt  700 ]; then EchoItColor 1 "Ucd over limit";Speaker Problems/The-discharge-cannot-be-proces;exit; fi
        if [ `SelectDataBaseQuerry 0 infrastructure.bt_ecd u_bt` -gt  1300 ]; then EchoItColor 1 "Ubt over limit";Speaker Problems/The-discharge-cannot-be-proces;exit; fi

    #if [ $(<$SHM0/Infrastructure/Bt_Ecd/Parameters/u_bt) -gt 1300 ]; then EchoItColor 1 "UBt over limit 1300 V !!"; Speaker Problems/The-discharge-cannot-be-proces;return ;fi #Takhle to nejde, hodnoty jeste zdaleko nejsou v takovemto stavu

        $psql_password;psql -c "UPDATE infrastructure.workinggas SET $(</golem/shm_golem/CommandLineParameters/infrastructure.workinggas) WHERE shot_no=0" -q -U golem golem_database

        if [ `SelectDataBaseQuerry 0 infrastructure.workinggas p_h` -gt  100 ]; then EchoItColor 1 "pressure over limit";Speaker Problems/The-discharge-cannot-be-proces;exit; fi

        #DODELAT stejne predionizaci !


      	
}

function CheckAbilityToMakeDischargeTOBECOMPLETED
{
      	UBt=`ssh Charger 'source Bt_Ecd.sh;OpenOscDVMchannel 3;sleep 1;echo ":DVM:CURRENT?">> /dev/shm/ChargerOsc/OscRequestStream;sleep 1;DVMDisable;tail -1 /dev/shm/ChargerOsc/OscRespondStream|xargs printf "%4.0f\n"'`
      	LogIt "Napeti na Bt kondenzatoru pred pripravou: $UBt V"
        if [ $UBt -lt -100 ];then LogIt "DISCHARGE INITIATION PROBLEM: The voltage UBt is out of range -100V";
      	exit;fi
      	Relax
      	Ucd=`ssh Charger 'source Bt_Ecd.sh;OpenOscDVMchannel 4;sleep 1;echo ":DVM:CURRENT?">> /dev/shm/ChargerOsc/OscRequestStream;sleep 1;DVMDisable;tail -1 /dev/shm/ChargerOsc/OscRespondStream|xargs printf "%4.0f\n"'`
        LogIt "Napeti na CD kondenzatoru pred pripravou: $Ucd V"
      	if [ $Ucd -lt -100 ];then LogIt "DISCHARGE INITIATION PROBLEM: The voltage Ucd is out of range -100V"; exit;fi
}


function ConditionalBroadcast
{
    local ConditionToBeTested=$1
    local Where=$2
    local What=$3
    if [[ $(<$SHM0/Operation/HigherPower/$ConditionToBeTested) != 'off' ]];then 
        Broadcast $SHM0 $Where $What;
    else
        LogItColor 1 "Broadcast of the $What@$Where is switched off by the $ConditionToBeTested request "
    fi
}

function Discharge
{
        #PrepareDischargeEnv@SHM
        #return
        PrepareEverything
        PreTrigger
        Trigger
        PostTrigger #Broadcast SecurePostDischargeState & RawDataAcquiring
        PostDischargeAnalysis
        FinalDischargeOperations # Publish everything from $SHM0 -> http://golem../shots/#ShotNo 
}




function PrepareEverything
{
        CheckAbilityToMakeDischarge
        echo  "##########################" >> $SHML/tokamak_state_log
        PrepareDischargeEnv@SHM
        GeneralTableUpdateAtDischargeBeginning
}
        
function PreTrigger
{
        Speaker ChargingInstructions &     
        cd $SHM0 #Bez tohoto to zatim nejde.
        Broadcast $SHM0 "$Ensemble" GetReadyTheDischarge "$@"
        Call $RelayBoards Zarivky@MiscII ON
        Call $RelayBoards Reflektory@MiscII ON
        Broadcast $SHM0 "$Ensemble" Arming
        Speaker CountDown
        Call $SHMS/Infrastructure/WorkingGas LogActualChamberPressure
}

function Trigger
{
    ssh Chamber  "source Rasp-Trigger.sh;Trigger" # Chamber should be changed into Discharge
    Relax
}


function PostTrigger
{        
     
        Broadcast $SHM0 "$Ensemble" SecurePostDischargeState
        UpdateCurrentShotDataBase "\
        \"U_bt_discharge_request\"='$(<$SHM0/Infrastructure/Bt_Ecd/Parameters/u_bt)',\
        \"U_cd_discharge_request\"='$(<$SHM0/Infrastructure/Bt_Ecd/Parameters/u_cd)',\
        \"X_working_gas_discharge_request\"='$(<$SHM0/Infrastructure/WorkingGas/Parameters/s_gas)',\
        \"p_working_gas_discharge_request\"='$(<$SHM0/Infrastructure/WorkingGas/Parameters/p_h)',\
        \"t_bt_discharge_request\"='$(<$SHM0/Infrastructure/Bt_Ecd/Parameters/t_bt)',\
        \"t_cd_discharge_request\"='$(<$SHM0/Infrastructure/Bt_Ecd/Parameters/t_cd)'\
        "
        Call $RelayBoards Zarivky@MiscII OFF
        Call $RelayBoards Reflektory@MiscII OFF
        Call $SHM0/Diagnostics/PlasmaDetection PostDischargeAnalysis #Tohle MUSI dobehnout SAMO
        Call $SHM0/Diagnostics/BasicDiagnostics PostDischargeAnalysis &
        ConditionalBroadcast Parameters/rawdataacquiring Devices RawDataAcquiring
        wait #for the end of RawDataAcquiring@Devices or PostDischargeAnalysis@BasicDiagnostics
}

function PostDischargeAnalysis
{
        WWWmanagement PostDischargeAnalysis@DischargeBasicManagement
        ConditionalBroadcast Parameters/diagnostics_onstage Diagnostics_OnStage PostDischargeAnalysis
        WWWmanagement PostDischargeAnalysis@OnStage_wave
        #ConditionalBroadcast Parameters/diagnostics_onstage Diagnostics_OnStageWithoutBasicDiagnostics PostDischargeAnalysis
        #Call $SHM0/Infrastructure/Homepage/Basic IndexGeneration
        Speaker HomepageReady
        #DischargeFunction PublishOnStageTasks #On Stage tasks to web
        ConditionalBroadcast Parameters/diagnostics_offstage Diagnostics_OffStage PostDischargeAnalysis
        ConditionalBroadcast Parameters/analysis Analysis PostDischargeAnalysis
        ConditionalBroadcast Parameters/infrastructure Infrastructure PostDischargeAnalysis
        bash -c "cd $SHM0/Infrastructure/Homepage; source driver.sh; ScanIssues"
        WWWmanagement FinalizationWithoutAnnouncement # without StandbyAnnouncement
        WWWmanagement Finalization #Final homepage creation
        qrencode -s 30 -o Production/qrcode.jpg http://golem.fjfi.cvut.cz/shots/$(<$SHM/shot_no)
}


 
 function FinalDischargeOperations() {
 
    UpdateCurrentShotDataBase "end_timestamp='`date "$date_format"`'"
    shot_no=`cat $SHM/shot_no`
    currshot=/golem/database/operation/shots/$shot_no
    unlink $currshot
    mkdir -p $currshot
    cp -r $SHM0/* $SHM0/*.* $currshot/ 1>/dev/null 2>/dev/null
    cp $SHM0/Infrastructure/Homepage/FinalizationWithoutAnnouncement.html $currshot/index.html
    unlink /golem/database/operation/shots/0
    ln -s $currshot /golem/database/operation/shots/0
    chmod -R g+rwx $SHM0
    Speaker The-end-of-the-discharge-proce
    SubmitTokamakState "idle" 
    
     if [[ $(<$SHM/Production/style) == 'dummy' ]]; then
        rm $SHM/Production/style
        echo It was a dummy discharge
     fi
   
 }
 
 function Sleep-downCall()
{ 
    Call Infrastructure/Support/RelayBoards/SwBo_VaccGdHV DischargeSystemDisEngage
}
 
  
  function Emergency() {
    Bt_Ecd_Management SecurePostDischargeState
    WorkingGasManagement SwitchOutAllGases
 }
 

    


