#!/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/>.
"""cylc [task] message [OPTIONS] MESSAGE ...

This command is used by task jobs to automatically report success and failure.

It can also be used to send info-, warning-, or critical-priority messages
back, and to report registered task "message outputs" completed.

Note: to abort a job script with a custom error message, use cylc__job_abort:
  cylc__job_abort 'message...'
(for technical reasons this is a shell function, not a cylc sub-command)."""


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()
