#! /usr/bin/python
#
# Copyright (C) 2012 Canonical Ltd.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3, as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranties of
# MERCHANTABILITY, SATISFACTORY QUALITY, 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/>.
#
# In addition, as a special exception, the copyright holders give
# permission to link the code of portions of this program with the
# OpenSSL library under certain conditions as described in each
# individual source file, and distribute linked combinations
# including the two.
# You must obey the GNU General Public License in all respects
# for all of the code used other than OpenSSL.  If you modify
# file(s) with this exception, you may extend this exception to your
# version of the file(s), but you are not obligated to do so.  If you
# do not wish to do so, delete this exception statement from your
# version.  If you delete this exception statement from all source
# files in the program, then also delete it here.
"""A script that checks for unintended imports of twisted.internet.reactor."""

# NOTE: the goal of this script is to avoid a bug that affects
# ubuntuone-control-panel on windows and darwin. Those platforms use
# the qt4reactor, and will break if the default reactor is installed
# first. This can happen if a module used by control-panel (such as
# ubuntuone.platform.credentials), imports reactor.  Only sub-modules
# that are not used by ubuntuone-control-panel can safely import
# reactor at module-level.

from __future__ import (unicode_literals, print_function)

import __builtin__

import os
import sys
import traceback

sys.path.append(os.path.abspath(os.getcwd()))


def fake_import(*args, **kwargs):
    """A wrapper for __import__ that dies when importing reactor."""
    imp_name_base = args[0]

    if len(args) == 4 and args[3] is not None:
        imp_names = ["{0}.{1}".format(imp_name_base, sm)
                     for sm in args[3]]
    else:
        imp_names = [imp_name_base]

    for imp_name in imp_names:
        if 'twisted.internet.reactor' == imp_name:
            print("ERROR: should not import reactor here:")
            traceback.print_stack()
            sys.exit(1)

    r = real_import(*args, **kwargs)
    return r


if __name__ == '__main__':

    real_import = __builtin__.__import__
    __builtin__.__import__ = fake_import

    subs = ["", ".tools", ".logger", ".credentials"]
    for module in ["ubuntuone.platform" + p for p in subs]:
        m = __import__(module)
