#!/usr/bin/env python

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2017 NIWA
#
# 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/>.

"""gcapture [options] COMMAND
Run a command as a subprocess and capture the resulting stdout and
stderr to display in a dialog. Examples:
    $ capture "echo foo" &

Arguments:
   COMMAND    - the command line to run"""

import os
import sys
from optparse import OptionParser

sys.path.append(
    os.path.dirname(os.path.realpath(os.path.abspath(__file__))) + '/../lib')

from cylc.cfgspec.globalcfg import GLOBAL_CFG
from cylc.gui.gcapture import gcapture, gcapture_tmpfile

# This is a unit test for $CYLC_DIR/lib/cylc/gui/gcapture.py
# but it may be more generally useful.

parser = OptionParser(__doc__)

parser.add_option(
    "--width",
    help="dialog window width in pixels (default 400)",
    metavar='INT', action="store", default=400, dest="width")

parser.add_option(
    "--height",
    help="dialog window height in pixels (default 200)",
    metavar='INT', action="store", default=200, dest="height")

parser.add_option(
    "--file",
    help="(optional) capture stdout and stderr in FILE"
    "(full path, e.g. /path/to/foo/output.txt).",
    metavar='FILE', action="store", default=None, dest="filep")

parser.add_option(
    "--other",
    help="(optional) view the output (--prefix) of another gcapture process.",
    action="store_true", default=False, dest="other")

(options, args) = parser.parse_args()

# import modules that require gtk now, so that a display is not needed
# just to get command help (e.g. when running make on a post-commit hook
# on a remote repository).
import gtk
import gobject

if options.other and not options.filep:
    parser.error('--other requires --prefix')

command = ' '.join(args)

if options.other:
    ignore_command = True
else:
    ignore_command = False

cylc_tmpdir = GLOBAL_CFG.get_tmpdir()

gobject.threads_init()
if options.filep:
    try:
        if ignore_command:
            # open existing file
            stdout = open(options.filep, 'rb')
        else:
            stdout = open(options.filep, 'wb')
    except IOError, x:
        raise SystemExit(x)
    gcapture(command, stdout, width=int(options.width),
             height=int(options.height), standalone=True,
             ignore_command=ignore_command).run()
else:
    gcapture_tmpfile(command, cylc_tmpdir, width=int(options.width),
                     height=int(options.height), standalone=True).run()
gtk.main()
