#!/usr/bin/python3
# This script is used to generate the dynamic inventory for the current deployment.
# It does this by parsing the yaml file pushed, and producing a JSON object as
# specified in:
# http://docs.ansible.com/ansible/latest/dev_guide/developing_inventory.html#developing-inventory

# When called with --list the full json object required by the netops deployment
# process is printed to stdout. When called with --host, an empty json object
# is printed as we no longer have any requirement to implement host specific
# data.

# Be the time this script is called, we assuming all of the required
# files for the deployments are in place.
import sys
import getopt
import json
import central_dop.config
import central_dop.nodes
from central_dop.inventory import get_inventory


def usage():
    print("Usage: generate_inventory --list")


def main():
    if len(sys.argv) > 3:
        usage()
        sys.exit(1)

    try:
        optlist, args = getopt.getopt(sys.argv[1:], "", ["list", "host="])
    except getopt.GetoptError as err:
        print((str(err)))
        usage()
        sys.exit(2)

    print_list = False
    print_host = False
    for o, a in optlist:
        if o == "--list":
            print_list = True
        elif o == "--host":
            print_host = True
        else:
            usage()
            sys.exit(1)

    config = central_dop.config.load_config_from_dir("/srv/deploy")
    try:
        central_dop.config.validate_config(config)
    except central_dop.config.Error as err:
        print("error loading configuration: {}".format(err.message))
        sys.exit(1)

    if print_list:
        print((json.dumps(get_inventory(config))))
    elif print_host:
        print({})

    sys.exit(0)


if __name__ == "__main__":
    main()
