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

Remove one or more suites from your suite database. The REGEX pattern
must match whole suite names to avoid accidental de-registration of
partial matches (e.g. 'bar.baz' will not match 'foo.bar.baz').

Associated suite definition directories will not be deleted unless the
'-d,--delete' option is used."""

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

import os
from shutil import rmtree
from cylc.option_parsers import CylcOptionParser as COP
from cylc.registration import RegistrationDB
import cylc.flags


def main():
    parser = COP(
        __doc__,
        argdoc=[('REGEX', 'Regular expression to match suite names.')])

    parser.add_option(
        "-d", "--delete",
        help="Delete the suite definition directory too (!DANGEROUS!).",
        action="store_true", default=False, dest="obliterate")

    parser.add_option(
        "-f", "--force",
        help="Don't ask for confirmation before deleting suite definitions.",
        action="store_true", default=False, dest="force")

    (options, args) = parser.parse_args()

    db = RegistrationDB(options.db)

    unregistered_set, skipped_set = db.unregister(args[0])

    print '%d suite(s) unregistered.' % len(unregistered_set)
    if not unregistered_set or not options.obliterate:
        sys.exit(bool(skipped_set))

    for _, path in sorted(unregistered_set):
        if not options.force:
            response = raw_input('REALLY DELETE "%s"? (y/n/a) ' % (path))
            if response == 'a':
                options.force = True
            elif response != 'y':
                continue
        print 'DELETE "%s"' % (path)
        try:
            rmtree(path)
        except OSError as exc:
            print >> sys.stderr, (
                "ERROR, could not remove directory: " + path)
            print >> sys.stderr, str(exc)
            continue
    sys.exit(bool(skipped_set))

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