#!/usr/bin/env python

'''This module parses the screen IOCs file. The main method is the parseScreenIOCs'''
from __future__ import print_function

import sys
from plex import *
import globals


# Here's where we define the lexicon for the parser.
# This is based on the format of the screenIOCs file - see parseScreenIOCs for a specification
letter = Range("AZaz")
digit = Range("09")
hspace = Any(" \t")
spchars = Any("-_.")
comma = Str(",")
quote = Str('"')
pathSeparator = Str("/")
name = Rep1(letter | digit | spchars)
number = Rep1(digit)
path = pathSeparator + Rep1(name | pathSeparator)
space = Any(" \t\n")
comment = Bol + Str("#") + Rep(AnyBut("\n"))  + Eol
iocName = Bol + name
description = Str("#") + Rep(AnyBut("\n"))  + Eol

fileLexicon = Lexicon([
    (comment, IGNORE),
    (space, IGNORE),
    (iocName, 'iocName'),
    (path, 'path'),
    (number, 'port'),
    (name, 'genericname'),
    (description, 'description')
])

def convertFileToTokens(screenIOCsFileName):
    '''This method does the actual parsing. It converts the screenioc file into a list of tokens.
    Unsure if there is a proper grammmar for this file so go first to a list of tokens and then to iocinfo'''
    tokens = []
    with open(screenIOCsFileName, 'r') as f:
        scanner = Scanner(fileLexicon, f, screenIOCsFileName)
        while 1:
            token = scanner.read()
            if token[0] is None:
                break
            tokens.append(token)
    return tokens

def parseScreenIOCs(screenIOCsFileName):
    '''Parse the screen IOCS file whose path is specified in screenIOCsFileName and return a dict of IOCName -> Info.
    Info can be one of these types - the type of the info is in the type column
    1) type:IOC - All hard IOCs connecting thru a terminal server have names that begin with ioc/eioc. For example, ioc-b34-bp02. 
    These have columns for
    1.1) iocName/Alias
    1.2) Terminal
    1.3) Port No.
    1.4) Host where screen is run
    1.5) Comments (must start with #)
    For example, 
    ioc-b34-bp02 ts-b34-nw01     2002       lcls-dev1       # bpm test ioc 
    2)type:SIOC - All soft IOCs for whom we expect an executable path have names that begin with sioc. For example, sioc-sys0-cv01.
    These have columns for
    2.1) iocName/Alias
    2.2) Full path to executable
    2.3) A fixed field that is always the string sioc
    2.4) Host where screen is run
    2.5) Comments (must start with #)
    For example, 
    sioc-sys0-cv01 /afs/slac/g/lcls/epics/iocCommon/sioc-sys0-cv01/bin/CAMACSoft            sioc     lcls-dev1
    3) type:VIOC - All hard IOCs connecting thru a SSH session have names that begin with a vioc. For example, vioc-b15-mg01
    These have columns for
    3.1) iocName/Alias
    3.2) Machine name hosting the IOC+ssh session
    3.3) UserID that we ssh as.
    3.4) Comments (need not start with #)
    For example,
    vioc-b15-mg01         eioc-b15-mg01         laci       lcls-dev1     embedded ATOM-MCOR IOC Test Stand
    '''
    if globals.verbose:
        print("Parsing screenIOCs file {0}".format(screenIOCsFileName))
    tokens = convertFileToTokens(screenIOCsFileName)
    # We now walk thru the tokens and use the fact that hard IOC's have a port in column 3 and SIOC's a path in column 2.
    iocInfos = {}
    currentIOCInfo = None
    columnNumber = 1
    for token in tokens:
        if token[0] == 'iocName':
            if currentIOCInfo:
                iocInfos[currentIOCInfo['name']] = currentIOCInfo
                currentIOCInfo = None
            currentIOCInfo = {}
            columnNumber = 1
            currentIOCInfo['name'] = token[1]
        elif token[0] == 'path':
            if columnNumber == 2:
                currentIOCInfo['type'] = 'SIOC'
            currentIOCInfo['executable'] = token[1]
        elif token[0] == 'port':
            currentIOCInfo['type'] = 'HIOC'
            currentIOCInfo['port'] = token[1]
        elif token[0] == 'description':
            currentIOCInfo['description'] = token[1]
        elif token[0] == 'genericname':
            # Now's the tricky part; we use type and then column number to intelligently place the token in the correct place
            if 'type' in currentIOCInfo:
                if currentIOCInfo['type'] == 'HIOC':
                    # We'd know the HIOC's type only in column 4 after the port number
                    currentIOCInfo['screenhost'] = token[1]
                elif currentIOCInfo['type'] == 'SIOC':
                    # For SIOC's the only genericname that matters is column 4; column 3 is fixed as sioc
                    if token[1] != 'sioc' and token[1] != 'SIOC':
                        currentIOCInfo['screenhost'] = token[1]
                elif currentIOCInfo['type'] == 'VIOC':
                    # We'd know the VIOC's type only in column 4 after the user name; VIOC's do not have a screenhost
                    raise Exception("Error parsing screenioc. Encountering generic name in column".format(columnNumber))
                else:
                    raise Exception("Unknown IOC type".format(currentIOCInfo['type']))
            else:
                if columnNumber == 2:
                    # We don't really care about the type here; both VIOC's and HIOC's use the same attribute
                    currentIOCInfo['terminalserver'] = token[1]
                elif columnNumber == 3:
                    # A generic name in column 3 tells us that this a VIOC
                    currentIOCInfo['type'] = 'VIOC'
                    currentIOCInfo['user'] = token[1]
                else:
                    raise Exception("Error parsing screenioc. Encountering generic name in column {}".format(columnNumber))
        else:
            print("Unrecognized token {0}".format(token))
        columnNumber = columnNumber + 1
    if currentIOCInfo:
        iocInfos[currentIOCInfo['name']] = currentIOCInfo
        currentIOCInfo = None
    return iocInfos

        
   
if __name__ == "__main__":
    from pprint import pprint
    iocInfos = parseScreenIOCs(sys.argv[1])
    pprint(iocInfos)
