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

Register the suite definition located in PATH as REG.

Suite names are hierarchical, delimited by '.' (foo.bar.baz); they
may contain letters, digits, underscore, and hyphens. Colons are not
allowed because directory paths incorporating the suite name are
sometimes needed in PATH variables.

EXAMPLES:

For suite definition directories /home/bob/(one,two,three,four):

% cylc db reg bob         /home/bob/one
% cylc db reg foo.bag     /home/bob/two
% cylc db reg foo.bar.baz /home/bob/three
% cylc db reg foo.bar.waz /home/bob/four

% cylc db pr '^foo'             # print in flat form
  bob         | 'Test Suite One'   | /home/bob/one
  foo.bag     | 'Test Suite Two'   | /home/bob/two
  foo.bar.baz | 'Test Suite Four'  | /home/bob/three
  foo.bar.waz | 'Test Suite Three' | /home/bob/four

% cylc db pr -t '^foo'          # print in tree form
  bob        'Test Suite One'   | /home/bob/one
  foo
   |-bag     'Test Suite Two'   | /home/bob/two
   `-bar
     |-baz   'Test Suite Three' | /home/bob/three
     `-waz   'Test Suite Four'  | /home/bob/four"""

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

import os

from cylc.option_parsers import CylcOptionParser as COP
from cylc.registration import RegistrationDB
import cylc.flags


def main():
    parser = COP(
        __doc__,
        argdoc=[("REG", "Suite name"),
                ("PATH", "Suite definition directory")])

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

    if args[1].endswith('suite.rc'):
        suiterc = args[1]
        rdir = os.path.dirname(suiterc)
    else:
        rdir = args[1]
        suiterc = os.path.join(rdir, 'suite.rc')

    db = RegistrationDB(options.db)
    db.register(suite, rdir)


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