#!/usr/bin/env python
# Copyright (c) 2012 Arista Networks, Inc.  All rights reserved.
# Arista Networks, Inc. Confidential and Proprietary.
#
# fabric networking driver utility

from sys import argv
from fcntl import ioctl
import ctypes, errno
import cpufabric
import os.path
from linux_ioc import _IOWR

bufsize = 4096

def usage():
   print 'usage: fab name [ values .. ]'
   exit( -1 )

if ( len( argv ) < 2 ) or ( argv[1] == '-h' ) or ( argv[1] == '--help' ):
   usage()

if argv[1] == 'dump':
   for path in ( '/proc/sand-dma', '/proc/strata-dma',
      '/proc/fpdma', '/proc/xpdma', '/proc/bfdma' ):
      try:
         print open( path ).read()
         exit( 0 )
      except IOError:
         pass
   exit( -1 ) 

# incrementally convert drivers to standard linux ioctl cmd encoding
stdioc = os.path.exists( '/proc/xpdma' )
cmd = _IOWR(0, 0, bufsize) if stdioc else bufsize

with open( '/dev/fabric' ) as f:
   buf = ctypes.create_string_buffer( ' '.join( argv[1:] ), bufsize )
   try:
      rc = ioctl( f.fileno(), cmd, buf )
   except IOError as ( e, strerror ):
      if e == errno.ENOENT:
         strerror = "not supported"
      print argv[1], ':', strerror
      exit( -1 )

   if rc:
      if argv[1] == 'devstats':
         stats = ctypes.cast(buf, ctypes.POINTER(cpufabric.FabDevStats)).contents
         stats.__print__()
      else:
         print buf.value
