#!/usr/bin/env python

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2016 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/>.
"""cylc [task] message [OPTIONS] MESSAGE ...

This command is part of the cylc task messaging interface, used by
running tasks to communicate progress to their parent suite.

The message command can be used to report "message outputs" completed.
Other messages received by the suite daemon will just be logged.

Suite and task identity are determined from the task execution
environment supplied by the suite (or by the single task 'submit'
command, in which case case the message is just printed to stdout)."""


import os
import sys
from optparse import OptionParser
import cylc.flags
from cylc.task_message import TaskMessage


def main():
    """CLI."""
    parser = OptionParser(__doc__)

    parser.add_option(
        "-p", "--priority", metavar="PRIORITY", type="choice",
        choices=['NORMAL', 'WARNING', 'CRITICAL'],
        help="message priority: NORMAL, WARNING, or CRITICAL; default NORMAL.",
        action="store", dest="priority", default="NORMAL")

    parser.add_option(
        "-v", "--verbose", help="Verbose output mode.", action="store_true",
        default=False, dest="verbose")

    options, args = parser.parse_args()
    if not args:
        parser.error("No task message supplied")

    task_message = TaskMessage(priority=options.priority)
    if (task_message.env_map.get('CYLC_VERBOSE') in ["True", "true"] or
            options.verbose):
        cylc.flags.verbose = True

    if task_message.env_map.get('CYLC_DEBUG') in ["True", "true"]:
        cylc.flags.debug = True

    try:
        task_message.send(args)
    except Exception, exc:
        print >> sys.stderr, 'ERROR: task messaging failure.'
        if cylc.flags.debug:
            import traceback
            traceback.print_exc(exc)
        raise SystemExit(exc)


if __name__ == "__main__":
    main()
