#!/usr/bin/env python
# Copyright 2016-2020 CERN for the benefit of the ATLAS collaboration.
#
# 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.
#
# Authors:
# - Martin Barisits <martin.barisits@cern.ch>, 2016-2018
# - Vincent Garonne <vincent.garonne@cern.ch>, 2018
# - Tomas Javurek <tomas.javurek@cern.ch>, 2018
# - Hannes Hansen <hannes.jakob.hansen@cern.ch>, 2018
# - Benedikt Ziemons <benedikt.ziemons@cern.ch>, 2020
#
# PY3K COMPATIBLE

"""
BB8 is a daemon to rebalance data.
"""

import argparse

from rucio.daemons.bb8.common import rebalance_rse


def get_parser():
    """
    Returns the argparse parser.
    """
    parser = argparse.ArgumentParser(description='The BB8 daemon is responsible for rebalancing data between RSEs.')
    parser.add_argument('rse', action='store', help='RSE to rebalance')
    parser.add_argument('bytes', action='store', type=int, help='Number of bytes to rebalance')
    parser.add_argument('--dry-run', action='store_true', default=False, help='Only run in dry-run mode')
    parser.add_argument('--exclude-expression', action='store', help='Exclude these rse_expression from being destinations')
    parser.add_argument('--comment', action='store', help='Add a comment to the new rules')
    parser.add_argument('--force-expression', action='store', help='For this rse_expression for rebalanced rules instead of letting BB8 decide')
    parser.add_argument('--decommission', action='store_true', help='Run BB8 in decommission mode')
    parser.add_argument('--priority', action='store', help='Priority for the newly created rules', type=int, default=3)
    parser.add_argument('--source-replica-expression', action='store', help='Source replica expression for the newly created rules')
    return parser


if __name__ == "__main__":
    parser = get_parser()
    args = parser.parse_args()

    if args.decommission:
        rebalance_rse(rse_id=args.rse, max_bytes=args.bytes, dry_run=args.dry_run,
                      comment=args.comment, force_expression=args.force_expression,
                      priority=args.priority,
                      source_replica_expression=args.source_replica_expression,
                      mode='decommission')
    else:
        rebalance_rse(rse_id=args.rse, max_bytes=args.bytes, dry_run=args.dry_run,
                      comment=args.comment, force_expression=args.force_expression,
                      priority=args.priority,
                      source_replica_expression=args.source_replica_expression)
