#!/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 upgrade-db

Upgrade a pre-cylc-5.4 suite name database to the new cylc-5.4+ format.
This will create a new-format DB if necessary, or if one already exists
it will transfer old registrations to the new DB so long as the suite
names do not conflict. It is safe to run this utility multiple times.

Prior to cylc-5.4 the suite name registration DB was a Python pickle
file stored at $HOME/.cylc/DB.  Since cylc-5.4 it is a directory
$HOME/.cylc/REGDB/ containing one file per registered suite. The
filenames are the suite names, and the file contains key=value pairs:
  shell$ cat $HOME/.cylc/REGDB/my.suite
  title=my suite title
  path=/path/to/my/suite/"""

import sys
import os
from optparse import OptionParser
import pickle

import cylc.flags
from cylc.registration import RegistrationDB, RegistrationError


def main():

    oldpath = os.path.join(os.environ['HOME'], '.cylc', 'DB')
    newpath = os.path.join(os.environ['HOME'], '.cylc', 'REGDB')

    parser = OptionParser(__doc__)

    parser.add_option(
        "--from",
        help="Path to pre-cylc-5.4 db; default:" + oldpath,
        metavar="PATH", action="store", default=oldpath)

    parser.add_option(
        "--to", help="Path to new cylc-5.4+ db; default:" + newpath,
        metavar="PATH", action="store", default=newpath)

    (options, args) = parser.parse_args()

    if not os.path.isfile(oldpath):
        sys.exit("ERROR, old DB not found: " + oldpath)

    # load old DB
    olditems = pickle.load(open(oldpath, 'r'))

    # new db
    db = RegistrationDB(newpath)
    for suite, (dir, title) in olditems.items():
        try:
            db.register(suite, dir)
        except RegistrationError, x:
            print >> sys.stderr, x


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