#!/usr/bin/env python
""" 
A plugin extendable hostlist infrastructure, command line
utility.

This utility provides functions for getting a list of hosts
from various systems as well as compressing the list into
a simplified list.

This module uses the hostlists_plugins python scripts
to actually obtain the listings.  
"""

from __future__ import print_function

# noinspection PyStatementEffect
"""
 Copyright (c) 2010 Yahoo! Inc. All rights reserved.
 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. See accompanying LICENSE file.
"""
import hostlists
import optparse
import sys


if __name__ == "__main__":
    parser = optparse.OptionParser(
        usage="usage: %prog [options] plugin:parameters"
    )
    parser.add_option(
        "-s", "--sep",
        dest="sep",
        default=',',
        help="Separator character, default=\",\""
    )
    parser.add_option(
        "--onepass",
        dest="onepass",
        default=False,
        action="store_true",
        help="Only perform a single expansion pass (no recursion)"
    )
    parser.add_option(
        "--expand", "-e",
        dest="expand",
        default=False,
        action="store_true",
        help="Expand the host list and display one host per line"
    )
    parser.add_option(
        "--list_plugins",
        dest="list_plugins",
        default=False,
        action="store_true",
        help="List the currently found hostlists plugins"
    )
    (options, args) = parser.parse_args()
    if options.list_plugins:
        plugins = hostlists.installed_plugins()
        plugins.sort()
        print(
            'Hostlists plugins currently installed are:'
        )
        print('\t'+'\n\t'.join(plugins))
        sys.exit(0)

    hostnames = hostlists.range_split(','.join(args))
    if options.expand:
        print('\n'.join(hostlists.expand(hostnames, onepass=options.onepass)))
    else:
        print(
            ', '.join(
                hostlists.compress(
                    hostlists.expand(
                        hostnames, onepass=options.onepass
                    )
                )
            )
        )
