#!/usr/bin/env python3
# Copyright (c) 2006 Arastra, Inc.  All rights reserved.
# Arastra, Inc. Confidential and Proprietary.

import seeprom
import optparse, sys # pylint: disable=deprecated-module

usage = """
idprom [options] read

  Read idprom contents and write to stdout, in binary

idprom [options] write

  Take idprom contents from stdin (in binary) and write to the idprom.

  All numeric arguments can be specified in decimal, hex (prefixed by
  '0x'), or binary (prefixed by '0b')."""

parser = optparse.OptionParser(usage=usage)
parser.add_option( "-u", "--unlock", action="store_true",
                   help="unlock the id seeprom" )
parser.add_option( "", "--busId", action="store", default = 1,
                   help="Specify the bus id the seeprom is on")
parser.add_option( "", "--seepromId", action="store", default=0x52,
                   help="Specify the seeprom address")
parser.add_option( "", "--offset", action="store", default=0,
                   help="Specify the read offset")

( options, args ) = parser.parse_args()
if len( args ) < 1:
   parser.error( "Too few arguments" )

busId = options.busId
seepromId = options.seepromId
offset = options.offset

op = args[0]
l = len( args )

try:
   if options.unlock and op == "write":
      seeprom.unlock()

   if op == "read":
      # pylint: disable-next=multiple-statements
      if l != 1: parser.error( "Too many arguments" )
      result = seeprom.doRead( busId, seepromId, offset, 256-offset )
      sys.stdout.write( result )
   elif op == "write":
      data = sys.stdin.read( 256 )
      if offset + len( data ) > 256:
         parser.error( "offset + data length exceeds 256" )
      seeprom.doWrite( busId, seepromId, offset, data, options.unlock )
      if options.unlock:
         seeprom.restoreLock()
   else:
      parser.error( "Unknown operation: '" + op + "'" )
except MemoryError as e:
   print( e, file=sys.stderr )
finally:
   if options.unlock:
      seeprom.restoreLock()

