#!/usr/bin/env python
import re
import os
import sys

def main():
    print 'Verifying firmware update tool/package compatibility:'

    # Look up the tool version on the system. If there's
    # no isi.hw.fw module, or if no isi.hw.fw.TOOL_VERSION
    # variable exists, or if it's not an integer, we treat
    # the version as 0.
    msg = ''
    try:
        import isi.hw.fw as fw
        sysVer = int(fw.TOOL_VERSION)
    except Exception:
        sysVer = 0
        msg = ' (none found)'
    print '- Tool version    : %d%s' % (sysVer, msg)

    # Try to open the firmware.xml file in the package
    # Script arguments as given to us by the package system are:
    #  1 = temp dir containing untarred package
    #  2 = package name
    tmpDir = sys.argv[1]
    try:
        f = open(os.path.join(tmpDir, 'config/firmware.xml'))
    except Exception, e:
        print ('Error: Unable to open firmware.xml for version '
               'check: %s' % e)
        sys.exit(1)

    # Now check if the system version is listed in our
    # firmware.xml file. Note that we aren't actually
    # parsing the XML here, but just lazily grepping
    # through the lines looking for a match. Since
    # we generate all the firmware.xml files (and can
    # thus guarantee that the <tool-version> lines will
    # be well-formed), this should be sufficient, and
    # is a heck of a lot simpler and more portable.
    toolReg = re.compile('^\s*<tool-version>\s*(?P<ver>\d+)\s*'
                         '</tool-version>')
    okay = False
    for line in f.readlines():
        match = toolReg.match(line)
        if match:
            pkgVer = int(match.group('ver'))
            print '- Package version : %d' % pkgVer
            if pkgVer == sysVer:
                okay = True
                break

    if not okay:
        print """\
Error: The current firmware update tool is not compatible with this package"""

    return okay

if __name__ == '__main__':
    okay = main()
    result = not okay and 2 or 0
    sys.exit(result)
