#!/usr/bin/env python2

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2019 NIWA & British Crown (Met Office) & Contributors.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

"""cylc gscan [OPTIONS]

This is the cylc scan gui for monitoring running suites on a set of
hosts.

To customize themes copy $CYLC_DIR/etc/gcylc.rc.eg to ~/.cylc/gcylc.rc and
follow the instructions in the file."""

import sys
if "--use-ssh" in sys.argv[1:]:
    sys.argv.remove("--use-ssh")
    from cylc.remote import remrun
    if remrun(forward_x11=True):
        sys.exit(0)

from cylc.option_parsers import CylcOptionParser as COP


def main():
    """Implement "cylc gscan"."""
    parser = COP(
        __doc__,
        comms=True,
        noforce=True,
        argdoc=[(
            "[HOSTS ...]", "Hosts to scan instead of the configured hosts.")])
    parser.add_option(
        "-a", "--all",
        help="Scan all port ranges in known hosts.",
        action="store_true", default=False, dest="all_ports")
    parser.add_option(
        "-n", "--name",
        metavar="PATTERN",
        help="List suites with name matching PATTERN (regular expression). "
             "Defaults to any name. Can be used multiple times.",
        action="append", dest="patterns_name", default=[])
    parser.add_option(
        "-o", "--suite-owner",
        metavar="PATTERN",
        help="List suites with owner matching PATTERN (regular expression). "
             "Defaults to just your own suites. Can be used multiple times.",
        action="append", dest="patterns_owner", default=[])
    parser.add_option(
        "--comms-timeout", metavar="SEC",
        help="Set a timeout for network connections "
             "to each running suite. The default is 5 seconds.",
        action="store", default=None, dest="comms_timeout")
    parser.add_option(
        "--interval",
        help="Time interval (in seconds) between full updates",
        type="int", metavar="SECONDS", dest="interval")
    options, args = parser.parse_args()

    # Only import GTK, etc here, as the command may be called with "--help" in
    # batch mode, which may be unable to import GTK.
    import gtk
    import warnings
    warnings.filterwarnings('ignore', 'use the new', Warning)
    gtk.settings_get_default().set_long_property(
        "gtk-button-images", True, "main")
    gtk.settings_get_default().set_long_property(
        "gtk-menu-images", True, "main")
    from cylc.cfgspec.glbl_cfg import glbl_cfg
    from cylc.gui.gscan import ScanApp

    if options.all_ports:
        args.extend(
            glbl_cfg().get(["suite servers", "scan hosts"]) or ["localhost"])
    scan_app = ScanApp(
        hosts=args,
        patterns_name=options.patterns_name,
        patterns_owner=options.patterns_owner,
        comms_timeout=options.comms_timeout,
        interval=options.interval)
    try:
        gtk.main()
    except KeyboardInterrupt:
        print >> sys.stderr, "Stopping..."
        scan_app.window.destroy()
        raise SystemExit(1)


if __name__ == "__main__":
    main()
