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

Change the suite runahead limit in a running suite. This is the number of
hours that the fastest task is allowed to get ahead of the slowest. If a
task spawns beyond that limit it will be held back from running until the
slowest tasks catch up enough. WARNING: if you omit HOURS no runahead
limit will be set - DO NOT DO THIS for for any cycling suite that has
no near stop cycle set and is not constrained by clock-trigger tasks."""

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.option_parsers import CylcOptionParser as COP
from cylc.network.suite_command_client import SuiteCommandClient


def main():
    parser = COP(
        __doc__, comms=True,
        argdoc=[('REG', 'Suite name'),
                ('[HOURS]', 'Runahead limit (default: no limit)')])

    (options, args) = parser.parse_args()
    suite = args[0]

    runahead = None
    if len(args) == 2:
        runahead = args[1]

    pclient = SuiteCommandClient(
        suite, options.owner, options.host, options.port,
        options.comms_timeout, my_uuid=options.set_uuid,
        print_uuid=options.print_uuid)

    if runahead:
        prompt('Change runahead limit in %s to %s' % (suite, runahead),
               options.force)
        pclient.put_command('set_runahead', interval=runahead)
    else:
        # no limit!
        prompt('Change runahead limit in %s to NO LIMIT' % suite,
               options.force)
        pclient.put_command('set_runahead')


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