#!/usr/bin/env python
# Copyright (c) 2006-2012 Arista Networks, Inc.  All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.

import Tac, FdlIo
import optparse
import sys

def parseOptions():
   parser = optparse.OptionParser( usage="""
   %prog [options] <fdl>
      Write <fdl> file to the appropriate fdl storage.

   or:
   %prog [options]
      Write the fdl from stdin to the appropriate fdl storage.
      """ )

   parser.add_option( "", "--dataFormat", action="store", type="int",
                      default=2, help="Data format to store the fdl in"
                      " (1 - uncompressed, 2 - bzip2 compressed)" )

   parser.add_option( "", "--prefdl", action="store", default="",
                      help="Store the given raw prefdl in the seeprom as the "
                      "fdl's header." )

   parser.add_option( "", "--raw", action="store_true",
                      help="Write the data from stdin directly to the seeprom "
                           "(prefdl has already been added)." )

   parser.add_option( "--sysname", dest="sysname", action="store",
                      type="string", default="ar",
                      help="System name (default=%default)." )
   return parser.parse_args()

def parseSmbusAddress( address ):
   import re
   m = re.match( '/([\dxXa-fA-F]+)/([\d]+)/([\dxXa-fA-F]+)$', address )
   if not m:
      print "Could not parse address", address
      sys.exit( 1 )
   accelOffsetStr = m.group( 1 )
   if accelOffsetStr.startswith( "0x" ) or accelOffsetStr.startswith( "0X" ):
      accelOffset = int( accelOffsetStr, 16 )
   else:
      accelOffset = int( accelOffsetStr )
   busId = int( m.group( 2 ) )
   deviceIdStr = m.group( 3 )
   if deviceIdStr.startswith( "0x" ) or deviceIdStr.startswith( "0X" ):
      deviceId = int( deviceIdStr, 16 )
   else:
      deviceId = int( deviceIdStr )
   return ( accelOffset, busId, deviceId )

def main():
   ( opts, args ) = parseOptions()

   if len( args ) > 1:
      print "Incorrect number of arguments."
      return 1
   elif len( args ) == 1:
      data = file( args[ 0 ] ).read()
   else:
      data = sys.stdin.read()

   FdlIo.writeFdl( data, raw=opts.raw, dataFormat=opts.dataFormat,
                   prefdl=opts.prefdl, sysname=opts.sysname )

   return 0

if __name__ == "__main__":
   sys.exit( main() )
