#! /usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2009, Felspar Co Ltd. http://fost.3.felspar.com/
# Distributed under the Boost Software License, Version 1.0.
# See accompanying file LICENSE_1_0.txt or copy at
#     http://www.boost.org/LICENSE_1_0.txt


def main():
    """
        This can be used to handle cases where the middleware is not able to
        perform an automatic update. Simply execute this script and it will
        do any needed database migration and then exit.
    """
    import os, sys
    from django.core.management import setup_environ
    try:
        settings = endmodule(os.environ['DJANGO_SETTINGS_MODULE'])
    except ImportError:
        sys.stderr.write(
                "Error: Can't find the file 'settings.py' in the directory containing %r. \n\
                It appears you've customized things.\n\
                You'll have to run django-admin.py, passing it your settings module.\n\
                (If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
        return 1
    setup_environ(settings)
    from modelsync.resync import check_migration_model, MigrationMisMatch
    check_migration_model(
        settings.DATABASE_HOST, settings.DATABASE_NAME, settings.DATABASE_USER, settings.DATABASE_PASSWORD
    )
    return 0


def endmodule(module_name):
    module = __import__(module_name)
    module_path = module_name.split('.')
    if module_path:
        for m in module_path[1:]:
            module = getattr(module, m)
    return module

if __name__ == "__main__":
    import sys
    sys.exit(main() or 0)
