#!/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

'''
SHINS will also provide a shutdown procedure consisting in the following steps (see AD3):
1.    Parking the instrument. This will be done through the sequencer using a specific OB. In particular:
    a.    Stop running templates or OB (if any);
    b.    Close instrument shutter;
    c.    Home all the motorized stage but the derotator and deployable arm deployer;
    d.    Move the deployable arm deployer to the OUT position (free the optical path from M3 to LBTI);
    e.    Switch off calibration lamps acting on the PDU (if on);
    f.    Send to C-RED2 the shutdown command;
2.  Switch off the workstation and the related hardware. This will
    be done with a custom bash script acting on the remaining PDU
    elements. In particular:    
    a.    Switch off the C-RED2;
    b.    Switch off the RTC;
    c.    Switch off the DM;
    d.    Switch off the MoCon;
    e.    Switch off the Scientific Camera;
3.    Stop basdard services in the instrument workstation;
4.    Shut down scientific camera workstation;
5.    Shut down instrument workstation.
'''

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

# 1 a
logger.warning("Aborting any OB...")
#os.system("ssh -t observer@sashaws '/opt/local/sharknir/bin/setINDI \'sasha.stop.value=On\''")
#sleep(1)

seq = Sequencer()

seq.ob_file = obdir+"SHARKNIR_gen_abort.xml"
seq.execute()
logger.warning("Aborting any OB... DONE")

# 1 b-e
logger.warning("Parking instrument...")
seq.ob_file = obdir+"SHARKNIR_gen_park.xml"
seq.execute()
logger.warning("Parking instrument... DONE")

# 1 f
logger.warning("Shutting down technical camera...")
seq.ob_file = obdir+"SHARKNIR_gen_tiptilt_shutdown.xml"b
seq.execute()
logger.warning("Shutting down technical camera... DONE")

# 2 a-d
logger.warning("Switching off PDU elements...")
pdu_Off_Dict = {
    "MOCON": "OFF",
    "CAL_FIBER_FOCUS_LAMP": "OFF",
    "CAL_FF_LAMP": "OFF",
    "CAL_FIBER_DEFOCUS_LAMP": "OFF",
    "MACIE": "OFF",
    "DM": "OFF",
    "RTC": "OFF",
    "CRED2": "OFF"
    "ARDUINO": "OFF",
    "MEDIA1": "OFF",
    "MEDIA2": "OFF",
    "LAKESHORE": "OFF",    
    "ELECTROVALVE": "OFF"
}
os.setupInstrument(pdu_Off_Dict)
#os.instrumentSetup(pdu_Off_Dict)
logger.warning("Switching off PDU elements... DONE")

# 3
logger.warning("Stopping monit services...")
os.system("sudo monit stop all")
logger.warning("Stopping monit services...DONE")

# 4
logger.warning("Shutting down scientific camera workstation...")
os.system("ssh observer@sashaws 'sudo shutdown -h now'")
logger.warning("Shutting down scientific camera workstation... DONE")

# # # 5
# logger.warning("Shutting down this workstation... bye.")
# os.system("sudo shutdown -h now")
