#!/usr/bin/env python

# oio-blob-registrator.py
# Copyright (C) 2015-2018 OpenIO SAS, as part of OpenIO SDS
#
# This program 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.
#
# This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

import argparse

from oio.blob.registrator import BlobRegistratorWorker
from oio.common.utils import get_logger


def make_arg_parser():
    log_parser = argparse.ArgumentParser(add_help=False)
    levels = ['DEBUG', 'INFO', 'WARN', 'ERROR']
    log_parser.add_argument('--log-level', choices=levels,
                            help="Log level")
    log_parser.add_argument('--log-syslog-prefix',
                            help="Syslog prefix")
    log_parser.add_argument('--log-facility',
                            help="Log facility")
    log_parser.add_argument('--log-address',
                            help="Log address")

    descr = "Especially for my favorite customer! " + \
            "The script runs the chunks on the given rawx volume and " + \
            "it registers them in their container."
    parser = argparse.ArgumentParser(description=descr, parents=[log_parser])
    parser.add_argument('namespace', help="Namespace")
    parser.add_argument('volume', help="The volume id to rebuild")
    parser.add_argument('-q', '--quiet', action='store_true',
                        help="Don't print log on console")
    parser.add_argument('--first', default=False, action='store_true',
                        help="Also work on a chunk if it is the first in " + \
                             "its metachunk")
    parser.add_argument('--lock', action='store_true',
                        help="Protect the run with an xattr-lock on the " + \
                             "volume")
    parser.add_argument('--report-interval', type=int,
                        help="Report interval in seconds (3600)")
    parser.add_argument('--update', default=False, action='store_true',
                        help="Should the script update the meta2 with " + \
                             "the xattr. Mutually exclusive with --insert")
    parser.add_argument('--insert', default=False, action='store_true',
                        help="Should the script insert the chunkks in " + \
                             "the container, without overriding the " + \
                             "chunks in place. Mutually exclusive with" + \
                             "--update, with a greater priority.")
    parser.add_argument('--check', default=False, action='store_true',
                        help="Default acction when neither --insert nor " + \
                             "--update are specified (it overrides both)." + \
                             " Only query the meta2 to check for the " + \
                             "presence of the chunks in the volume.")

    return parser


if __name__ == '__main__':
    args = make_arg_parser().parse_args()

    conf = {}
    if args.log_level is not None:
        conf['log_level'] = args.log_level
    if args.log_facility is not None:
        conf['log_facility'] = args.log_facility
    if args.log_address is not None:
        conf['log_address'] = args.log_address
    if args.log_syslog_prefix is not None:
        conf['syslog_prefix'] = args.log_syslog_prefix
    else:
        conf['syslog_prefix'] = 'OIO,%s,blob-registrator,%s' % \
            (args.namespace, args.volume)

    conf['namespace'] = args.namespace
    conf['first'] = args.first

    if args.insert:
        conf['action'] = 'insert'
    elif args.update:
        conf['action'] = 'update'
    else:
        conf['action'] = 'check'

    if args.report_interval is not None:
        conf['report_interval'] = args.report_interval

    logger = get_logger(conf, None, not args.quiet)

    try:
        worker = BlobRegistratorWorker(conf, logger, args.volume)
        if args.lock:
            worker.pass_with_lock()
        else:
            worker.pass_without_lock()
    except Exception as e:
        logger.exception('ERROR in registrator: %s' % e)

