#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# Author: Chmouel Boudjnah <chmouel@enovance.com>
# Author: Fabien Boucher <fabien.boucher@enovance.com>
#
# 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.

"""Simple script to get a global usage of a swift cluster. Install the
pypi module ```hurry.filesize``` to get prettier size output (by
default in bytes).

eg: swift-df.py http://localhost:5000/v2.0 tenant:admin ADMIN
First argument is the AUTH_URL
Second argument is the ADMIN_TENANT:ADMIN_USER (i.e: tenant:admin)
Third argument is the ADMIN_PASSWORD

"""
import argparse
import eventlet

import keystoneclient.v2_0.client
import swiftclient

from swstat import report
from swstat import swstat


eventlet.patcher.monkey_patch()

#TODO(fbo): Could add content_type repartition


def get_swift_auth(auth_url, tenant, user, password, os_options):
    """Get swift connection from args."""
    return swiftclient.client.Connection(
        auth_url,
        '%s:%s' % (tenant, user),
        password,
        auth_version=2,
        os_options=os_options).get_auth()


def main():
    parser = argparse.ArgumentParser(add_help=True)
    parser.add_argument('-r', action='store_true',
                        dest="raw_output",
                        help='No human output')
    parser.add_argument('-d', action='store_true',
                        dest="detailed",
                        help='Get a detailed output')
    parser.add_argument('--endpoint-type',
                        metavar='ENDPOINT_TYPE',
                        type=str,
                        default='public', help='The endpoint type')
    parser.add_argument('--file-path',
                        metavar='PATH',
                        type=str, default=None,
                        help='File to output stats results')
    parser.add_argument('auth_url', metavar='AUTH_URL', type=str,
                        help='The Keystone auth URL')
    parser.add_argument('tenant_user', metavar='TENANT:USER', type=str,
                        help='The admin tenant and user')
    parser.add_argument('password', metavar='PASSWORD', type=str,
                        help='The admin password')
    parser.add_argument('--bare_storage_url', metavar='BARE_STORAGE_URL',
                        type=str)
    parser.add_argument('--tenants', metavar='TENANT1,...,TENANTn', type=str,
                        help='list of comma-separated tenants to scan,'
                             ' defaults to all')


    args = parser.parse_args()
    (admin_tenant, admin_user) = args.tenant_user.split(':')
    keystone_cnx = keystoneclient.v2_0.client.Client(auth_url=args.auth_url,
                                                     username=admin_user,
                                                     password=args.password,
                                                     tenant_name=admin_tenant)

    os_options = {
        'endpoint_type': args.endpoint_type,
    }
    storage_url, admin_token = get_swift_auth(args.auth_url,
                                              admin_tenant,
                                              admin_user,
                                              args.password,
                                              os_options)
    bare_storage_url = (args.bare_storage_url and args.bare_storage_url or
                        storage_url[:storage_url.find('AUTH_')] + "AUTH_")

    tenants = keystone_cnx.tenants.list()
    tenant_lists = []
    if args.tenants:
        args_tenants = args.tenants.split(',')
        for t in args_tenants:
            valid = [tenant for tenant in tenants
                     if (t == tenant.name or t == tenant.id)]
            if valid:
                tenant_lists.append(valid[0])
            else:
                print >> sys.stderr, "tenant %s not found, skipping." % t
    else:
        #print "# Listing all available tenants"
        tenant_lists = tenants
    stats = []
    pile = eventlet.GreenPile(size_or_pool=10)
    for tenant in tenant_lists:
        try:
            email = keystone_cnx.users.list(tenant_id=tenant.id)[0].email
        except(AttributeError, IndexError):
            email = "None"
        try:
            pile.spawn(swstat.retrieve_account_stats, tenant,
                       bare_storage_url, os_options, admin_token, email)
        except(swiftclient.client.ClientException), x:
            print x
            continue
    for ret in pile:
        stats.append(ret)
    if args.detailed:
        path = None
        if args.file_path is not None:
            path = args.file_path + '-detailed'
        report.report_detailed_stats(stats, raw_output=args.raw_output,
                                     path=path)
    report.report_global_stats(stats, raw_output=args.raw_output,
                               path=args.file_path)

if __name__ == '__main__':
    main()
