#!/usr/bin/python

"""
    This module contains the deployment script to update the AMT FW
"""

import string, os, os.path, shutil, sys, popen2, systemMgr
from logMgr import addLogRecord,CRITICAL,ERROR,WARNING,INFO,DEBUG
from config import DeploymentStore, DeployPath
from deploymentData import ATSTATE,FAILURE,UPDATE,REFRESH,REBOOT,UNSUPPORTED
try:
    __file__
except:
    __file__ = __name__

hostIP = 0      # -N n.n.n.n
subnetMask = 1  # -S n.n.n.n
gatewayIP = 2   # -G n.n.n.n
dnsIP = 3       # none
domain = 4      # none
hostName = 5    # -N nodename

amtSpecs = {
    'S3000': ['10.243.42.235','255.255.252.0','10.243.42.251','10.127.1.11','intel.com','aspenhill1']
}
amtRestoreSpecs = {
    'S3000': ['0.0.0.0','0.0.0.0','0.0.0.0','0.0.0.0','nowhere.way','noname']
}

def getSpec(restore):
    ret, system = systemMgr.queryProperty(0,'IntelBIOSID','BoardFamilyID','',{})
    if not system or ret:
        print 'Intel board family unavailable: ret = %d'%ret
        addLogRecord(0,__file__, ERROR,'Intel board family unavailable: ret = %d'%ret)
        return 0
    if not system == 'S3000':
        print 'AMT only on S3000 systems'
        addLogRecord(0,__file__, INFO,'AMT only on S3000 systems')
        return 0
    if restore:
        if not amtRestoreSpecs.has_key(system):
            print 'system %s is an unsupported AMT system'%system
            addLogRecord(0,__file__, ERROR,'system %s is an unsupported AMT system'%system)
            return 0
        return amtRestoreSpecs[system]
    else:
        if not amtSpecs.has_key(system):
            print 'system %s is an unsupported AMT system'%system
            addLogRecord(0,__file__, ERROR,'system %s is an unsupported AMT system'%system)
            return 0
        return amtSpecs[system]
    return 0

def checkState(restore=0):
    """
        checkState() returns ATSTATE if at desired state
        checkState() returns FAILURE if state can't be achieved
        checkState() returns REFRESH if system info refresh is needed once configured
    """
    amtSpec = getSpec(restore)
    if not amtSpec:
        return FAILURE
    ret, value = systemMgr.queryProperty(0,'AMT','Local Addr','',{})
    if ret < 0:
        addLogRecord(0,__file__, ERROR,'AMT Local Addr unavailable: ret = %d'%ret)
        return REFRESH
    if not value == amtSpec[hostIP]:
        return REFRESH
    ret, value = systemMgr.queryProperty(0,'AMT','Subnet Mask','',{})
    if ret < 0:
        addLogRecord(0,__file__, ERROR,'AMT Subnet Mask unavailable: ret = %d'%ret)
        return REFRESH
    if not value == amtSpec[subnetMask]:
        return REFRESH
    ret, value = systemMgr.queryProperty(0,'AMT','Gateway','',{})
    if ret < 0:
        addLogRecord(0,__file__, ERROR,'AMT Gateway unavailable: ret = %d'%ret)
        return REFRESH
    if not value == amtSpec[gatewayIP]:
        return REFRESH
    ret, value = systemMgr.queryProperty(0,'AMT','Primary DNS','',{})
    if ret < 0:
        addLogRecord(0,__file__, ERROR,'AMT Primary DNS unavailable: ret = %d'%ret)
        return REFRESH
    if not value == amtSpec[dnsIP]:
        return REFRESH
    ret, value = systemMgr.queryProperty(0,'AMT','Domain Name','',{})
    if ret < 0:
        addLogRecord(0,__file__, ERROR,'AMT Domain Name unavailable: ret = %d'%ret)
        return REFRESH
    if not value == amtSpec[domain]:
        return REFRESH
    ret, value = systemMgr.queryProperty(0,'AMT','Host Name','',{})
    if ret < 0:
        addLogRecord(0,__file__, ERROR,'AMT Host Name unavailable: ret = %d'%ret)
        return REFRESH
    if not value == amtSpec[hostName]:
        return REFRESH
    print 'AMT has correct configuration'
    addLogRecord(0,__file__, INFO,'AMT has correct configuration')
    return ATSTATE

def amtConfig(restore=0):
    state = checkState(restore)
    if state < UPDATE:
        return state
    amtSpec = getSpec(restore)
    if not amtSpec:
        return FAILURE

    print "running an example of configuring the AMT FW using amtcfg ..."

    args = '-I %s -S %s -G %s -P %s -N %s -H %s'%(amtSpec[hostIP],amtSpec[subnetMask],amtSpec[gatewayIP],amtSpec[dnsIP],amtSpec[domain],amtSpec[hostName])

    from config import getstatusoutput
    status, output = getstatusoutput("amtcfg %s"%(args))
    if status:
        print 'amtcfg %s failed: status = 0x%x, %s'%(args,status,output)
        addLogRecord(0,__file__, ERROR,'amtcfg %s failed: status = 0x%x, %s'%(args,status,output))
        return FAILURE
    return REFRESH

if __name__ == '__main__':
    """
    this script assumed these enviroment variables have been set:
    (see deploy.sh or deploy.cmd)
        DeployPath
        DeploymentStore
        PATH
        LD_LIBRARY_PATH (Linux)
        PYTHONPATH
    """
    if len(sys.argv) == 1:
        restore = 0
    elif len(sys.argv) == 2 and sys.argv[1] == '0':
        restore = 0
    else:
        restore = 1
    for i in [1,2,3]:   # try 3 time to get to state
        state = amtConfig(restore)
        if state == ATSTATE:
            print 'AMT configuration succeeded'
            addLogRecord(0,__file__, INFO,'AMT configuration succeeded')
            break
        if state == FAILURE:
            break
        os.system('prepareDeployment refresh')
    else:
        print 'AMT configuration failed after 3 retries'
        addLogRecord(0,__file__, ERROR,'AMT configuration failed after 3 retries')
        state = FAILURE
    sys.exit(state)
