#!/usr/bin/env python
import sys
import argparse
import os
sys.path.append('../')
sys.path.append('./')
from repoman_client import repoman_client
from repoman_client import make_config
import os.path

def ask_yes_or_no(*args, **kwargs):
    try:
        force = kwargs['force']
    except:
        force = False
    print " Are you sure you want to continue?"
    if force:
        print " To prevent this message from displaying, run the command with" 
        print " --force or -f."
    k=raw_input("[y/N]")
    if k in ('y', 'ye', 'yes'):
        return True
    return False

def print_help_menu(long):
    if long:
        print "Repoman-Client 0.2.3"
        print 'usage: repoman [subcommand]'
        print " "
        print "Manages VMs, users and groups on a Repoman repository."
        print " "
        print "Possible subcommands:"
        print "Run \"repoman [subcommand] --help|-h\" for a complete list of options."
        print "To see the current version of repoman-client, use \"--version\""
        print ""
        print "Basic commands:"
        print ""
        print "  make-config -- create the initial configuration file (required)"
        print "  get -- download an image"
        print "  save -- snapshot current system and upload it to the server"
        print "  delete -- delete an image"
        print "  rename -- rename an image"
        print "  list -- list your available images"
        print ""
        print "Advanced commands:"
        print ""
        print "  make-config | mc               creates a config file (must be done first)"
        print "  list-users | li                list users"
        print "  list-groups | lg               list groups"
        print "  list-images | li               list images"
        print "  create-user | cu               create a user"
        print "  create-group | cg              create a group"
        print "  create-image | ci              create an image"
        print "  modify-user | mu               modify user metadata"
        print "  modify-group | mg              modify group metadata"
        print "  modify-image | mi              modify image metadata"
        print "  remove-user | ru               remove a user"
        print "  remove-group | rg              remove a group"
        print "  remove-image | ri              remove an image"
        print "  describe-user | du             describe a user"
        print "  describe-group | dg            describe a group"
        print "  describe-image | di            describe an image"
        print "  download-image | get           download an image"
        print "  upload-image | ui              upload an image"
        print "  share-image | si               share an image with a user or group"
        print "  unshare-image | usi            unshare an image with a user or group"
        print "  add-users-to-group | aug       add users to a group"
        print "  remove-users-from-group | rug  remove users from a group"
        print "  add-permissions | ap           add permissions to a group"
        print "  remove-permissions | rp        add permissions to a group"
        print "  snapshot-system | ss           snapshot current system and store locally or upload."
        print "  upload-snapshot | us           upload a snapshot to the server."
        print "  whoami                         returns current username or user information"
        print "  about | a                      returns information about repoman-client"
        sys.exit(0)
    else:
        print "Repoman-Client 0.2.4"
        print "usage: repoman [subcommand]"
        print ""
        print "The most commonly used commands are:"
        print ""
        print "  make-config -- create the initial configuration file (required)"
        print "  get -- download an image"
        print "  save -- snapshot current system and upload it to the server"
        print "  delete -- delete an image"
        print "  rename -- rename an image"
        print "  list -- list your available images"
        print ""
        print "For a full list of repoman commands use \"--help --all\""
        print "To see the current version of repoman-client, use \"--version\""
        sys.exit(0)
def main():
    if not len(sys.argv) > 1:
        print_help_menu(False)
        sys.exit(0)
    else:
        command = sys.argv[1]
        
    if command == 'make-config' or command == 'mc':
        parser = argparse.ArgumentParser(prog='repoman make-config', description='Removes permissions from a group on the repository.')
        parser.add_argument('--repo', help='full address of your repository (https://REPO:PORT)', required=True)
        parser.add_argument('--snapshot_location', help='location to store the image snapshot (default is /tmp/fscopy.img)', default='/tmp/fscopy.img')
        parser.add_argument('--mount_location', help='location to mount the image snapshot (default is /mnt/fscopy)', default='/mnt/fscopy/')
        parser.add_argument('--usercert', help='allows the user to specify a custom usercert (rather than a grid proxy)')
        parser.add_argument('--userkey', help='allows the user to specify a custom userkey (rather than a grid proxy)')
        args = parser.parse_args(args=sys.argv[2:])
        user_config = os.getenv("HOME")+'/.repoman-client'
        if os.path.isfile(user_config):
            print "WARNING! You already have a configuration file at ~/.repoman-client."
            print "Do you wish to overwrite?"
            k=raw_input("[y/N]")
            if k in ('y', 'ye', 'yes'):
                file = open(user_config, 'w')
            else:
                print "Exiting repoman-client."
                sys.exit(0)  
        else:
            file = open(user_config, 'w')
        if not args.usercert and not args.userkey:
            file.write(make_config.make_config(args.repo, args.snapshot_location, args.mount_location, False))
            file.close()
            print "Config file successfully written."
            sys.exit(0)
        elif (args.usercert and not args.userkey) or (args.userkey and not args.usercert):
            print "Custom usercert and userkey must both be defined or neither.  If neither are defined Repoman-client will look in the default grid proxy location (/tmp/x509up_uUSER_ID) and in the environment variable REPOMAN_CLIENT_CONFIG."
            sys.exit(1)
        else:
            file.write(make_config.make_config(args.repo, args.snapshot_location, args.mount_location, True, usercert=args.usercert, userkey=args.userkey))
            file.close()
            print "Config file successfully written."
            sys.exit(0)
        sys.exit(0)
        
    else:  
        repo = repoman_client.repoman_client()

    if command == 'list-images' or command == 'li' or command == 'list':
        parser = argparse.ArgumentParser(prog='repoman list|list-images|li', description='Lists images on the Repoman repository.', usage='%(prog)s [--long | -l] [--all | -a] [--sharedwith] [--sharedwith [[--user | -u] USER] | [[--group | -g] GROUP]]] [[--user | -u] USER] [[--group | -g] GROUP]')
        parser.add_argument('--long','-l', action='store_true', default=False, help='display full URLs')
        parser.add_argument('--sharedwith', action='store_true', default=False, help='list all images shared with current user')
        parser.add_argument('--all','-a', action='store_true', default=False, help='list all images')
        parser.add_argument('--user','-u', action='store', help='list user\'s images')
        parser.add_argument('--group','-g', action='store', help='list group\'s images')
        args = parser.parse_args(args=sys.argv[2:])
        if args.all:
            repo.list_all_images()
        elif args.sharedwith:
            if args.user:
                repo.list_images_sharedwith_user(args.user, args.long)
            elif args.group:
                repo.list_images_sharedwith_group(args.group, args.long)
            else:
                repo.list_images_sharedwith(args.long)
        elif args.user:
            if args.long:
                repo.list_user_images(args.user, args.long)
            else:
                repo.list_user_images(args.user, args.long)
        else:
            if args.long:
                repo.list_images(args.long)
            else:
                repo.list_images(args.long)
        
        sys.exit(0)

    elif command == 'list-users' or command == 'lu':
        parser = argparse.ArgumentParser(prog='repoman list-users', description='Lists users on the Repoman repository.', usage='%(prog)s [--long | -l] [[--group | -g] GROUP]')
        parser.add_argument('--long','-l', action='store_true', default=False, help='display full user information')
        parser.add_argument('--group','-g', action='store', help='display users in group')
        args = parser.parse_args(args=sys.argv[2:])
        if args.group:
            repo.list_group_members(args.group, args.long)
        else:
            repo.list_users(args.long)
        sys.exit(0)
        
    elif command == 'list-groups' or command == 'lg':
        parser = argparse.ArgumentParser(prog='repoman list-groups', description='Lists groups on the Repoman repository.', usage='%(prog)s [--long | -l] [--all | -a] [[--user | -u] USER]')
        parser.add_argument('--long','-l', action='store_true', default=False, help='display full group information')
        parser.add_argument('--all','-a', action='store_true', default=False, help='display all groups')
        parser.add_argument('--user','-u', help='display groups that user is a member of')
        args = parser.parse_args(args=sys.argv[2:])
        if args.user:
            repo.list_users_groups(args.user, args.long)
        elif args.all:
            repo.list_groups(args.long)
        else:
            repo.list_users_groups(repo.return_username(), args.long)
        sys.exit(0)

    elif command == 'whoami':
        parser = argparse.ArgumentParser(prog='repoman whoami', description='List current username and user information.', usage='%(prog)s [--long | -l])')
        parser.add_argument('--long','-l', default=False, action="store_true", help='displays current user information')
        args = parser.parse_args(args=sys.argv[2:])
        if args.long:
            repo.get_user()
        else:
            repo.get_username()
        sys.exit(0)
          
    elif command == 'create-user' or command == 'cu':
        parser = argparse.ArgumentParser()
        args = parser.parse_known_args(args=sys.argv[2:])
        metadata = dict([(args[1][i].strip('-'), args[1][i+1]) for i in range(0, len(args[1]) - 1, 2)])
        if not set (['user_name','email','cert_dn','full_name']) <= set(metadata):
            print 'usage: repoman create-user --user_name USERNAME --email USER_EMAIL --cert_dn USER_CERT_DN --full_name "FULL NAME"'
            print " "
            print "Creates users on the Repoman repository."
            print " "
            print "required arguments:"
            print "  --user_name           new user's username"
            print "  --email               new user's email address"
            print "  --cert_dn             new user's distinguished name"
            print "  --full_name           new user's full name in quotes"
            print ""
            print "optional arguments:"
            print "   -h, --help           show this help message and exit"
            sys.exit(0)
        print "Creating user with metadata:"
        for item in metadata:
            print item+": "+metadata[item]
        repo.create_user(metadata)
        sys.exit(0)
        
    elif command == 'create-group' or command == 'cg':
        parser = argparse.ArgumentParser()
        args = parser.parse_known_args(args=sys.argv[2:])
        metadata = dict([(args[1][i].strip('-'), args[1][i+1]) for i in range(0, len(args[1]) - 1, 2)])
        print str(metadata)
        if not set (['name']) <= set(metadata):
            print 'usage: repoman create-group --name GROUP_NAME'
            print " "
            print "Creates groups on the Repoman repository."
            print " "
            print "required arguments:"
            print "   --name               name of group to be created"
            print ""
            print "optional arguments:"
            print "   -h, --help           show this help message and exit"
            sys.exit(0)
        print "Creating group with metadata:"
        for item in metadata:
            print item+": "+metadata[item]
        repo.create_group(metadata)
        sys.exit(0)
        
    elif command == 'remove-user' or command == 'ru':
        parser = argparse.ArgumentParser(prog='repoman remove-user', description='Removes a user from the Repoman repository.', usage='%(prog)s user [--force | -f]')
        parser.add_argument('user', help='user to remove')
        parser.add_argument('--force','-f', action='store_true', default=False, help='overrides the confirmation message')
        args = parser.parse_args(args=sys.argv[2:])
        if args.force:
            repo.remove_user(args.user)
        else:
            print 'Removing user '+args.user+'...'
            if ask_yes_or_no(force=True):
                repo.remove_user(args.user)
            else:
                print 'Exiting repoman-client.'
        sys.exit(0)
            
    elif command == 'remove-group' or command == 'rg':
        parser = argparse.ArgumentParser(prog='repoman remove-group', description='Removes a group from the Repoman repository.', usage='%(prog)s group [--force | -f]')
        parser.add_argument('group')
        parser.add_argument('--force','-f', action='store_true', default=False)
        args = parser.parse_args(args=sys.argv[2:])
        if args.force:
            repo.remove_group(args.group)
        else:
            print 'Removing group '+args.group+'...'
            if ask_yes_or_no(force=True):
                repo.remove_group(args.group)
            else:
                print 'Exiting repoman-client.'
        sys.exit(0)
        
    elif command == 'remove-image' or command == 'ri' or command == 'delete':
        parser = argparse.ArgumentParser(prog='repoman delete|remove-image|ri', description='Removes an from the Repoman repository.', usage='%(prog)s [user/]image [--force | -f]')
        parser.add_argument('image')
        parser.add_argument('--force','-f', action='store_true', default=False)
        args = parser.parse_args(args=sys.argv[2:])
        if args.force:
            repo.remove_image(args.image)
        else:
            print 'Removing image '+args.image+'...'
            if ask_yes_or_no(force=True):
                repo.remove_image(args.image)
            else:
                print 'Exiting repoman-client.'
        sys.exit(0)
        
    elif command == 'modify-image' or command == 'mi':
        parser = argparse.ArgumentParser(prog='repoman modify-image', description='Updates the metadata for an image in the Repoman repository.', usage='%(prog)s [user/]image [--META_KEY META_VALUE]')
        parser.add_argument('image', help='image to modify')
        args = parser.parse_known_args(args=sys.argv[2:])
        image = args[0].image
        metadata = dict([(args[1][i].strip('-'), args[1][i+1]) for i in range(0, len(args[1]) - 1, 2)])
        metadata['name'] = image
        #Server is expecting Bool objects for readonly
        try:
            read_only = metadata['read_only']
            true_values = ['t', 'True', 'true']
            if true_values.count(metadata['read_only']):
                metadata['read_only'] = True
            else:
                metadata['read_only'] = False
        except:
            pass
        images = repo.list_images_raw()
        exists = False
        for image in images:
            if metadata['name'] == image.split('/')[6]:
                exists = True
        if not exists:
            print "This image does not exist."
            sys.exit(1)
        print "Updating image "+metadata['name']+" with metadata: "
        for key in metadata:
             print key+": "+str(metadata[key])
        repo.update_metadata(metadata=metadata, exists=True)
        sys.exit(0)

    elif command == 'rename':
        parser = argparse.ArgumentParser(prog='repoman rename', description='Rename an image in the Repoman repository.', usage='%(prog)s image_name new_image_name')
        parser.add_argument('image_name', help='image to rename')
        parser.add_argument('new_image_name', help='new image name')
        args = parser.parse_args(args=sys.argv[2:])

        images = repo.list_images_raw()
        exists = False
        for image in images:
            if args.image_name == image.split('/')[6]:
                exists = True
        if not exists:
            print "This image does not exist in the repository."
            sys.exit(1)
        print "Renaming image "+args.image_name+" to "+args.new_image_name
        repo.rename_image(args.image_name, args.new_image_name)
        sys.exit(0)
        
    elif command == 'download-image' or command == 'get':
        parser = argparse.ArgumentParser(prog='repoman get|download-image', description='Downloads an image from the Repoman repository.', usage='%(prog)s [user/]image [[--dest | -d] DESTINATION]')
        parser.add_argument('image', help='image to download')
        parser.add_argument('--dest','-d', default='./', help='destination to save file to. defaults to current directory.')
        args = parser.parse_args(args=sys.argv[2:])
        images = repo.list_images_raw()
        exists = False
        for image in images:
            if args.image == image.split('/')[6]:
                exists = True
        if not exists:
            print "This image does not exist."
            sys.exit(1)
        if not os.path.split(args.dest)[1]:
            if '/' in args.image:
                args.dest = args.dest+args.image.split('/')[1]
            else:
                args.dest = args.dest+args.image
                args.image = repo.return_username()+'/'+args.image
        repo.get(args.image,args.dest)
        sys.exit(0)

    elif command == 'describe-image' or command == 'di':
        parser = argparse.ArgumentParser(prog='repoman describe-image', description='Prints detailed information about an image.', usage='%(prog)s [user/]image')
        parser.add_argument('image', help='image to describe')
        args = parser.parse_args(args=sys.argv[2:])
        if '/' in args.image:
            user = args.image.split('/')[0]
            image = args.image.split('/')[1]
            repo.describe_image(image, user=user)
        else:
            image = args.image
            repo.describe_image(args.image)
            sys.exit(0)
            
    elif command == 'describe-user' or command == 'du':
        parser = argparse.ArgumentParser(prog='repoman describe-user', description='Prints detailed information about a user.', usage='%(prog)s user')
        parser.add_argument('user', help='user to describe')
        args = parser.parse_args(args=sys.argv[2:])
        repo.describe_user(args.user)
        sys.exit(0)
        
    elif command == 'describe-group' or command == 'dg':
        parser = argparse.ArgumentParser(prog='repoman describe-group', description='Prints detailed information about a group.', usage='%(prog)s group')
        parser.add_argument('group')
        args = parser.parse_args(args=sys.argv[2:])
        repo.describe_group(args.group)
        sys.exit(0)
        
    elif command == 'modify-user' or command == 'mu':
        parser = argparse.ArgumentParser(prog='repoman modify-user', description='Updates the metadata for a user in the Repoman repository.', usage='%(prog)s user [--META_KEY META_VALUE]')
        parser.add_argument('user')
        args = parser.parse_known_args(args=sys.argv[2:])
        metadata = dict([(args[1][i].strip('-'), args[1][i+1]) for i in range(0, len(args[1]) - 1, 2)])
        print "Modifying user "+args[0].user+" with metadata:"
        for item in metadata:
            print item+": "+metadata[item]
        repo.modify_user(args[0].user, metadata)
        sys.exit(0)

    elif command == 'modify-group' or command == 'mg':
        parser = argparse.ArgumentParser(prog='repoman modify-group', description='Updates the metadata for a group in the Repoman repository.', usage='%(prog)s group [--META_KEY META_VALUE]')
        parser.add_argument('group')
        args = parser.parse_known_args(args=sys.argv[2:])
        metadata = dict([(args[1][i].strip('-'), args[1][i+1]) for i in range(0, len(args[1]) - 1, 2)])
        print args[0].group
        print metadata
        repo.modify_group(args[0].group, metadata)
        sys.exit(0)     
        
    elif command == 'create-image' or command == 'ci':
        parser = argparse.ArgumentParser(prog='repoman create-image', description='Creates an image on the Repoman repository.  The minimum required metadata is --name NAME.  If a file to upload is specified but a name is not, the name is set to the filename.', usage='%(prog)s [--file FILENAME] [--META_KEY VALUE]')
        # [--file FILE] [--METAVAR VALUE ...]
        parser.add_argument('--file', action='store', help='specifies a full to upload. if no name specified, defaults to filename')
        args = parser.parse_known_args(args=sys.argv[2:])
        metadata = dict([(args[1][i].strip('-'), args[1][i+1]) for i in range(0, len(args[1]) - 1, 2)])
        try:
            name = metadata['name']
        except:
            try:
                metadata['name'] = os.path.split(args[0].file)[1]
                name = metadata['name']
            except:
                print 'usage: repoman create-image [--file FILENAME] [--META_KEY VALUE]'
                print " "
                print "Creates an image on the Repoman repository."
                print "The minimum required metadata is --name NAME."
                print "If a file to upload is specified but a name is not, the name is set to the filename."
                print " "
                print "optional arguments:"
                print "   --file FILENAME      upload an image file with the metadata"
                print "   --META_KEY VALUE     add metadata to the image"     
                print "   -h, --help           show this help message and exit"
                sys.exit(0)
        #Server is expecting Bool objects for readonly
        try:
            read_only = metadata['read_only']
            true_values = ['t', 'True', 'true']
            if true_values.count(metadata['read_only']):
                metadata['read_only'] = True
            else:
                metadata['read_only'] = False
        except:
            pass
        print "Creating image "+name+" with metadata: "
        for key in metadata:
            print key+": "+str(metadata[key])
        repo.update_metadata(metadata=metadata, exists=False)
        if args[0].file is not None:
            print "Uploading image file "+args[0].file+'...'
            if not os.path.isfile(args[0].file):
                print "The file you specified does not exist."
                sys.exit(1)
            else:
                repo.upload_image(args[0].file, image=metadata['name'], metadata=metadata)
                sys.exit(0)
        sys.exit(0)
        
    elif command == 'share-image' or command == 'si':
        parser = argparse.ArgumentParser(prog='repoman share-image', description='Shares an image with another user or group.', usage='%(prog)s image [[--user | -u] USERNAME] [[ --group | -g] GROUPNAME]')
        parser.add_argument('image', help='image to share')
        parser.add_argument('--user','-u', help='user to share with')
        parser.add_argument('--group','-g', help='group to share with')
        args = parser.parse_args(args=sys.argv[2:])
        if args.user:
            print "Sharing image "+args.image+" with user "+args.user+"..."
            repo.share_user(args.image, args.user)
            sys.exit(0)
        if args.group:
            print "Sharing image "+args.image+" with group "+args.group+"..."
            repo.share_group(args.image,args.group)
            sys.exit(0)
        sys.exit(0)
                
    elif command == 'unshare-image' or command == 'usi':
        parser = argparse.ArgumentParser(prog='repoman unshare-image', description='Removes a previous share from another user or group.', usage='%(prog)s image [[--user | -u] USERNAME] [[ --group | -g] GROUPNAME]')
        parser.add_argument('image', help='image to remove share from')
        parser.add_argument('--user','-u', help='user to remove share from')
        parser.add_argument('--group','-g', help='group to remove share from')
        args = parser.parse_args(args=sys.argv[2:])
        if args.user:
            print "Unsharing image "+args.image+" with user "+args.user+"..."
            repo.unshare_user(args.image, args.user)
            sys.exit(0)
        if args.group:
            print "Unsharing image "+args.image+" with group "+args.group+"..."
            repo.unshare_group(args.image,args.group)
            sys.exit(0)
        sys.exit(0)
    
    elif command == 'snapshot-system' or command == 'ss':
        parser = argparse.ArgumentParser(prog='repoman snapshot-system', description='Snapshots currently running system and either stores it locally or uploads it to the repository.', usage='%(prog)s [--force | -f] [--upload | -u] [--META_KEY VALUE]')
        parser.add_argument('--upload', action='store_true', default=False)
        parser.add_argument('--force','-f', action='store_true', default=False)
        args = parser.parse_known_args(args=sys.argv[2:])
        metadata = dict([(args[1][i].strip('-'), args[1][i+1]) for i in range(0, len(args[1]) - 1, 2)])
        if args[0].upload:
            try:
                name = metadata['name']
            except:
                print "Please enter at least a name as metadata with --name IMAGE_NAME."
                sys.exit(1)
            images = repo.list_images_raw()
            exists = False
            for image in images:
                if metadata['name'] == image.split('/')[6]:
                    exists = True
                    if not args[0].force:
                        print 'WARNING!! This image already exists on the repository.'
                        if not ask_yes_or_no(force=True):
                            print 'Exiting repoman-client.'
                            sys.exit(2)
            try:
                read_only = metadata['read_only']
                true_values = ['t', 'True', 'true']
                if true_values.count(metadata['read_only']):
                    metadata['read_only'] = True
                else:
                    metadata['read_only'] = False
            except:
                pass
            print "Snapshotting system and uploading with the following metadata:"
            for key in metadata:
                print key+": "+metadata[key]
            repo.update_metadata(metadata=metadata, exists=exists)
            repo.upload_snapshot(metadata=metadata,replace=exists, snapshot_complete=False)
            sys.exit(0)
        else:
            repo.snapshot_system()
            print "Local filesystem synced and prepared for upload at "+repo.return_snapshot_mount()+"."
            print "To upload this image to the repository, run repoman upload-snapshot --META VALUE."
            sys.exit(0)

    elif command == 'save':
        parser = argparse.ArgumentParser(prog='repoman save', description='Snapshots current system and uploads it to the repository.', usage='%(prog)s [--force | -f] [--META_KEY VALUE]')
        parser.add_argument('--force','-f', action='store_true', default=False)
        args = parser.parse_known_args(args=sys.argv[2:])
        metadata = dict([(args[1][i].strip('-'), args[1][i+1]) for i in range(0, len(args[1]) - 1, 2)])
        try:
            name = metadata['name']
        except:
            print "Please enter at least a name as metadata with --name IMAGE_NAME."
            sys.exit(1)
        images = repo.list_images_raw()
        exists = False
        for image in images:
            if metadata['name'] == image.split('/')[6]:
                exists = True
                if not args[0].force:
                    print 'WARNING!! This image already exists on the repository.'
                    if not ask_yes_or_no(force=True):
                        print 'Exiting repoman-client.'
                        sys.exit(2)
        try:
            read_only = metadata['read_only']
            true_values = ['t', 'True', 'true']
            if true_values.count(metadata['read_only']):
                metadata['read_only'] = True
            else:
                metadata['read_only'] = False
        except:
            pass
        print "Snapshotting system and uploading with the following metadata:"
        for key in metadata:
            print key+": "+metadata[key]
        repo.update_metadata(metadata=metadata, exists=exists)
        repo.upload_snapshot(metadata=metadata,replace=exists, snapshot_complete=False)
        sys.exit(0)

    elif command == 'upload-snapshot' or command == 'us':
        parser = argparse.ArgumentParser(prog='repoman upload-snapshot', description='Uploads a snapshot to the repository.  The snapshot created by upload-snapshot is stored in the location defined in the configfile.  Run "repoman about" to see the image location.', usage='%(prog)s [--force | -f] [--META_KEY VALUE]')
        parser.add_argument('--force','-f', action='store_true', default=False)
        args = parser.parse_known_args(args=sys.argv[2:])
        metadata = dict([(args[1][i].strip('-'), args[1][i+1]) for i in range(0, len(args[1]) - 1, 2)])
        try:
            name = metadata['name']
        except:
            print "usage: repoman upload-snapshot [--force | -f] [--META_KEY VALUE]"
            print ""
            print "Uploads a snapshot to the repository. The snapshot created by upload-snapshot is stored in the location defined in the configfile. Run 'repoman about' to see the image location."
            print "The minimum amount of metadata is a name (--name IMAGE_NAME)."
            print ""
            print "optional arguments:"
            print "  -h, --help   show this help message and exit"
            print "  --force, -f"
            sys.exit(1)
        images = repo.list_images_raw()
        exists = False
        for image in images:
            if metadata['name'] == image.split('/')[6]:
                exists = True
                if not args[0].force:
                    print 'WARNING!! This image already exists on the repository.'
                    if not ask_yes_or_no(force=True):
                        print 'Exiting repoman-client.'
                        sys.exit(2)
        print "Snapshotting image "+name+" with the following metadata:"
        for key in metadata:
            print key+": "+metadata[key]
        repo.update_metadata(metadata=metadata, exists=exists)
        repo.upload_snapshot(metadata=metadata,replace=exists, snapshot_complete=True)
        sys.exit(0)
        
    elif command == 'upload-image' or command == 'ui':
        parser = argparse.ArgumentParser(prog='repoman upload-image', description='Uploads a file to a previously-created image on the repository.', usage='%(prog)s [USER/]image --file FILE_NAME')
        parser.add_argument('image', help='image on repository to upload to')
        parser.add_argument('--file', required=True, help='file to upload')
        args = parser.parse_args(args=sys.argv[2:])
        if not os.path.isfile(args.file):
            print "The file "+args.file+" does not exist.  Please try again."
            sys.exit(0)
        images = repo.list_images_raw()
        exists = False
        for image in images:
            if args.image == image.split('/')[6]:
                exists = True
        if not exists:
            print "This image does not exist."
            sys.exit(0)
        repo.upload_image(args.file,image=args.image)
        sys.exit(0)
        
    elif command == 'add-users-to-group' or command == 'aug':
        parser = argparse.ArgumentParser(prog='repoman add-users-to-group', description='Adds user to a group on the repository.', usage='%(prog)s group --users USER1 USER2...')
        parser.add_argument('group', help='group to add users to')
        parser.add_argument('--users','-u', nargs='+', help='users to add')
        args = parser.parse_args(args=sys.argv[2:])
        repo.add_users_to_group(args.group, args.users)
        sys.exit(0)
        
    elif command == 'remove-users-from-group' or command == 'rug':
        parser = argparse.ArgumentParser(prog='repoman remove-users-from-group', description='Removes users from a group on the repository.', usage='%(prog)s group --users USER1 USER2...')
        parser.add_argument('group', help='group to remove users from')
        parser.add_argument('--users','-u', nargs='+', help='users to remove')
        args = parser.parse_args(args=sys.argv[2:])
        repo.remove_users_from_group(args.group, args.users)
        sys.exit(0)
        
    elif command == 'add-permissions' or command == 'ap':
        parser = argparse.ArgumentParser(prog='repoman add-permissions', description='Adds permissions to a group on the repository.', usage='%(prog)s group --permissions PERMISSION1 PERMISSION2...')
        parser.add_argument('group', help='group to add permissions to')
        parser.add_argument('--permissions', nargs='+', help='permissions to add')
        args = parser.parse_args(args=sys.argv[2:])
        if not args.permissions:
            print "Please enter at least one permission to add."
            sys.exit(1)
        repo.add_permissions(args.group, args.permissions)
        sys.exit(0)
        
    elif command == 'remove-permissions' or command == 'rp':
        parser = argparse.ArgumentParser(prog='repoman remove-permissions', description='Removes permissions from a group on the repository.', usage='%(prog)s group --permissions PERMISSION1 PERMISSION2...')
        parser.add_argument('group', help='group to remove permissions from')
        parser.add_argument('--permissions', nargs='+', help='permissions to remove')
        args = parser.parse_args(args=sys.argv[2:])
        if not args.permissions:
            print "Please enter at least one permission to remove."
            sys.exit(1)
        repo.remove_permissions(args.group, args.permissions)
        sys.exit(0)

    elif command == 'about' or command == 'a':
        print "Repoman-client"
        print "Version:                     0.2.4"
        print "User certificate:            "+repo.return_usercert()
        print "User key:                    "+repo.return_userkey()
        print "Repository:                  "+repo.return_repo()
        print "Snapshot image location:     "+repo.return_snapshot_location()
        print "Snapshot mount location:     "+repo.return_snapshot_mount()
        sys.exit(0)

    elif command == '--help' or command == '-h':
        try:
            arg = sys.argv[2]
        except:
            print_help_menu(False)
            sys.exit(0)
        if arg == '--all' or arg == '-a':
            print_help_menu(True)
            sys.exit(0)
        else:
            print_help_menu(False)
            sys.exit(0)
        
        sys.exit(0)
        
    elif command == '--version' or command == '-v':
        print "Repoman-Client"
        print "Version 0.2.4"
        sys.exit(0)

    else:
        print "Command not recognized."
        print_help_menu(False)
        sys.exit(0)

if __name__ == "__main__":
    main() 
