#!/usr/bin/env python
# Version 1.3-1
import sys
import optparse
from nodes import Hierarchy, NodesException

# MAIN

op = optparse.OptionParser(usage="usage: %prog [OPTION]... NODESPEC")
op.add_option("--to-nodes",
              action="store_true", 
              help="convert NODESPEC to nodes (default)")
op.add_option("-u", "--up",
              action="store",
              metavar="GROUP",
              help="list groups where any node in NODESPEC is a member")
op.add_option("-f", "--fill",
              action="store",
              metavar="GROUP",
              help="as --up, but then convert to nodes")
op.add_option("-g", "--gather",
              action="store",
              metavar="GROUP",
              help="list groups whose members are all in NODESPEC plus the individual nodes that are left over")
op.add_option("-s", "--slurm",
              action="store_true", 
              help="create dynamic groups for SLURM jobs and users")
op.add_option("--config-file",
              action="store",
              default="/etc/nodes.conf",
              metavar="FILE",
              help="use FILE instead of /etc/nodes.conf")

(opts, args) = op.parse_args()

h = Hierarchy()
try:
    h.parse_file(opts.config_file)
except NodesException, e:
    print
    sys.stderr.write("Config file error: %s\n" % e.msg)
    sys.exit(1)

if opts.slurm:
    try:
        h.parse_slurm()
    except NodesException, e:
        print
        sys.stderr.write("SLURM error: %s\n" % e.msg)
        sys.exit(1)

if len(args) <> 1:
    sys.exit("Error: You need to provide a single node specifier!\n")
    sys.exit(1)
else:
    arg = args[0]

modes_chosen = int(opts.to_nodes is not None) + \
    int(opts.up is not None) + \
    int(opts.fill is not None) + \
    int(opts.gather is not None)

if modes_chosen > 1:
    sys.exit("Error: You cannot choose more than one mode at a time!\n")
    sys.exit(1)
elif modes_chosen == 0 or opts.to_nodes:
    func = lambda a: h.expand(a)
else:
    if opts.up:
        func = lambda arg: h.up(opts.up, arg)
    elif opts.fill:
        func = lambda arg: h.fill(opts.fill, arg)
    elif opts.gather:
        func = lambda arg: h.gather(opts.gather, arg)

try:
    res = func(arg)
    print res
except NodesException, e:
    print
    sys.stderr.write("Error: %s\n" % e.msg)
    sys.exit(1)

