#!/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 [prep] register [OPTIONS] ARGS

Register the suite definition located in PATH (or $PWD) as REG.

This creates the suite run directory, and authentication files in a
sub-directory called ".service/".

Suite names are the same as the directory path under the suite run directory.
They may contain alphanumeric characters plus '_' '-' and '/'.

Example: if the cylc run directory is $HOME/cylc-run (the default) and
/home/bob/suites/test is a suite source directory, then:

% cylc reg nwp/test1 /home/bob/suites/test

will create the following suite run directory:

/home/bob/cylc-run/nwp/test1
`-- .service
    |-- passphrase
    |-- source -> /home/bob/test
    |-- ssl.cert
    `-- ssl.pem

The suite can subsequently be started and targeted by cylc commands using
"nwp/test1" as the name."""

import sys
from cylc.remote import remrun
if remrun().execute():
    sys.exit(0)

from cylc.option_parsers import CylcOptionParser as COP
from cylc.suite_srv_files_mgr import SuiteSrvFilesManager
import cylc.flags


def main():
    parser = COP(
        __doc__,
        argdoc=[("REG", "Suite name"),
                ("[PATH]", "Suite definition directory (defaults to $PWD)")])
    options, args = parser.parse_args()
    if len(args) == 2:
        SuiteSrvFilesManager().register(args[0], args[1])
        print 'REGISTER %s: %s' % (args[0], args[1])
    else:
        SuiteSrvFilesManager().register(args[0])
        print 'REGISTER %s' % (args[0])


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