#!/bin/bash

# THIS FILE IS PART OF THE CYLC SUITE ENGINE.
# Copyright (C) 2008-2019 NIWA & British Crown (Met Office) & Contributors.
#
# 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.
  -e --edit    Open the jobscript in a CLI text editor.
  -g --gedit   Open the jobscript in a GUI text editor.
  --plain      Don't print the "Task Job Script Generated message."
 (see also 'cylc submit --help')

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

editor () {
    python2 -c "
import sys
from cylc.cfgspec.glbl_cfg import glbl_cfg
if sys.argv[1] in ['-g', '--gedit']:
    print glbl_cfg().get(['editors', 'gui'])
elif sys.argv[1] in ['-e', '--edit']:
    print glbl_cfg().get(['editors', 'terminal'])
" $1
}

PLAIN=false
EDITOR_CMD=
SUBMIT_ARGS=
for arg in "${@}"; do
    if [[ "${arg}" == '-h' ]] || [[ "${arg}" == '--help' ]]; then
        usage
        exit 0
    elif [[ "${arg}" == '--edit' ]] || [[ "${arg}" == '--gedit' ]] || \
         [[ "${arg}" == '-e' ]] || [[ "${arg}" == '-g' ]]; then
        EDITOR_CMD="$(editor ${arg})"
    elif [[ "${arg}" == '--plain' ]]; then
        PLAIN=true
    else
        SUBMIT_ARGS="${SUBMIT_ARGS} ${arg}"
    fi
done

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