#!/usr/bin/python3
# Copyright (C) 2014  ABRT Team
# Copyright (C) 2014  Red Hat, Inc.
#
# This file is part of faf.
#
# faf 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.
#
# faf 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 faf.  If not, see <http://www.gnu.org/licenses/>.


import inspect
import os
import argparse
import logging
from alembic.config import Config
from alembic import command
from argcomplete import autocomplete
from pyfaf.common import get_connect_string
from pyfaf.storage import getDatabase, GenericTable, migrations


parser = argparse.ArgumentParser(description="Migrate FAF database.")
parser.add_argument("--revision", default="head",
                    help="Revision specification. Default: head")

parser.add_argument("--stamp-only", action="store_true",
                    help="Don't run any migrations, only stamp the database to"
                         " indicate it is up-to-date.")

parser.add_argument("--create-all", action="store_true",
                    help="Create all tables without running migrations. "
                         "Please run --stamp-only afterwards.")

parser.add_argument("--sql", action="store_true",
                    help="Print sql instead of executing it.")

parser.add_argument("--downgrade",
                    help="Downgrade to a previous version.")

autocomplete(parser)
args = parser.parse_args()

logging.basicConfig()
alembic_cfg = Config()
alembic_cfg.set_main_option("script_location",
                            os.path.dirname(inspect.getfile(migrations)))
alembic_cfg.set_main_option("sqlalchemy.url", get_connect_string())

if args.create_all:
    db = getDatabase()
    GenericTable.metadata.create_all()
elif args.stamp_only:
    command.stamp(alembic_cfg, "head", sql=args.sql)
elif args.downgrade:
    command.downgrade(alembic_cfg, args.downgrade, sql=args.sql)
else:
    command.upgrade(alembic_cfg, args.revision, sql=args.sql)
