#!/usr/bin/env python3
# Copyright 2014, Rob Lyon <nosignsoflifehere@gmail.com>
#
# 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.

import sys
from optparse import OptionParser
import qhost
from qhost.constants import VERSION


def get_options():
    usage = "usage: %prog [options] [optional-node-regex]"
    parser = OptionParser(usage=usage)
    parser.add_option(
        "-c",
        "--color",
        action="store_true",
        dest="color",
        default=False,
        help="turn on colorized output",
    )
    parser.add_option(
        "-j",
        "--jobs",
        action="store_true",
        dest="jobs",
        default=False,
        help="show job information",
    )
    parser.add_option(
        "-J",
        "--jobid",
        dest="jobid",
        default=None,
        help="Only show nodes used by the specified job ID.",
    )
    parser.add_option(
        "-n",
        "--ntype",
        action="store_true",
        dest="ntype",
        default=False,
        help="show node type information",
    )
    parser.add_option(
        "-p",
        "--properties",
        action="store_true",
        dest="properties",
        default=False,
        help="show node properties",
    )
    parser.add_option(
        "-a",
        "--all",
        action="store_true",
        dest="all",
        default=False,
        help="show jobs, node properties, notes, and type",
    )
    parser.add_option(
        "-N",
        "--notes",
        action="store_true",
        dest="notes",
        default=False,
        help="show node notes",
    )
    parser.add_option(
        "-v",
        "--version",
        action="store_true",
        dest="version",
        default=False,
        help="Print version and exit.",
    )
    parser.add_option(
        "-s",
        "--state",
        dest="state",
        default=None,
        help="Filter nodes by state. Valid state characters are F (free), "
        + "O (offline), D (down), R (reserve), E (job-exclusive), "
        + "S (job-sharing), B (busy), T (time-shared), and "
        + "U (state-unknown).",
    )
    parser.add_option(
        "-x",
        "--exclusive",
        action="store_true",
        dest="exclusive",
        default=False,
        help="When specifying the state, use exclusive matching.",
    )
    parser.add_option(
        "-X",
        "--xmlfile",
        dest="xmlfile",
        default=None,
        help="Use an XML file containing the pbsnodes output instead of " +
        "pbsnodes.",
    )

    (options, args) = parser.parse_args()

    if options.version:
        print(f"qhost version {VERSION}")
        sys.exit(0)

    if options.all:
        options.jobs = True
        options.properties = True
        options.ntype = True
        options.notes = True

    if len(args) > 0:
        options.node_regex = args[0]
    else:
        options.node_regex = None

    return options


def run(options):
    if options.xmlfile is None:
        pbsnodes = qhost.Pbsnodes("pbsnodes")
        xml = pbsnodes.execute()
        if xml is None:
            print(pbsnodes.error())
            sys.exit(1)
    else:
        try:
            xml = open(options.xmlfile, "r").read()
        except IOError as e:
            print(e)
            sys.exit(1)

    qp = qhost.Parser(xml)
    nodelist = qp.parse()
    if options.exclusive:
        nodelist.add_filter("exclusive_state", options.state)
    else:
        nodelist.add_filter("any_state", options.state)
    nodelist.add_filter("node_regex", options.node_regex)
    nodelist.add_filter("jobid", options.jobid)

    display = qhost.Display(
        color=options.color,
        showjobs=options.jobs,
        showprops=options.properties,
        showtype=options.ntype,
        shownote=options.notes,
    )
    display.list(nodelist)


def main():
    run(get_options())


if __name__ == "__main__":
    main()
