#!/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 [control] reset [OPTIONS] ARGS

Force one or more task proxies in a running suite to change state and modify
their prerequisites and outputs accordingly.  For example, --state=waiting
means "prerequisites not satisfied, outputs not completed"; --state=ready means
"prerequisites satisfied, outputs not completed" (this generally has the same
effect as using the "cylc trigger" command).

"cylc reset --state=spawn" is deprecated: use "cylc spawn" instead.

See the documentation for the -s/--state option for legal reset states."""

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

import cylc.flags
from cylc.prompt import prompt
from cylc.network.suite_command import SuiteCommandClient
from cylc.option_parsers import CylcOptionParser as COP
from cylc.task_state import TASK_STATUSES_CAN_RESET_TO


def main():
    parser = COP(
        __doc__, pyro=True, multitask=True,
        argdoc=[
            ('REG', 'Suite name'),
            ('[TASKID ...]', 'Task identifiers')])

    parser.add_option(
        "-s", "--state", metavar="STATE",
        help="Reset task state to STATE, can be %s" % (
            ', '.join(TASK_STATUSES_CAN_RESET_TO)),
        action="store", default=None, dest="state")

    options, args = parser.parse_args()

    suite = args.pop(0)

    if options.state == "spawn":
        # Back compat.
        sys.stderr.write(
            "'cylc reset -s spawn' is deprecated; calling 'cylc spawn'\n")
        cmd = sys.argv[0].replace('reset', 'spawn')
        try:
            os.execvp(cmd, [cmd] + args)
        except OSError, exc:
            if exc.filename is None:
                exc.filename = cmd
            raise SystemExit(exc)

    if options.state not in TASK_STATUSES_CAN_RESET_TO:
        parser.error("Illegal STATE value: " + options.state)

    prompt('Reset task(s) %s in %s' % (args, suite), options.force)
    pclient = SuiteCommandClient(
        suite, options.owner, options.host, options.pyro_timeout,
        options.port, options.db, my_uuid=options.set_uuid,
        print_uuid=options.print_uuid)
    items, compat = parser.parse_multitask_compat(options, args)
    pclient.put_command('reset_task_state', items, compat, options.state)


if __name__ == "__main__":
    try:
        main()
    except Exception as exc:
        if cylc.flags.debug:
            raise
        sys.exit(str(exc))
