#!/usr/bin/python

import argparse
import sys

import mirrormanager2.lib


parser = argparse.ArgumentParser(usage=sys.argv[0] + " [options]",
                                 formatter_class=argparse.RawTextHelpFormatter)
parser.add_argument(
    "-c", "--config",
    dest="config", default='/etc/mirrormanager/mirrormanager2.cfg',
    help="Configuration file to use")

parser.add_argument(
    "-f", "--fraction",
    dest="fraction", default="1:1",
    help='''Specify which part of the mirror range should be returned
1:1 - all mirrors
1:2 - the first half of the mirrors
2:3 - the middle third of the mirrors''')

options = parser.parse_args()

config = dict()
with open(options.config) as config_file:
    exec(compile(config_file.read(), options.config, 'exec'), config)

if ':' not in options.fraction:
    parser.print_help()
    sys.exit(0)

session = mirrormanager2.lib.create_session(config['DB_URL'])

# Get all active mirrors
hosts = mirrormanager2.lib.get_mirrors(session, private=False,
    admin_active=True, user_active=True, site_private=False,
    site_user_active=True, site_admin_active=True)

# only the ids
hosts = [ host.id for host in hosts ]

session.close()

hosts.sort()

total = int(options.fraction.split(':')[1])
part = int(options.fraction.split(':')[0])

start = (part-1)*(len(hosts)/total)
stop = (len(hosts)/total)*part

if total == part:
    print "--startid=%d" % (hosts[start])
else:
    print "--startid=%d --stopid=%d" % (hosts[start], hosts[stop])
