from yaml import load
from yaml import Loader
from yaml import YAMLError
import sys

# Read modem configuration parameters from configuration file, e.g. power-port 
# and serial port. Configuration file contains uniquely-named modem entries.

# Allowed radio types
cellRadio = 'cell'
consoleRadio = 'console'


if len(sys.argv) != 3:
    print 'usage: ' + sys.argv[0] + ' configFilename radioName'
    exit(1)

filename = sys.argv[1]
radio = sys.argv[2]

try:
    config = load(open(filename), Loader=Loader)
except IOError as e:
    print filename + ' -  IOError: ' + str(e.errno) + ' ' + e.strerror
    exit(1)
except YAMLError as e:
    print "Error in configuration file: ", e
    exit(1)
except:
    print 'Error parsing ' + filename
    exit(1)

### print config
### print "keys: " + str(config.keys())

# Find specified radio in configuration
if radio in config:
    ### print 'found radio named ' + radio
    # Get entries for this radio
    entryList = config.get(radio)
    ### print 'entryList: ' + str(entryList)
    foundSerial = False
    foundPower = False
    for entry in entryList:

        ### print 'entry keys: ' + str(entry.keys())
        ### for key in entry:
            ### print str(key) + ': ' + str(entry.get(key))

        if "powerPort" in entry:
            powerPort = entry.get("powerPort")
            foundPower = True

        if "serialPort" in entry:
            serialPort = entry.get("serialPort")
            foundSerial = True

    if foundPower and foundSerial:
        print str(powerPort) + ' ' + str(serialPort)
        exit(0)
    else:
        if not foundPower:
            print 'powerPort not found for ' + radio
        if not foundSerial:
            print 'serialPort not found for ' + radio

        exit(1)

else:
    print 'radio \'' + radio + '\' not found in configuration file ' + filename
    exit(1)
