#!/usr/bin/env python

# oio-meta1-rebuilder
# Copyright (C) 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
import sys

from oio.rebuilder.meta1_rebuilder import Meta1Rebuilder
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 = "Rebuild meta1 databases by setting 'last_rebuild' " \
            "property in admin table, thus triggering a replication." \
            "And print the failed container IDs."
    parser = argparse.ArgumentParser(description=descr, parents=[log_parser])
    parser.add_argument('namespace', help="Namespace")
    parser.add_argument('--report-interval', type=int,
                        help="Report interval in seconds (3600)")
    parser.add_argument('--workers', type=int,
                        help="Number of workers (1)")
    parser.add_argument('--prefixes-per-second', type=int,
                        help="Max prefixes per second per workers (30)")
    parser.add_argument('-q', '--quiet', action='store_true',
                        help="Don't print log on console")
    ifile_help = "Read container IDs from this file instead of redis. " \
                 "Each line should be formatted like 'container_id'."
    parser.add_argument('--input-file', nargs='?',
                        help=ifile_help)

    return parser


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

    conf = {}
    conf['namespace'] = args.namespace

    if args.log_level is not None:
        conf['log_level'] = args.log_level
    if args.log_syslog_prefix is not None:
        conf['syslog_prefix'] = args.log_syslog_prefix
    else:
        conf['syslog_prefix'] = 'OIO,%s,meta1-rebuilder' % args.namespace
    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.report_interval is not None:
        conf['report_interval'] = args.report_interval
    if args.workers is not None:
        conf['workers'] = args.workers
    if args.prefixes_per_second is not None:
        conf['items_per_second'] = args.prefixes_per_second

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

    success = False
    try:
        meta1_rebuilder = Meta1Rebuilder(conf, logger,
                                         input_file=args.input_file)
        success = meta1_rebuilder.rebuilder_pass()
    except KeyboardInterrupt:
        logger.info('Exiting')
    except Exception as e:
        logger.exception('ERROR in rebuilder: %s' % e)
    if not success:
        sys.exit(1)
