#!/bin/bash

# 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/>.

set -e

usage() {
    cat <<__END__
Usage: cylc [prep] jobscript [OPTIONS] REG TASK

Generate a task job script and print it to stdout.

Here's how to capture the script in the vim editor:
  % cylc jobscript REG TASK | vim -
Emacs unfortunately cannot read from stdin:
  % cylc jobscript REG TASK > tmp.sh; emacs tmp.sh

This command wraps 'cylc [control] submit --dry-run'.
Other options (e.g. for suite host and owner) are passed
through to the submit command.

Options:
  -h,--help   - print this usage message.
 (see also 'cylc submit --help')

Arguments:
  REG         - Registered suite name.
  TASK        - Task ID (NAME.CYCLE_POINT)
__END__
}

for arg in "${@}"; do
    if [[ "${arg}" == '-h' ]] || [[ "${arg}" == '--help' ]]; then
        usage
        exit 0
    fi
done

if CYLC_SUBMIT_OUT="$(cylc submit --dry-run "${@}")"; then
    JOBSCRIPT="$(sed -n 's/^JOB SCRIPT=//p' <<<"${CYLC_SUBMIT_OUT}")"
    echo "Task Job Script Generated: ${JOBSCRIPT}" >&2
    exec less "${JOBSCRIPT}"
else
    echo "${CYLC_SUBMIT_OUT}" >&2
    echo "ERROR: no jobscript generated" >&2
    exit 1
fi
