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

import os, sys

class SwixCommand:
   def __init__( self, name, help, module=None ):
      self.name_ = name
      self.help_ = help or "(undocumented)"
      self.module_ = module or ( "Swix." + name )

   def name( self ): return self.name_
   def help( self ): return self.help_

   def _module( self ):
      return __import__( self.module_, globals(), locals(), [None] )

   def run( self, args ):
      f = getattr( self._module(), self.name_ + "Handler" )
      f( args=args )

   def printHelp( self ):
      getattr( self._module(), self.name_ + "Help" )()

swixcommands = {c.name(): c for c in (
   SwixCommand( "create",
                help="Create a swix file with the given name" ),
   SwixCommand( "info",
                help="Display manifest for the given swix file" ),
   SwixCommand( "sign",
                help="Sign the swix file with a cryptographic signature" ),
   SwixCommand( "verify",
                help="Check if the swix file is signed by a trusted CA" ),
   )}

if __name__ == "__main__":
   if not sys.argv[1:]:
      sys.stderr.write( "Unknown command.  Try 'swix help' for info.\n" )
      sys.exit( 1 )

   # Figure out where swix lives so the right modules are loaded when the user
   # invokes swix with '/usr/bin/swix' or 'python mytree/src/EosUtils/swix.in'
   swix = os.path.abspath( sys.argv[0] )
   swixdir = os.path.dirname( swix )
   if swixdir.endswith( "/usr/bin" ):
      libdir = os.environ.get( "PYTHONPATH", "" ).split( ":" )[0]
      if libdir:
         sys.path.insert( 0, os.path.join( swixdir, "..", "..", libdir ) )
   else:
      sys.path.insert( 0, swixdir )
      swixsrcdir = swixdir.replace( "/bld/", "/src/" )
      sys.path.insert( 0, swixsrcdir )

   cmd, args = sys.argv[1], sys.argv[2:]

   if cmd == "--version":
      sys.stdout.write( "swix version 1.1.19\n" )
   elif cmd == "help" and args and args[0] in swixcommands:
      swixcommands[ args[0] ].printHelp()
   elif cmd in swixcommands:
      swixcommands[ cmd ].run( args )
   elif cmd == "help" and ( not args or args[0] == "commands" ):
      for c in sorted( swixcommands ):
         sys.stdout.write( "\t%-11s %s\n" % (c, swixcommands[c].help()) )
      sys.stdout.flush()
   else:
      sys.stderr.write( "use 'swix help' for help\n" )
      sys.exit( 1 )
