#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright (C) Bull S.A.S (2010, 2011)
# Contributor: Pierre Vignéras <pierre.vigneras@bull.net>
#
# 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
###############################################################################

"""
Convert sequencer db-based ruleset format to new file-based one.
"""

from sequencer.commons import get_db_connection
from sequencer.dgm.db import SequencerFileDB, SequencerSQLDB
from sequencer.ise.rc import ACTION_RC_OK
from sequencer.tracer import init_trace
import logging
import optparse
import os
import sys

_LOGGER = logging.getLogger(__name__)

__author__ = "Pierre Vigneras"
__copyright__ = "Copyright (c) 2010 Bull S.A.S."
__credits__ = ["Pierre Vigneras"]

def main():
    """
    The main! ;-)
    """
    usage = "%prog [options] host[:port],database,user,password directory"

    doc = """Convert ruleset from the old db-based format to the new
file-based format. The result is produced in the given directory."""

    optparser = optparse.OptionParser(usage, description=doc)
    optparser.disable_interspersed_args()

    optparser.add_option("-v", "--verbose", dest="verbose",
                         action='store_true', default=False,
                         help="Display all levels of trace on output" + \
                             " except DEBUG level.")
    optparser.add_option("-q", "--quiet", dest="quiet",
                         action='store_true', default=False,
                         help="Display only ERROR level messages on output.")
    optparser.add_option("-D", "--Debug", dest="debug",
                         action='store_true', default=False,
                        help="Display all levels of trace on output.")

    (options, args) = optparser.parse_args()

    init_trace(options)

    if len(args) != 2:
        optparser.error("Wrong number of arguments.")

    db_src = None
    try:
        params = args[0].split(',', 4)
        raw_db = get_db_connection(host=params[0],
                                   database=params[1],
                                   user=params[2],
                                   password=params[3])
        db_src = SequencerSQLDB(raw_db)
        basedir = os.path.abspath(args[1])
        db_dst = SequencerFileDB(basedir)
        db_dst.create_table()
        rules_map = db_src.get_rules_map()
        for ruleset in rules_map:
            db_dst.add_rules(rules_map[ruleset].values())


        return ACTION_RC_OK
    finally:
        if db_src is not None:
            db_src.close()

if __name__ == "__main__":
    rc = main()
    sys.exit(int(rc))
