#!/usr/bin/python
#
# Copyright 2012 Major Hayden
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
import ConfigParser
import os
import subprocess
import sys


# Helps us find non-python files installed by setuptools
def data_file(fname):
    """Return the path to a data file of ours."""
    return os.path.join(os.path.split(__file__)[0], fname)

# Pick up the user's credentials and environments
user_creds = ConfigParser.RawConfigParser()
user_creds.read(os.path.expanduser("~/.supernova"))


def bin_helper():
    # Parse any options the user might have passed
    args = sys.argv
    args.pop(0)  # get rid of the PROG arg
    try:
        nova_env = args.pop(0)  # environment argument for supernova
    except:
        print "You must specify a valid nova environment as " \
            "the first argument."
        print "Available environments: %r" % user_creds.sections()
        sys.exit()

    # Our remaining arguments should be the stuff we pass through to
    # novaclient
    if len(args) < 1:
        print "You didn't provide any arguments to pass through " \
            "to novaclient."
        sys.exit()
    else:
        nova_args = args

    # Does the user have a configuration block for this environment?
    if nova_env not in user_creds.sections():
        print "You asked for the %r environment but it doesn't " \
            "have a configuration section starting with [%s] in %s." % (
            nova_env, nova_env, os.path.expanduser("~/.supernova"))
        sys.exit()

    # Do we have any login credentials for the environment specified?
    try:
        dict(user_creds.items(nova_env))['nova_url']
    except KeyError:
        print """
You may be missing authentication credentials for the %r environment in your
%s file.  Newer versions of supernova require all of your novaclient
environment variables to be present in %s.
""" % (nova_env, os.path.expanduser("~/.supernova"),
            os.path.expanduser("~/.supernova"))

    # Get our environment variables ready
    # novaclient compatibility note - if your values are surrounded by ""
    # or '', those characters will be stripped automatically below
    env = os.environ
    for key, value in user_creds.items(nova_env):
        if key == "insecure":
            continue
        env[key.upper()] = value.strip("\"'")

    # Do we need to call nova with --insecure for this environment?
    if user_creds.has_option(nova_env, 'insecure'):
        nova_args = ['--insecure'] + nova_args

    # Call novaclient
    p = subprocess.Popen(['nova'] + nova_args,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        env=env
    )

    # Print novaclient's output
    for line in p.stdout:
        print line.rstrip("\n")

@@ -969,16 +969,17 @@
 ds.read(
+%5B
 os.path.
@@ -1004,16 +1004,31 @@
 ernova%22)
+, '.supernova'%5D
 )%0A%0A%0Adef 
@@ -1155,16 +1155,36 @@
 ROG arg%0A
+    while True:%0A    
     try:
@@ -1176,32 +1176,36 @@
 e:%0A        try:%0A
+    
         nova_env
@@ -1257,16 +1257,20 @@
 pernova%0A
+    
     exce
@@ -1271,26 +1271,40 @@
   except
-:%0A
+ IndexError:%0A   
         
 print %22Y
@@ -1287,32 +1287,33 @@
 ror:%0A           
+ 
 print %22You must 
@@ -1364,16 +1364,20 @@
         
+    
 %22the fir
@@ -1394,24 +1394,28 @@
 t.%22%0A        
+ 
+   
 print %22Avail
@@ -1439,25 +1439,24 @@
 : %25r%22 %25 
-user_cred
+nova_env
 s.sectio
@@ -1460,32 +1460,36 @@
 tions()%0A        
+    
 sys.exit()%0A%0A    
@@ -1487,233 +1487,235 @@
 t()%0A
-%0A
     
-# Our remaining arguments should be the stuff we pass through to%0A    # novaclient%0A    if len(args) %3C 1:%0A        print %22You didn't provide any arguments to pass through %22 %5C%0A            %22to novaclient.%22%0A        sys.exit()%0A
+    # make the sneakies on %22supernova debug nova_env list%22%0A        if nova_env == 'debug':%0A            # note this doesn't %22export%22 the var, it only effects this process%0A            os.environ%5B'NOVACLIENT_DEBUG'%5D = '1'%0A    
     
@@ -1732,24 +1732,17 @@
     
-nova_args = args
+    break
 %0A%0A  
@@ -2092,153 +2092,412 @@
   # 
-Do we have any login credentials for the environment specified?%0A    try:%0A        dict(user_creds.items(nova_env))%5B'nova_url'%5D%0A    except KeyError
+Our remaining arguments should be the stuff we pass through to%0A    # novaclient%0A    if len(args) %3C 1:%0A        print %22You didn't provide any arguments to pass through %22 %5C%0A            %22to novaclient.%22%0A        sys.exit()%0A    else:%0A        nova_args = args%0A%0A    # Do we have any login credentials for the environment specified?%0A    if not any(k for (k, v) in user_creds.items(nova_env) if k.endswith('_url'))
 :%0A  

Support curdir conf, OS_* env, and "debug novaenv"