#!/usr/bin/python
"""
A Python shell to interact with the Linode API

Copyright (c) 2008 Timothy J Fontaine <tjfontaine@gmail.com>

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""

import api
import code
import rlcompleter
import readline
import atexit
import os

class LinodeConsole(code.InteractiveConsole):
  def __init__(self, locals=None, filename="<console>",
      histfile=os.path.expanduser("~/.linode-console-history")):
    code.InteractiveConsole.__init__(self)
    self.init_history(histfile)
    
  def init_history(self, histfile):
    if hasattr(readline, "read_history_file"):
      try:
        readline.read_history_file(histfile)
      except IOError:
        pass
        atexit.register(self.save_history, histfile)

  def save_history(self, histfile):
    readline.write_history_file(histfile)

class LinodeComplete(rlcompleter.Completer):
  def complete(self, text, state):
    result = rlcompleter.Completer.complete(self, text, state)
    if result and result.find('_') > -1:
      result = ''
    return result


if __name__ == "__main__":
  from getpass import getpass
  from os import environ

  if environ.has_key('LINODE_API_KEY'):
    key = environ['LINODE_API_KEY']
  else:
    key = getpass('Enter API Key: ')
  linode = api.Api(key)
  console = LinodeConsole()

  console.runcode('import readline,rlcompleter,api,shell,simplejson')
  console.runcode('readline.parse_and_bind("tab: complete")')
  console.runcode('readline.set_completer(shell.LinodeComplete().complete)')
  console.runcode('def pp(text=None): print simplejson.dumps(text, indent=2)')
  console.locals.update({'linode':linode})
  console.interact()

@@ -1965,16 +1965,17 @@
 .find('_
+_
 ') %3E -1:
@@ -2094,16 +2094,57 @@
  environ
+%0A  import getopt, sys%0A  import simplejson
 %0A%0A  if e
@@ -2282,16 +2282,1193 @@
 pi(key)%0A
+%0A  def usage():%0A    print 'shell.py --%3Capi action%3E %5B--parameter1=value %5B--parameter2=value %5B...%5D%5D%5D'%0A    print 'Valid Actions'%0A    for a in sorted(linode.valid_commands().keys()):%0A      print '%5Ct--'+a%0A    print 'Valid Named Parameters'%0A    for a in sorted(linode.valid_params().keys()):%0A      print '%5Ct--'+a+'='%0A%0A  options = %5B%5D%0A  for arg in linode.valid_params().keys():%0A    options.append(arg+'=')%0A%0A  for arg in linode.valid_commands().keys():%0A    options.append(arg)%0A  options.append('help')%0A%0A  if len(sys.argv%5B1:%5D) %3E 0:%0A    try:%0A      optlist, args = getopt.getopt(sys.argv%5B1:%5D, '', options)%0A    except getopt.GetoptError, err:%0A      print str(err)%0A      usage()%0A      sys.exit(2)%0A%0A    command = optlist%5B0%5D%5B0%5D.replace('--', '')%0A%0A    if hasattr(linode, command):%0A      func = getattr(linode, command)%0A      params = %7B%7D%0A      for param,value in optlist%5B1:%5D:%0A        if param.replace('--', '') == 'help':%0A          usage()%0A          sys.exit(2)%0A%0A        params%5Bparam.replace('--', '')%5D = value%0A      print simplejson.dumps(func(params), indent=2)%0A    else:%0A      if not command == 'help':%0A        print 'Invalid action '+optlist%5B0%5D%5B0%5D%0A%0A      usage()%0A      sys.exit(2)%0A  else:%0A  
   consol
@@ -3488,16 +3488,18 @@
 sole()%0A%0A
+  
   consol
@@ -3558,24 +3558,26 @@
 plejson')%0A  
+ 
+ 
 console.runc
@@ -3620,24 +3620,26 @@
 omplete%22)')%0A
+  
   console.ru
@@ -3699,24 +3699,26 @@
 complete)')%0A
+  
   console.ru
@@ -3784,16 +3784,18 @@
 nt=2)')%0A
+  
   consol
@@ -3829,16 +3829,18 @@
 inode%7D)%0A
+  
   consol

add command line driver, actions are case sensitive and match api methods, parameters are all lower case