#!/opt/vertica/oss/python/bin/python
import os, pwd, argparse
import sys,json
from vertica.network import adapterpool
from vertica.network import SSH
from vertica.utils import api
from vertica.config.Configurator import Configurator
from vertica.config import DBinclude

class ArgumentException(Exception):
    def __init__(self, value):
        self.value = value
    def __str__(self):
        return "The required argument %s is missing." % self.value


#################################################################
def sync():
    ''' sync the set of keys across the known cluster using ssh '''
    print "Synchronizing cluster..."
    all_cluster_hosts = Configurator.Instance().gethosts()

    session = adapterpool.AdapterConnectionPool_3.Instance()
    session.connect2(all_cluster_hosts, pwd.getpwuid(os.getuid())[0] , None)

    SSH.scpToPool(session, DBinclude.DB_DIR + "/config/apikeys.dat")



def do_list():
    ''' list the keys in the apikeys.dat file and try to format them in a nice way '''
    keys = api.list_keys()
    widths = [max(len(x) for x in col) for col in zip(*keys)]
    print 'Listing %d keys' % len(keys)
    for k in keys:
        print '{}'.format(k['requestor'], widths[0] ), '{}'.format(k['app'], widths[1]), '{}'.format(k['apikey'], widths[2]), '{}'.format(k['level'], widths[3])

def do_migrate():
    print 'Migrating keys...'
    api.migrate()


def do_delete( args ):
    ''' delete the key(s) matching the user/app and save them back out'''
    if not args.requestor: 
        raise ArgumentException( "--user" )

    if not args.application: 
        raise ArgumentException( "--app" )

    existing_keys = api.list_keys()
    new_set = []
    deletions = 0
    for k in existing_keys:
        if k['requestor'] == args.requestor and k['app'] == args.application:
            deletions += 1
        else:
            new_set.append( k )

    if deletions > 0:
       api.savekeys( new_set )
       sync()

    print deletions, "key(s) deleted."


def do_secure( args ):
    if not args.requestor: 
        raise ArgumentException( "--user" )

    if not args.application: 
        raise ArgumentException( "--app" )

    existing_keys = api.list_keys()
    updates = 0
    for k in existing_keys:
        if k['requestor'] == args.requestor and k['app'] == args.application:
            updates += 1
            k['level'] = args.secure

    if updates > 0:
        api.savekeys(existing_keys)
        sync()

    print updates, "key(s) updated."



def do_create( args ):
    ''' create a new set of keys for the user/app '''
    if not args.requestor: 
        raise ArgumentException( "--user" )

    if not args.application: 
        raise ArgumentException( "--app" )

    existing_keys = api.list_keys()
    for k in existing_keys:
        if k['requestor'] == args.requestor and k['app'] == args.application:
            print "Key already exists for this request: " , k['apikey']
            return

    keyset =  api.api_key_gen( args.application, args.requestor )
    print "Requestor  :", keyset['requestor']
    print "Application:", keyset['app']
    print "API Key    :", keyset['apikey']
    sync()


if __name__ == "__main__":

    userName = pwd.getpwuid(os.getuid())[0]
    if (userName == "root"):
       print "\nRoot user is not allowed to use this tool."
       print "Try again as the DB administrative user."
       sys.exit(1)

    parser = argparse.ArgumentParser(description="API key management tool")
    parser.add_argument( '--user', dest='requestor', action='store', help='The name of the person requesting the key' )
    parser.add_argument( '--app', dest='application', action='store', help='The name of the application that will use the key' )
    parser.add_argument( '--delete', dest='is_delete', default=False, action='store_true', help='Delete the key for the given R & A' )
    parser.add_argument( '--create', dest='is_create', default=False, action='store_true', help='Create a key for the given R & A' )
    parser.add_argument( '--update', dest='is_update', default=False, action='store_true', help='Update a key for the given R & A' )
    parser.add_argument( '--migrate', dest='migrate', default=False, action='store_true', help='migrate the keyset to the latest format' )
    parser.add_argument( '--secure', dest='secure', default='restricted', action='store', help='Set the keys security level', choices=['restricted','normal','admin'] )
    parser.add_argument( '--list', dest='is_list', default=False, action='store_true', help='List all the keys known' )

    args = parser.parse_args()

    try:
        if args.is_list: 
            do_list()
        elif args.migrate:
            do_migrate()
        elif args.is_delete:
            do_delete(args)
        elif args.is_update:
            do_secure(args)
        else:
            do_create(args)
    except ArgumentException, a:
        print a

    sys.exit(0)

