#!/usr/bin/python3
#   Copyright (C) 2013 Canonical Ltd.
#
#   Author: Scott Moser <scott.moser@canonical.com>
#
#   Simplestreams is free software: you can redistribute it and/or modify it
#   under the terms of the GNU Affero General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or (at your
#   option) any later version.
#
#   Simplestreams is distributed in the hope that it will be useful, but
#   WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
#   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
#   License for more details.
#
#   You should have received a copy of the GNU Affero General Public License
#   along with Simplestreams.  If not, see <http://www.gnu.org/licenses/>.
#
# this is python2 as openstack dependencies (swiftclient, keystoneclient,
# glanceclient) are not python3.
#
import argparse
import os.path
import sys

from simplestreams import objectstores
from simplestreams.objectstores import swift
from simplestreams import log
from simplestreams import mirrors
from simplestreams import openstack
from simplestreams import util
from simplestreams.mirrors import glance

DEFAULT_FILTERS = ['ftype~(disk1.img|disk.img)', 'arch~(x86_64|amd64|i386)']


def error(msg):
    sys.stderr.write(msg)


class StdoutProgressAggregator(util.ProgressAggregator):
    def __init__(self, remaining_items):
        super(StdoutProgressAggregator, self).__init__(remaining_items)

    def emit(self, progress):
        size = float(progress['size'])
        written = float(progress['written'])
        print("%.2f %s (%d of %d images) - %.2f" %
              (written / size, progress['name'],
               self.total_image_count - len(self.remaining_items) + 1,
               self.total_image_count,
               float(self.total_written) / self.total_size))


def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('--keep', action='store_true', default=False,
                        help='keep items in target up to MAX items '
                             'even after they have fallen out of the source')
    parser.add_argument('--max', type=int, default=None,
                        help='store at most MAX items in the target')

    parser.add_argument('--region', action='append', default=None,
                        dest='regions',
                        help='operate on specified region '
                             '[useable multiple times]')

    parser.add_argument('--mirror', action='append', default=[],
                        dest="mirrors",
                        help='additional mirrors to find referenced files')
    parser.add_argument('--path', default=None,
                        help='sync from index or products file in mirror')
    parser.add_argument('--output-dir', metavar="DIR", default=False,
                        help='write image data to storage in dir')
    parser.add_argument('--output-swift', metavar="prefix", default=False,
                        help='write image data to swift under prefix')

    parser.add_argument('--name-prefix', metavar="prefix", default=None,
                        help='prefix for each published image name')
    parser.add_argument('--cloud-name', metavar="name", default=None,
                        required=True, help='unique name for this cloud')
    parser.add_argument('--modify-hook', metavar="cmd", default=None,
                        required=False,
                        help='invoke cmd on each image prior to upload')
    parser.add_argument('--content-id', metavar="name", default=None,
                        required=True,
                        help='content-id to use for published data.'
                             '  may contain "%%(region)s"')

    parser.add_argument('--progress', action='store_true', default=False,
                        help='display per-item download progress')
    parser.add_argument('--verbose', '-v', action='count', default=0)
    parser.add_argument('--log-file', default=sys.stderr,
                        type=argparse.FileType('w'))

    parser.add_argument('--keyring', action='store', default=None,
                        help='The keyring for gpg --keyring')

    parser.add_argument('source_mirror')
    parser.add_argument('item_filters', nargs='*', default=DEFAULT_FILTERS,
                        help="Filter expression for mirrored items. "
                        "Multiple filter arguments can be specified"
                        "and will be combined with logical AND. "
                        "Expressions are key[!]=literal_string "
                        "or key[!]~regexp.")

    parser.add_argument('--hypervisor-mapping', action='store_true',
                        default=False,
                        help="Set hypervisor_type attribute on stored images "
                        "and the virt attribute in the associated stream "
                        "data. This is useful in OpenStack Clouds which use "
                        "multiple hypervisor types with in a single region.")

    args = parser.parse_args()

    modify_hook = None
    if args.modify_hook:
        modify_hook = args.modify_hook.split()

    mirror_config = {'max_items': args.max, 'keep_items': args.keep,
                     'cloud_name': args.cloud_name,
                     'modify_hook': modify_hook,
                     'item_filters': args.item_filters,
                     'hypervisor_mapping': args.hypervisor_mapping}

    (mirror_url, args.path) = util.path_from_mirror_url(args.source_mirror,
                                                        args.path)

    def policy(content, path):  # pylint: disable=W0613
        if args.path.endswith('sjson'):
            return util.read_signed(content, keyring=args.keyring)
        else:
            return content

    smirror = mirrors.UrlMirrorReader(mirror_url, mirrors=args.mirrors,
                                      policy=policy)
    if args.output_dir and args.output_swift:
        error("--output-dir and --output-swift are mutually exclusive\n")
        sys.exit(1)

    level = (log.ERROR, log.INFO, log.DEBUG)[min(args.verbose, 2)]
    log.basicConfig(stream=args.log_file, level=level)

    regions = args.regions
    if regions is None:
        regions = openstack.get_regions(services=['image'])

    for region in regions:
        if args.output_dir:
            outd = os.path.join(args.output_dir, region)
            tstore = objectstores.FileStore(outd)
        elif args.output_swift:
            tstore = swift.SwiftObjectStore(args.output_swift, region=region)
        else:
            sys.stderr.write("not writing data anywhere\n")
            tstore = None

        mirror_config['content_id'] = args.content_id % {'region': region}

        if args.progress:
            drmirror = glance.ItemInfoDryRunMirror(config=mirror_config,
                                                   objectstore=tstore)
            drmirror.sync(smirror, args.path)
            p = StdoutProgressAggregator(drmirror.items)
            progress_callback = p.progress_callback
        else:
            progress_callback = None

        tmirror = glance.GlanceMirror(config=mirror_config,
                                      objectstore=tstore, region=region,
                                      name_prefix=args.name_prefix,
                                      progress_callback=progress_callback)
        tmirror.sync(smirror, args.path)


if __name__ == '__main__':
    main()

# vi: ts=4 expandtab syntax=python
