#!/usr/bin/env python
"""Parser for parsing epicsEnvSet commands
These take these forms
1) epicsEnvSet("IOC","sioc-li20-pm20")
2) epicsEnvSet IOC_SUFF "PM20"
3) epicsEnvSet ID 695

"""

import os
import sys
from plex import *
import random
import StringIO

# Here's where we define the lexicon for the parser. 
letter = Range("AZaz")
digit = Range("09")
hspace = Any(" \t")
space = Any(" \t\n")
spchars = Any(".-_:{}+/*$<>")
newline = Str("\n")
comma = Str(",")
quote = Str('"')
name = Rep1(letter | digit | spchars)
namewithspaces = Rep1(letter | digit | spchars | hspace)
nameinquotes = quote + name + quote
namewithspacesinquotes = quote + namewithspaces + quote
openParan = Str("(")
closeParan = Str(")")
comment = Bol + Str("#") + Rep(AnyBut("\n")) + Str("\n")

fileLexicon = Lexicon([
    (comment,  'comment'),
    (space, IGNORE),
    (Str("epicsEnvSet("), Begin("Name")),
    (Str("epicsEnvSet") + Rep(hspace) + Str("("), Begin("Name")),
    (Str("epicsEnvSet "), Begin("Name")),
    State('Name', [
                    (nameinquotes, 'name'),
                    (name, 'name'),
                    (quote, IGNORE),
                    (hspace, Begin("Value")),
                    (comma, Begin("Value"))
                    ]),
    State('Value', [
                    (namewithspacesinquotes, 'value'),
                    (name, 'value'),
                    (quote, IGNORE),
                    (hspace, IGNORE),
                    (comma, IGNORE),
                    (newline, Begin('')),
                    (closeParan, Begin(''))
                    ]),
    (space, IGNORE)
])

def parseSingleEnvPathsLine(line):
    '''Parses a single envPaths line and return the name/value TUPLE'''
    scanner = Scanner(fileLexicon, StringIO.StringIO(line))
    currentName = None
    currentValue = None
    while 1:
        token = scanner.read()
        if token[0] is None:
            break
        elif token[0] == 'name':
            currentName = token[1].strip('"')
        elif token[0] == 'value':
            currentValue = token[1].strip('"')
            return (currentName, currentValue)
        else:
            sys.stderr.write("Unknown token" + token)

# if __name__ == "__main__":
#     parseAndReplaceEnvPathsFile(sys.argv[1], {'TOP': 'ABC123'})
