#!/bin/bash

SHM="/dev/shm/golem"
#SW_dir=`pwd`;export SW_dir

function Prerequisities()
{
    mkdir -p $SHM
    hostname > $SHM/hostname # migration to SuperMicro
    cp Dirigent.sh Commons.sh $SHM/
    #if [ -e /dev/shm/golem/session.setup ]; 
    #then 
        # setup aktualizace ...
        cp current.setup $SHM/session.setup
        cp `realpath current.setup` $SHM/
    #fi
        echo `realpath current.setup |xargs basename -s .setup` > $SHM/session_setup_name
        


    source $SHM/Commons.sh
    echo $((`CurrentShotDataBaseQuerry "shot_no"`)) > $SHM/shot_no 
}

Prerequisities


# SaveCommandLineParams()
    if [[ $1 == "--discharge" ]]; then 
    mkdir -p $SHMCLP
    rm $SHMCLP/*
    cp Dirigent.sh Commons.sh $SHM0/

    args=("$@")
    
    CL='./Dirigent.sh --discharge'
    #CL='./Dirigent.sh'

    while [ $# -gt 0 ]; do
   if [[ $1 == *"--"* ]]; then
        v="${1/--/}"
        declare $v="$2"
        echo $2 > $SHMCLP/$v
 #       echo $v=$2
           if [ $v == "comment" ] || [[ "$v" =~ "diagnostics." ]] || [[ "$v" =~ "discharge." ]] || [ $v == "ScanDefinition" ]; then
            CL="$CL --$v \"$2\"";
         elif [ $v == "discharge" ]; then
         echo ;
         else
          
          
          
          CL="$CL --$v $2"
        fi
   fi
  shift
done
echo "$CL" > $SHMCLP/CommandLine

set -- $args
fi





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

    LogItColor 10 "********* Broadcasting `echo "$what@$where" | tr a-z A-Z`"
    SubmitTokamakState "$what@$where"
    WWWmanagement "$what@$where"
    #LogItColor 5 "Musician:Dirigent .. playing $what"
    #source Dirigent.sh;$what #Do it at Dirigent as well
    for Collection in $where; do
        for Dev in ${!Collection}; do 
            #LogItColor 5 "Musician:$Dev .. testing presence $@"
            if  grep -qic "function $what" $Dev.sh || grep -qic "function $what" Commons.sh
                then 
                LogItColor 5 "Musician:$Dev .. playing $what"
                bash -c "
                source Commons.sh
                cd `dirname $Dev`; source `basename $Dev`.sh;
                $what "$@"" &
            fi
            SubBroadcast $Dev "$@" &
        done    
    done
	wait
    LogIt "**`basename $PWD`: `echo "$what@$where" | tr a-z A-Z` end"
}




function SubBroadcast(){
local where=$1
local what=$3
#echo "$@"

    LogItColor 2 "********* SubBroadcasting `echo "$what@$where" | tr a-z A-Z`"
    cd `dirname $where`;source `basename $where`.sh;cd $OLDPWD
    for Category in Devices; do
       for Item in ${!Category}; do
       TrackIt "$PWD/$Category/$Item.sh"
        if  grep -sqic "function $what" $Category/$Item.sh || grep -sqic "function $what" Commons.sh $Category/`dirname $Item`/Universals.sh; then
         if [[ $Item == RASPs* ]]; then
            RaspName=`dirname $Item|xargs basename`
            TaskName=`basename $Item`
            TrackIt "Subbroadcast ssh call ${Item#RASPs/} with $what"
            ssh $RaspName.golem "source $TaskName.sh;$what" &
         else
            TrackIt "Subbroadcast call ${Item} with $what"
            bash -c "source Commons.sh;cd $Category/`dirname $Item`; source `basename $Item`.sh;$what "$@"" &
          fi 
        fi
       done   
    done
    wait

}    


function SandBox()
{
######### Test part #############
        rm -rf  $SHM0
        Broadcast Everywhere PrepareDischargeEnv@SHM "$@" # Get ready the whole 
        exit
########### End test part ###################
}


#Main command interaction with user, here it starts
#============================================

TASK=$1
#COMMANDLINE=`echo $@|sed 's/-r //g'`
# ToDo replace special chars: echo '!@#[]$%^&*()-' | sed 's/[]!@#[$%^&*()-]/\\&/g' ..... \!\@\#\[\]\$\%\^\&\*\(\)\-


case "$TASK" in
   "") 
      echo "Usage: $0 [-d|--discharge] [-o|--open] [-t|--test]  [-s|--shutdown]"
      RETVAL=1
      ;;
      --ping)
      Broadcast Everywhere PingCheck
      ;;
      --wake)
      Broadcast Everywhere WakeOnLan
      ;;
      --sleep)
      Broadcast Everywhere SleepOnLan
      ;;
      --reset)
      KillAllGMtasksEverywhere
      pkill -f json_status4remote.py
      rm -rf /dev/shm/golem;mkdir -p /dev/shm/golem
     ;;
      --resetup)
      ssh -Y golem@Chamber.golem  "killall -u golem"
      ssh -Y golem@golem "killall xterm"
      rm -rf /dev/shm/golem;
      echo "Jeste sestrel rucne feedgnuplot"
      ;;
      --open)
      source current.setup # source requested setup Setups/XXYY.setup
      cp current.setup $SHM/session.setup
      cp `realpath current.setup` $SHM/
      source Commons.sh
      mkdir -p $SHMS;
      rsyncRASPs
      Broadcast Everywhere PrepareSessionEnv@SHM $DirigentServer # Get ready the whole dir struct @SHMS
      cd $SHMS;
      Broadcast Everywhere OpenSession
      SubmitTokamakState "idle" 
      tail -f $SHML/GlobalLogbook
      ;;
      --discharge|-d|--d)
        if [[ ! -d $SHMS ]]; then echo "DISCHARGE INITIATION PROBLEM:$SHMS does not exist. First open session, we guess!";exit;fi
        ActualChamberPressuremPa=`cat $SHM/ActualSession/SessionLogBook/ActualChamberPressuremPa`;
      	if (( $(bc -l <<< "${ActualChamberPressuremPa/e/E} > 100") && ($UBt != 0 || $Ucd != 0) )); then echo "DISCHARGE INITIATION PROBLEM: The pressure in the chamber is over 100 mPa"; exit;fi # Dummy discharges can pass
        echo  "##########################" >> $SHML/tokamak_state_log
        Speaker_ChargingInstructionVoice &
        Broadcast Everywhere PingCheck
        rm -rf  $SHM0
        Broadcast Everywhere PrepareDischargeEnv@SHM "$@" # Get ready the whole dir struct @SHM0
        cd $SHM0;
        Broadcast Everywhere GetReadyTheDischarge "$@"
        Broadcast Everywhere Arming 
        Speaker_CountDownVoice; 
        TriggerManagement Trigger; mRelax; 
        Broadcast Everywhere SecurePostDischargeState
        Broadcast DischargeBasicManagement PostDischargeAnalysis
        Broadcast OnStage_wave PostDischargeAnalysis
        HomepageReadyVoice
        #DischargeFunction PublishOnStageTasks #On Stage tasks to web
        Broadcast OffStage_wave PostDischargeAnalysis
        #Broadcast Others_wave PostDischargeAnalysis
        #Broadcast Analysis PostDischargeAnalysis
        #Broadcast Infrastructure PostDischargeAnalysis
        bash -c "cd $SHM0/Analysis/Homepage; source Homepage.sh; ScanIssues"
        WWWmanagement FinalizationWithoutAnnouncement # without StandbyAnnouncement
        WWWmanagement Finalization #Final homepage creation
        DischargeFunction FinalDischargeOperations # Files from #0 to #XXYYZZ
        DataReadyVoice
        SubmitTokamakState "idle" 



        
      #MakeDischarge  "$@"
      ;;
      --close_session|-c|--c|--close)
      Broadcast Everywhere CloseSession
      KillAllGMtasksEverywhere # nefunguje
      ;;
      --shutdown|-s)
        xterm -fg yellow -bg blue -title "Golem pumping end" -hold -e "source Commons.sh;VacuumManagement PumpingOFF" &
#        VacuumManagement xtermPumpingOFF &
        Broadcast Everywhere SleepOnLan
        KillAllGMtasksEverywhere
        pkill -f json_status4remote.py
        rm -rf $SHM;
      ;;
      --pon)
      #VacuumManagement xtermPumpingON
      # Workarround due to psql password
      xterm -fg yellow -bg blue -title "Golem pumping start" -hold -e "source Commons.sh;VacuumManagement PumpingON"
      ;;
      --bon) #baking ON
      xterm -fg yellow -bg blue -title "Golem baking start" -hold -e "source Commons.sh;ChamberManagement Baking_ON 200 8"
      ;;
      --poff)
      #VacuumManagement xtermPumpingOFF
      # Workarround due to psql password
      xterm -fg yellow -bg blue -title "Golem pumping end" -hold -e "source Commons.sh;VacuumManagement PumpingOFF"
      ;;
      --fc)
      WGcalH2
      ;;
      --sandbox|--snb)
      rm -rf  $SHM0
      Broadcast Everywhere PrepareDischargeEnv@SHM "$@" # Get ready the whole
      ;;
    --emergency|-e|--e)
      Broadcast Everywhere Emergency
      ;; 
      --kill|-k)
        KillAllGMtasksEverywhere
      ;;
      --reset|-r)
      KillAllGMtasksEverywhere
      rm -rf /dev/shm/golem;
       ;; 
      -b) # Broadcasts 
       if [ $2 == "os" ]; then Broadcast Everywhere OpenSession ;fi
       if [ $2 == "a" ];  then Broadcast Everywhere Arming ;fi
       if [ $2 == "rs" ]; then Broadcast Everywhere PrepareSessionEnv@SHM
                               Broadcast Everywhere PrepareDischargeEnv@SHM ;fi
       if [ $2 == "p" ];  then Broadcast Everywhere PingCheck ;fi
       if [ $2 == "s" ];  then Broadcast Everywhere SleepOnLan ;fi
       if [ $2 == "w" ];  then Broadcast Everywhere WakeOnLan ;fi
                               
      ;; 
      --log|-l|--l)
      tail -f $SHML/GlobalLogbook
      ;;
      --tt) #basic test
      ssh golem@Discharge.golem "source Trigger.sh;DummyTrigger"
      ;;
      --rs) 
      source Commons.sh ;rsyncRASPs 
      ;;
      --leave) #backup
      ./Dirigent.sh --backup
      git add .;git commit -am "The end of a day";git push;
      pull_newest_gitlab
      ;;
      --backup) #backup
      $psql_password;pg_dump golem_database > golem_database.sql; 
      rsync -r -u -v -K -e ssh --exclude '.git' $PWD svoboda@bn:backup/Dirigent/`date "+%y%m%d"`
      zip golem_database golem_database.sql;mpack -s "GM database `date`" golem_database.zip tokamakgolem@gmail.com;
      rm golem_database.*
      ;;
      --commit) #from develop to gitlab
      #git commit -am "$PAR1"
      ;;
      --dummy|--dd)
      ./Dirigent.sh --discharge --UBt 0 --TBt 1000 --Ucd 0 --Tcd 2000 --preionization 1 --gas H --pressure 10  --Bt_orientation "CW" --CD_orientation "CW"  --comment "Dummy test discharge"
      ;;
      --modest|--dm)
      ./Dirigent.sh --discharge --UBt 220 --TBt 1000 --Ucd 220 --Tcd 2000 --preionization 1 --gas H --pressure 10 --Bt_orientation "CW" --CD_orientation "CW"   --comment "Modest test discharge"
      ;;
      --standard|--ds)
      ./Dirigent.sh --discharge --UBt 800 --TBt 1000 --Ucd 450 --Tcd 2000 --preionization 1 --gas H --pressure 10  --Bt_orientation "CW" --CD_orientation "CW"   --comment "Standard test discharge"
      ;;
      --sujb|--dds)
      ./Dirigent.sh --discharge --UBt 800 --Ucd 400 --Tcd 1000  --Tres 2000 --pressure 20  --Bt_orientation "CW" --CD_orientation "CW"   --comment "Standardni test dlouhodobe stability"
      ;;
      --help|-h|--h)
      echo "**********Fequently used commands************"
      #git add .;git commit -am "HV powSup@NIM crate controll with database entry";git push;./Dirigent.sh -r pull_newest_gitlab;./Dirigent.sh --backup
      echo "Discharge ..."
      echo "./Dirigent.sh -d --UBt 880 --TBt 5 --Ucd 400 --Tcd 5 --preionization 1 --gas H --pressure 10 --Bt_orientation 'CW' --CD_orientation 'CW' --vacuum_shot 32592 --comment 'Standard discharge' (--ds)"
      echo "git add .;git commit -am \"log\";git push;./Dirigent.sh -r pull_newest_gitlab;./Dirigent.sh --backup # nutny pull i pro user:golem"
      
      alias

      ;;
esac


#Tuning ...
#./Dirigent.sh -k;rm -rf /dev/shm/golem;./Dirigent.sh --setup current.setup b PrepareSessionEnv@SHM
