#!/usr/bin/env python
#
# Author: Hans Chris Jones <chris.jones@lambdastack.io>
#
# Copyright 2017, Bloomberg Finance L.P.
#
# 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 sys
import os
import locale
import argparse
import datetime
import subprocess
import json
import csv
import boto
import boto.s3.connection
from boto.s3.connection import Location
from boto.s3.bucket import Bucket

# rgw_s3_api.py is a collection of Python functions to do S3 things...
import rgw_s3_api

VERSION="0.1.7"

# These values get set by the functions below
conn = ''
admin_user = ''
user = ''
key = ''
secret = ''
bucket = ''
endpoint = ''
port = 80
region = None
zone = None

# NB: Outputs both JSON and CSV for pulling into Excel and graphing etc.

def error(code, message):
    print "Error: %d - %s" % (code, message)


# Returns JSON output from radosgw-admin and converts it to dict
# cmd is an array and NOT a string
def radosgw_admin(cmd):
    process = subprocess.Popen(cmd, env=os.environ.copy(), stdout=subprocess.PIPE)
    json_output, err = process.communicate()
    if err:
        error(500, err)
        return None

    return json.loads(json_output)


# This data is from the usage log of radosgw (must have 'rgw usage log = true' in the ceph.conf). It pulls in the usage
# across the wire for a date rante or since the last time the usage log reset (radosgw restart or hard reset option).
# Basically, what has come across the wire.

# Display on terminal. Data is always written to json and csv files. These files can be read by web service, pushed into
# cluster for later extraction based on dates or pushed into git or something else.
def get_usage(start_date=None, end_date=None, show_log_entries=False):
    retcode = False

    try:
        start_date_str = ""
        end_date_str = ""

        if start_date is not None:
            start_date_str = "--start-date=%s" % start_date

        if end_date is not None:
            end_date_str = "--end-date=%s" % end_date

        if region is None and zone is None:
            cmd = ["/usr/bin/radosgw-admin", "usage", "show", start_date_str, end_date_str, "--show-log-entries=%s" % show_log_entries]
        else:
            cmd = ["sudo", "/bin/radosgw-admin", "usage", "show", "-n", "client.radosgw.%s-%s" % (region, zone), start_date_str, end_date_str, "--show-log-entries=%s" % show_log_entries]

        json_data = radosgw_admin(cmd)
        if json_data:
            total_puts = 0
            total_gets = 0

            # Set locale for other types
            locale.setlocale(locale.LC_ALL, 'en_US')
            for data in json_data['summary']:
                total_puts += data['total']['bytes_received']
                total_gets += data['total']['bytes_sent']

                print "%s - Bytes" % data['user']
                print "\tPUT: %s" % locale.format("%d", data['total']['bytes_received'], grouping=True)
                print "\tGET: %s" % locale.format("%d", data['total']['bytes_sent'], grouping=True)
                print "\tOperations: %s" % locale.format("%d", data['total']['successful_ops'], grouping=True)
                print '-'*60

            print "Total PUT: %s" % locale.format("%d", total_puts, grouping=True)
            print "Total GET: %s" % locale.format("%d", total_gets, grouping=True)
            print '='*60

            retcode = True
    except Exception, e:
        print e

    return retcode


# If output is None then don't write the json data and only return the json users else write the user json and return it.
def get_users(output=None):
    users = None

    try:
        if region is None and zone is None:
            cmd = ["/usr/bin/radosgw-admin", "metadata", "list", "user"]
        else:
            cmd = ["sudo", "/bin/radosgw-admin", "metadata", "list", "user", "-n", "client.radosgw.%s-%s" % (region, zone)]

        json_data = radosgw_admin(cmd)
        if json_data:
            users = json_data
            if output is not None:
                with open("%s/users-%s.json" % (output, zone), 'w') as f:
                    json_data = {"users": users}
                    f.write(json.dumps(json_data, indent=4, sort_keys=True))

                with open("%s/users-%s.csv" % (output, zone), 'w') as csv_file:
                    # NB: Since only one column just write it
                    for data in users:
                        csv_file.write(data + '\n')

    except Exception, e:
        print e

    return users


# Pass in the uid and return the user which you can then extract the attribute(s) you like
def get_user(uid):
    data = None

    try:
        if region is None and zone is None:
            cmd = ["/usr/bin/radosgw-admin", "user", "info", "--uid", "%s" % uid]
        else:
            cmd = ["sudo", "/bin/radosgw-admin", "user", "info", "-n", "client.radosgw.%s-%s" % (region, zone), "--uid", "%s" % uid]

        json_data = radosgw_admin(cmd)
        if json_data:
            data = json_data

    except Exception, e:
        print e

    return data

# Must pass a valid user id. If bucket is None then pull stats on all buckets for the given user or just the bucket
# passed in.
def get_user_bucket_stats(uid, bucket=None, output=None):
    bucket_stats = None

    try:
        bucket_str = ""

        if bucket is not None:
            bucket_str = "--bucket=%s" % bucket

        if region is None and zone is None:
            cmd = ["/usr/bin/radosgw-admin", "bucket", "stats", "--uid", "%s" % uid if bucket is None else "", "%s" % bucket_str]
        else:
            cmd = ["sudo", "/bin/radosgw-admin", "bucket", "stats", "--uid", "%s" % uid if bucket is None else "", "%s" % bucket_str, "-n", "client.radosgw.%s-%s" % (region, zone)]

        json_data = radosgw_admin(cmd)
        if json_data:
            if output is not None:
                bucket_stats = json_data
                user = get_user(uid)
                if user is not None:
                    display_name = user['display_name']
                else:
                    display_name = ""

                with open("%s/usage-%s-%s.json" % (output, uid, zone), 'w') as f:
                    json_data = {"bucket_stats": bucket_stats}
                    f.write(json.dumps(json_data, indent=4, sort_keys=True))

                with open("%s/usage-%s-%s.csv" % (output, uid, zone), 'w') as csv_file:
                    fieldnames = ['uid', 'display_name', 'bucket', 'size_kb', 'size_kb_actual', 'num_objects', 'bucket_quota', 'bucket_quota_size', 'bucket_quota_objects']
                    csvwriter = csv.DictWriter(csv_file, fieldnames=fieldnames)

                    if bucket is not None:
                        size_kb = 0
                        size_kb_actual = 0
                        num_objects = 0
                        bucket_quota = False
                        bucket_quota_size = 0
                        bucket_quota_objects =0

                        if bucket_stats['usage'] and bucket_stats['usage']['rgw.main']:
                            size_kb = bucket_stats['usage']['rgw.main']['size_kb']
                            size_kb_actual = bucket_stats['usage']['rgw.main']['size_kb_actual']
                            num_objects = bucket_stats['usage']['rgw.main']['num_objects']

                        if bucket_stats['bucket_quota'] and bucket_stats['bucket_quota']['enabled']:
                            bucket_quota = True
                            bucket_quota_size = bucket_stats['bucket_quota']['max_size_kb'] if bucket_stats['bucket_quota']['max_size_kb'] > 0 else 0
                            bucket_quota_objects = bucket_stats['bucket_quota']['max_objects'] if bucket_stats['bucket_quota']['max_objects'] > 0 else 0

                        bucket_stat2 = {"uid": uid, "display_name": display_name, "bucket": bucket, "size_kb": size_kb, "size_kb_actual": size_kb_actual, "num_objects": num_objects, "bucket_quota": bucket_quota, "bucket_quota_size": bucket_quota_size, "bucket_quota_objects": bucket_quota_objects}
                        csvwriter.writerow(bucket_stat2)
                    else:
                        csvwriter.writeheader()

                        for bucket_stat in bucket_stats:
                            size_kb = 0
                            size_kb_actual = 0
                            num_objects = 0
                            bucket_quota = False
                            bucket_quota_size = 0
                            bucket_quota_objects =0

                            if bucket_stats['usage'] and bucket_stats['usage']['rgw.main']:
                                size_kb = bucket_stats['usage']['rgw.main']['size_kb']
                                size_kb_actual = bucket_stats['usage']['rgw.main']['size_kb_actual']
                                num_objects = bucket_stats['usage']['rgw.main']['num_objects']

                            if bucket_stats['bucket_quota'] and bucket_stats['bucket_quota']['enabled']:
                                bucket_quota = True
                                bucket_quota_size = bucket_stats['bucket_quota']['max_size_kb'] if bucket_stats['bucket_quota']['max_size_kb'] > 0 else 0
                                bucket_quota_objects = bucket_stats['bucket_quota']['max_objects'] if bucket_stats['bucket_quota']['max_objects'] > 0 else 0

                            bucket_stat2 = {"uid": uid, "display_name": display_name, "bucket": bucket, "size_kb": size_kb, "size_kb_actual": size_kb_actual, "num_objects": num_objects, "bucket_quota": bucket_quota, "bucket_quota_size": bucket_quota_size, "bucket_quota_objects": bucket_quota_objects}
                            csvwriter.writerow(bucket_stat2)

    except Exception, e:
        print e

    return bucket_stats


def user_stats_sync(uid, output=None):
    user_stats = None

    try:
        if region is None and zone is None:
            cmd = ["/usr/bin/radosgw-admin", "user", "stats", "--uid", "%s" % uid, "--sync-stats"]
        else:
            cmd = ["sudo", "/bin/radosgw-admin", "user", "stats", "--uid", "%s" % uid, "--sync-stats", "-n", "client.radosgw.%s-%s" % (region, zone)]

        json_data = radosgw_admin(cmd)
        if json_data:
            user = get_user(uid)
            if user is not None:
                display_name = user['display_name']
            else:
                display_name = ""

            if output is not None:
                user_stats = json_data
                with open("%s/user-stats-sync-%s-%s.json" % (output, uid, zone), 'w') as f:
                    json_data = {"user_stats": user_stats}
                    f.write(json.dumps(json_data, indent=4, sort_keys=True))

                with open("%s/user-stats-sync-%s-%s.csv" % (output, uid, zone), 'w') as csv_file:
                    # NB: The CSV library is not very robust so you must flatten out json. A better way would
                    # be more generic and cycle through each attribute and flatten as it went.

                    fieldnames = ['uid', 'display_name', 'total_entries', 'total_bytes', 'total_bytes_rounded', 'last_stats_sync']

                    ustats = {"uid": uid, "display_name": display_name, "total_entries": user_stats['stats']['total_entries'], "total_bytes": user_stats['stats']['total_bytes'], "total_bytes_rounded": user_stats['stats']['total_bytes_rounded'], "last_stats_sync": user_stats['last_stats_sync']}

                    csvwriter = csv.DictWriter(csv_file, fieldnames=fieldnames)
                    csvwriter.writerow(ustats)

    except Exception, e:
        print "UID: %s" % uid
        print e

    return user_stats

def users_stats_sync(user=None, output=None, show_zero=False):
    users_stats = []
    users = get_users(output)
    if users:
        for usr in users:
            user_search = None
            if user is not None:
                if usr == user:
                    user_search = usr
            else:
                user_search = usr

            if user_search is not None:
                user_stats = user_stats_sync(user_search, output=output)
                if user_stats:
                    users_stats.append({"uid": user_search, "user_stats": user_stats})

    if users_stats:
        if output is not None:
            with open("%s/user-stats-total-%s.json" % (output, zone), 'w') as f:
                json_data = {"user_stats": users_stats}
                f.write(json.dumps(json_data, indent=4, sort_keys=True))

            with open("%s/user-stats-total-%s.csv" % (output, zone), 'w') as csv_file:
                fieldnames = ['uid', 'display_name', 'total_entries', 'total_bytes', 'total_bytes_rounded', 'last_stats_sync']

                csvwriter = csv.DictWriter(csv_file, fieldnames=fieldnames)
                csvwriter.writeheader()

                for data in users_stats:
                    user = get_user(data['uid'])
                    if user is not None:
                        display_name = user['display_name']
                    else:
                        display_name = ""

                    user_stats = data['user_stats']['stats']
                    ustats = {"uid": data['uid'], "display_name": display_name, "total_entries": user_stats['total_entries'], "total_bytes": user_stats['total_bytes'], "total_bytes_rounded": user_stats['total_bytes_rounded'], "last_stats_sync": data['user_stats']['last_stats_sync']}
                    csvwriter.writerow(ustats)

    print 'Generating users stats...'
    print

    users_stats_summary(users_stats, show_zero=show_zero)

    return 0  # Force good


# Display on terminal. Data is always written to json and csv files. These files can be read by web service, pushed into
# cluster for later extraction based on dates or pushed into git or something else.
def users_stats_summary(users_stats, show_zero=False):
    if users_stats:
        user_total = 0
        object_count = 0
        total = 0
        total_objects = 0
        user = ''
        first_pass = True

        # Set locale for other types
        locale.setlocale(locale.LC_ALL, 'en_US')
        # A list of lists of buckets
        for data in users_stats:
            if user != data['uid']:
                if not first_pass:
                    if show_zero or (show_zero is False and user_total > 0):
                        print "%s" % user
                        print "\tTotal (bytes): %s" % locale.format("%d", user_total, grouping=True)
                        print "\tObjects: %s" % locale.format("%d", object_count, grouping=True)
                        print '-'*60

                    total_objects += object_count
                    total += user_total

                    user_total = 0
                    object_count = 0

                user = data['uid']
                first_pass = False

            user_total += data['user_stats']['stats']['total_bytes_rounded']
            object_count += data['user_stats']['stats']['total_entries']

        # Catch last one
        if not first_pass:
            if show_zero or (show_zero is False and user_total > 0):
                print "%s" % user
                print "\tTotal (bytes): %s" % locale.format("%d", user_total, grouping=True)
                print "\tObjects: %s" % locale.format("%d", object_count, grouping=True)
                print '-'*60

            total_objects += object_count
            total += user_total

        print "Total Objects: %s" % locale.format("%d", total_objects, grouping=True)
        print "Total Data Used (Bytes): %s" % locale.format("%d", total, grouping=True)
        print '='*60
    else:
        print 'No user stats!'


def get_bucket_stats(user=None, bucket_output=None, user_output=None):
    bucket_stats = []
    users = get_users(user_output)
    if users:
        for usr in users:
            user_search = None
            if user is not None:
                if usr == user:
                    user_search = usr
            else:
                user_search = usr

            if user_search is not None:
                user2 = get_user(usr)
                if user2 is not None:
                    display_name = user2['display_name']
                else:
                    display_name = ""

                user_bucket_stats = get_user_bucket_stats(user_search, output=bucket_output)
                if user_bucket_stats:
                    bucket_stats.append({"uid": user_search, "display_name": display_name, "buckets": user_bucket_stats})

    if bucket_stats:
        # Write it out for later use maybe...
        if bucket_output is not None:
            with open("%s/usage-total-%s.json" % (bucket_output, zone), 'w') as f:
                json_data = {"bucket_stats": bucket_stats}
                f.write(json.dumps(json_data, indent=4, sort_keys=True))

            with open("%s/bucket_stats-%s.csv" % (bucket_output, zone), 'w') as csv_file:
                fieldnames = ['uid', 'display_name', 'bucket', 'size_kb', 'size_kb_actual', 'num_objects', 'bucket_quota', 'bucket_quota_size', 'bucket_quota_objects']
                csvwriter = csv.DictWriter(csv_file, fieldnames=fieldnames)
                csvwriter.writeheader()

                for bucket_stat in bucket_stats:
                    size_kb = 0
                    size_kb_actual = 0
                    num_objects = 0
                    bucket_quota = False
                    bucket_quota_size = 0
                    bucket_quota_objects =0

                    if bucket_stats['usage'] and bucket_stats['usage']['rgw.main']:
                        size_kb = bucket_stats['usage']['rgw.main']['size_kb']
                        size_kb_actual = bucket_stats['usage']['rgw.main']['size_kb_actual']
                        num_objects = bucket_stats['usage']['rgw.main']['num_objects']

                    if bucket_stats['bucket_quota'] and bucket_stats['bucket_quota']['enabled']:
                        bucket_quota = True
                        bucket_quota_size = bucket_stats['bucket_quota']['max_size_kb'] if bucket_stats['bucket_quota']['max_size_kb'] > 0 else 0
                        bucket_quota_objects = bucket_stats['bucket_quota']['max_objects'] if bucket_stats['bucket_quota']['max_objects'] > 0 else 0

                    bucket_stat2 = {"uid": uid, "display_name": display_name, "bucket": bucket, "size_kb": size_kb, "size_kb_actual": size_kb_actual, "num_objects": num_objects, "bucket_quota": bucket_quota, "bucket_quota_size": bucket_quota_size, "bucket_quota_objects": bucket_quota_objects}
                    csvwriter.writerow(bucket_stat2)

    bucket_stats_summary(bucket_stats)

    return 0  # Force good


# Display on terminal. Data is always written to json and csv files. These files can be read by web service, pushed into
# cluster for later extraction based on dates or pushed into git or something else.
def bucket_stats_summary(bucket_stats):
    if bucket_stats:
        bucket_total = 0
        bucket_count = 0
        object_count = 0
        total = 0
        total_buckets = 0
        total_objects = 0
        user = ''
        first_pass = True

        # Set locale for other types
        locale.setlocale(locale.LC_ALL, 'en_US')
        # A list of lists of buckets
        for data in bucket_stats:
            if user != data['uid']:
                if not first_pass:
                    print "%s" % user
                    print "\tBucket total: %s" % locale.format("%d", bucket_count, grouping=True)
                    print "\tObjects: %s" % locale.format("%d", object_count, grouping=True)
                    print "\tData used for user (kb): %s" % locale.format("%d", bucket_total, grouping=True)
                    print '-'*60

                    total_buckets += bucket_count
                    total_objects += object_count
                    total += bucket_total

                    bucket_count = 0
                    bucket_total = 0
                    object_count = 0

                user = data['user']
                first_pass = False

            for bucket_data in data['buckets']:
                bucket_count += 1
                try:
                    bucket_total += bucket_data['usage']['rgw.main']['size_kb_actual']
                    object_count += bucket_data['usage']['rgw.main']['num_objects']
                except Exception, e:
                    pass

        # Catch last one
        if not first_pass:
            print "%s" % user
            print "\tBucket total: %s" % locale.format("%d", bucket_count, grouping=True)
            print "\tObjects: %s" % locale.format("%d", object_count, grouping=True)
            print "\tData used for user (kb): %s" % locale.format("%d", bucket_total, grouping=True)
            print '-'*60

            total_buckets += bucket_count
            total_objects += object_count
            total += bucket_total

        print "Total Buckets: %s" % locale.format("%d", total_buckets, grouping=True)
        print "Total Objects: %s" % locale.format("%d", total_objects, grouping=True)
        print "Total Data Used (kb): %s" % locale.format("%d", total, grouping=True)
        print '='*60
    else:
        print 'No bucket stats!'


def user_connect():
    global conn
    conn = rgw_s3_api.connect(key, secret, endpoint, port=port)  # There are many other options
    return conn


def get_user_secrets():
    global key
    global secret

    retcode = False
    try:
        if region is None and zone is None:
            cmd = ["/usr/bin/radosgw-admin", "user", "info", "--uid", "%s" % user]
        else:
            cmd = ["sudo", "/bin/radosgw-admin", "user", "info", "--uid", "%s" % user, "-n", "client.radosgw.%s-%s" % (region, zone)]

        user_dict = radosgw_admin(cmd)
        if user_dict:
            # Only gets the first one. User can have a number of key/secret pairs
            key = user_dict['keys'][0]['access_key']
            secret = user_dict['keys'][0]['secret_key']
            retcode = True
    except BaseException, e:
        error(e.errno, e.message)

    return retcode

def get_bucket(bucket_name, actions, headers=None, validate=True, verbose=False):
    global bucket

    retcode = False

    if not bucket_name:
        error(500, 'Missing bucket name.')
        return retcode

    create = False
    make_public = False

    for action in actions:
        if action == 'create':
            create = True
        if action == 'public':
            make_public = True

    bucket = rgw_s3_api.bucket_handle(conn, bucket_name, validate=validate, headers=headers, create=create, make_public=make_public, verbose=verbose)
    if not bucket:
        error(404, 'Bucket not found.')
        return retcode
    else:
        return True


def create_user(uid, display_name, access_key=None, secret_key=None):
    data = None

    try:
        if region is None and zone is None:
            cmd = ["/usr/bin/radosgw-admin", "user", "create", "--uid", "%s" % uid, "--display-name", "%s" % display_name]
        else:
            cmd = ["sudo", "/bin/radosgw-admin", "user", "create", "-n", "client.radosgw.%s-%s" % (region, zone), "--uid", "%s" % uid, "--display-name", "%s" % display_name]

        if access_key is not None and secret_key is not None:
            cmd.append("--access-key=%s" % access_key)
            cmd.append("--secret=%s" % secret_key)

        json_data = radosgw_admin(cmd)
        if json_data:
            data = json_data

    except Exception, e:
        print e

    return data


# Define a class for returns
def tasks(options):
    if find_action(options.actions, 'list'):
        rgw_s3_api.bucket_list(bucket)
        return None

    if find_action(options.actions, 'user'):
        if find_action(options.actions, 'create'):
            return create_user(options.user, options.display_name, options.access, options.secret)
            # NB: This call uses the S3 Auth verison - wip
            # return rgw_s3_api.user_create(conn, options.admin, options.user, options.display_name)

    if options.object:
        if not options.location and not options.object_string:
            error(400, 'Object location and/or object-string actions are not specified. At least one is required.')
            return None

        # NB: The rest of the actions require a valid bucket name
        if len(bucket) > 0:
            if find_action(options.actions, 'usage'):
                return get_usage(options.start_date, options.end_date, options.show_log_entries)
            if find_action(options.actions, 'put'):
                return rgw_s3_api.object_create(bucket, options.object, options.object_string, options.location, make_public=find_action(options.actions, 'public'), headers=options.headers)
            if find_action(options.actions, 'delete'):
                return rgw_s3_api.object_delete(bucket, options.object, headers=options.headers, version_id=options.version_id, mfa_token=None)
            if find_action(options.actions, 'get'):
                return rgw_s3_api.object_get(bucket, options.object, options.location, headers=options.headers, version_id=options.version_id)
            if find_action(options.actions, 'url'):
                signature = rgw_s3_api.object_url(bucket, options.object, signed_duration=options.duration)
                return signature

    return None


def find_action(actions, find_action):
    for action in actions:
        if action == find_action:
            return True
    return False


def main():
    retcode = 1

    p = argparse.ArgumentParser(description='radosgw-admin2 - Adds some missing features to radosgw-admin', prog='radosgw-admin2')
    p.add_argument('--admin', action='store', default='radosgw', help='Admin user name.')
    p.add_argument('--user', '-u', action='store', help='(Required) - Pass in the username used to perform action on.')
    p.add_argument('--display-name', action='store', help='Required when creating user. The display name.')
    p.add_argument('--endpoint', '-e', action='store', help='(Required) - Endpoint URL.')
    p.add_argument('--port', '-p', action='store', default=80, type=int, help='(Required - Defaults to port=80) - Endpoint port.')
    p.add_argument('--access', '-k', action='store', help='(Optional) - Pass in the key of the user.')
    p.add_argument('--secret', '-s', action='store', help='(Optional) - Pass in the secret of the user.')
    p.add_argument('--bucket', '-b', action='store', help='Bucket.')
    p.add_argument('--object', '-o', action='store', help='Object.')
    p.add_argument('--object-string', '-t', action='store', help='Object string - Make an object from the passed in string.')
    p.add_argument('--location', '-l', action='store', default=None, help='Location of object etc.')
    p.add_argument('--headers', action='store', default=None, help='Headers to inject.')
    p.add_argument('--version-id', action='store', default=None, help='Version ID of object.')
    p.add_argument('--duration', '-d', action='store', default=0, type=int, help='Object URL duration in seconds.')
    p.add_argument('--actions', '-a', nargs='+', help='Action(s) to take - N arguments.')
    p.add_argument('--region', '-r', action='store', help='RGW Region (datacenter).')
    p.add_argument('--zone', '-z', action='store', help='RGW Zone (tier).')
    p.add_argument('--start-date', action='store', help='Usage Start Date - yyyy-mm-dd (radosgw-admin restriction of format) - Used only with usage task.')
    p.add_argument('--end-date', action='store', help='Usage End Date - yyyy-mm-dd (radosgw-admin restriction of format) - Used only with usage task.')
    p.add_argument('--show-log-entries', action='store', default=False, help='True/False - default is False - Used only with usage task')
    p.add_argument('--bucket-output', action='store', default='/home/operations', help='Path to place Bucket related JSON data. Defaults to /home/operations')
    p.add_argument('--user-output', action='store', default='/home/operations', help='Path to place User related JSON data. Defaults to /home/operations')
    p.add_argument('--version', '-v', action='version', version="radosgw-admin2 %s" % VERSION)
    p.add_argument('--verbose', '-V', action='store_true', help='Verbose')

    # Make sure to set global since variable will be set
    global admin_user
    global user
    global bucket
    global key
    global secret
    global endpoint
    global port
    global region
    global zone

    options = p.parse_args()

    if options.admin:
        admin_user = options.admin
    if options.user:
        user = options.user
    if options.bucket:
        bucket = options.bucket
    if options.access:
        key = options.access
    if options.secret:
        secret = options.secret
    if options.endpoint:
        endpoint = options.endpoint
    if options.port:
        port = options.port
    if options.region:
        region = options.region
    if options.zone:
        zone = options.zone

    # Change to meet your environment
    if port < 80:
        p.print_help()
        return retcode

    if options.actions is None:
        p.print_help()
        return retcode

    if find_action(options.actions, 'usage'):
        if get_usage(options.start_date, options.end_date, options.show_log_entries) is None:
            return 1
        else:
            return 0

    if find_action(options.actions, 'user-stats-sync'):
        return users_stats_sync(output=options.user_output)

    if find_action(options.actions, 'stats'):
        return get_bucket_stats(bucket_output=options.bucket_output, user_output=options.user_output)

    if not options.user and not options.endpoint:
        p.print_help()
        return retcode

    # These two values are optional but if one is specified then both must be specified
    if options.access and not options.secret:
        p.print_help()
        return retcode

    if options.secret and not options.access:
        p.print_help()
        return retcode

    if not options.access and not options.secret and not find_action(options.actions, 'create'):
        if get_user_secrets() is not True:
            return retcode

    if user_connect() is None:
        return retcode

    # if get_bucket(options.bucket, options.actions, verbose=options.verbose):
    tasks(options)
    retcode = 0
    # else:
    #     # NB: exit code is hard coded to 0 for now. Change later...
    #     tasks(options)
    #     retcode = 0

    return retcode


if __name__ == "__main__":
    sys.exit(main())
