#!/usr/bin/env python

from sequencer import Sequencer
from util.shinsLogger import logger
import util.functions as ufun
import util.variables as uvars
import subprocess
import os
from time import sleep

'''
Starting from this state, the startup procedure consists in the following steps:
1.    Manually switch on the scientific camera workstation;
2.    Manually switch on the instrument workstation;
3.    Launch a custom script on the instrument workstation acting on the PDU elements, that will:
    a.    Switch on the C-RED2;
    b.    Switch on the DM;
    c.    Switch on the MoCon;
    d.    Switch on the MACIE electronics (SCICAM);
    e.    Switch on the RTC after 10 seconds;
4.    Restart the monit services related to the basdard services that control previous devices.
'''

obdir = "/opt/tan/share/shins/templates/ob/"


logger.warning("Resetting sasha...")
os.system("ssh -t observer@sashaws 'sudo /usr/bin/killall indiserver'")

# Media converter on!!
aliasDict = { "MEDIA1": "ON",
              "MEDIA2": "ON",
              "LAKESHORE": "ON",
              "ELECTROVALVE": "ON",
              "MACIE": "ON",
              "CRED2": "ON",
              "DM": "ON",
              "MOCON": "ON"
              }

logger.warning("Switching on Media converters...")
# 3 a-c
logger.warning("Switching on CRED DM MOCON elements...")
# ufun.switch_on_off_pdu_elements(uvars.ipPDU1, aliasDict, onoff="ON")
#os.instrumentSetup(aliasDict)
os.setupInstrument(aliasDict)
logger.warning("Switching on elements... DONE")

# 3 e
logger.warning("waiting some seconds before starting RTC...")
sleep(15)
aliasDict = { "RTC": "ON" }
#os.instrumentSetup(aliasDict)
os.setupInstrument(aliasDict)
logger.warning("Switching on PDU elements... DONE")

# 4
logger.warning("Restarting monit services...")
sleep(5)
os.system("sudo monit restart all")
sleep(3)

line=''
while ("Thread" not in line) and ("Start" not in line) :
    line = subprocess.check_output(['tail', '-1', "/opt/tan/var/log/obsControlServer.log"])
    print(line)
    sleep(0.1)

logger.warning("Restarting monit services...DONE")

# 5
seq = Sequencer()

logger.warning("Init instrument...")
seq.ob_file = obdir+"SHARKNIR_gen_init.xml" 
seq.execute()
logger.warning("Init instrument... DONE")

# 5 bis
logger.warning("Init RTC...")
seq.ob_file = obdir+"SHARKNIR_gen_tiptilt_init.xml"
seq.execute()
seq.ob_file = obdir+"SHARKNIR_gen_tiptilt_setup_and_start.xml"
seq.execute()
logger.warning("Init RTC... DONE")
