#!/usr/bin/env python
# This script is intended to be called from MEDM's Execute menu.
# Usage: instaSDF [EpicsChannel]
# The snap file loaded in SDF will be updated to
# reflect the current value of the EpicsChannel argument

import sys, re
from glob import iglob
import os.path as path

from tempfile import mkstemp
from shutil import move
from os import remove, close
from time import sleep

# ezca
import ezca as ez
ezca = ez.Ezca()

# CDS Python standard environment - defines cdsRoot
sys.path.append('/ligo/cdscfg')
import stdenv as cds
cds.INIT_ENV()
#
cdsRoot = cds.RTCDSDIR
filterDir = cds.CHANSDIR

#####
def pygrep(fileGlob, pattern):
  matches = []
  for fileName in iglob(fileGlob):
    with file(fileName, 'r') as f:
      for line in f:
        if re.search(pattern, line):
          matches.append(fileName)
          break
  return matches
#####
def changeSnap(snapFile, feName, channel, value):

    #Create temp file
    fh, newSnapFile = mkstemp()
    print 'TEMP SNAP ' + newSnapFile
    with open(newSnapFile,'w') as new_file:
        with open(snapFile) as old_file:
            for line in old_file:
              if re.search(channel, line):
                print 'WAS: ' + line.rstrip('\n')
                chan, flagA, oldValue, flagB = line.split(' ')
                line = chan + ' {:s} {:.15e} {:s}'.format(flagA, value, flagB)
                print 'NOW: ' + line.rstrip('\n')
              new_file.write(line)
    close(fh)

    moveFileTo = '/tmp/' + feName + '_' + path.basename(snapFile)
    print 'OLD SNAP moved to ' + moveFileTo

    # Move original file
    #move(snapFile, moveFileTo)
    # Move new file
    #move(newSnapFile, snapFile)


#####

##########
# main
##########

# need a channel name to work with
chan = ':'
chanSuffix = ''
if len(sys.argv) > 1:
  chan = sys.argv[1]
else:
  sys.exit('Need a channel name argument.')


# Split off the IFO and the top level system:
# H1:LSC-DARM -> H1, LSC-DARM
ifoName, chanName = chan.split(':', 1)

##############
# find FE name

# Grep for the channel in the autoBurt.req to find the FE name
targetDir = cdsRoot + '/target'
reqGlob = targetDir + '/*/*/autoBurt.req'
reqFileList = pygrep(cdsRoot + '/target/*/*/autoBurt.req', chan)

if not reqFileList:
  sys.exit('ERROR: ' + chan + ' not found in ' + reqGlob)
if len(reqFileList) > 1:
  sys.exit('ERROR: ' + chan + ' found in multiple files in ' + reqGlob)

feEpicsDir = path.dirname(reqFileList[0])
feName = path.split(path.split(feEpicsDir)[0])[1];

##############
# find DCU ID

# open the rtsystab, strip out comments and make list of models (IOP and user)
modelInfoFile = cdsRoot + '/cds/model_info.txt'
dcuids = {}
for line in open(modelInfoFile, "r"):
    li=line.strip()
    if not li.startswith("#"):
        string = line.rstrip('\n')
        # first word is the computer name, skip this 
        model,space,dcuid = string.partition(' ')
        dcuids[model] = dcuid

dcuid = dcuids[feName]
print chan + ' is on FE ' + feName + ' ' + dcuid

##############
# get SDF file name

sdfFileName = feEpicsDir + '/burt/' + ezca['FEC-' + dcuid + '_SDF_LOADED'] + '.snap'
if path.islink(sdfFileName):
  # follow symbolic link
  print 'SNAP ' + sdfFileName

  sdfFileName = path.realpath(sdfFileName)
  print ' links to ' + sdfFileName


##############
# change snap file
value = ezca[chanName]

# not really making changes yet...
changeSnap(sdfFileName, feName, chan, value)


##############
# load changes

sleep(1)
# ezca['FEC-' + dcuid + '_SDF_RELOAD'] = 2
print '==> This is the toothless version, so no action was taken'

