#!/usr/bin/python
# -*- coding: utf-8 -*-

"""
Library to work with plug-ins
"""

import os
from ConfigParser import ConfigParser
import glob
import shutil

from const import CACHE_CPNAME, UNKNOWN_CP_NAME, UNKNOWN_CP_IMPORT
from cpapiexceptions import PluginImportError


CLSYSCONFIG = '/etc/sysconfig/cloudlinux'
clsysconfig = ConfigParser()
clsysconfig.read(CLSYSCONFIG)

CONTROLPANELNAME_VAR = '__cpname__'
DETECTFUNCNAME_VAR = 'detect'


PLUGINS_DIR = None
if clsysconfig.has_option(section='cpapi', option='plugindir'):
    PLUGINS_DIR = clsysconfig.get(section='cpapi', option='plugindir')
API_LINK_PATH = os.path.join(os.path.dirname(__file__), 'apilink.py')



def detectplugin(plugin_pack):
    """
    Scan directory for the presence of plugins.
    Plugin is considered a file with the extension "py", and with a non-empty variable "__cpname__" inside
    (the name of the control panel).  Also in the file must be a function "detect" which returns True in the case of
    the presence of the control panel.

    >>> detectplugin('plugins')
    ('from .plugins import cpanel as api', 'cPanel')

    :param plugin_pack: package name or the name of the plug-ins directory
                       ('cache' - cache plugins users; 'plugins' - officially supported plug-ins)
    :rtype: tuple
    :return: a pair of values​​: (line to import the package, the name of the control panel)
    """
    plugin_dir = os.path.join(os.path.dirname(__file__), plugin_pack)
    modules = [os.path.splitext(os.path.basename(py_full_path))[0] for py_full_path in glob.glob(os.path.join(plugin_dir, '*.py'))]

    for mod_name in modules:
        if mod_name == '__init__':
            continue
        api = None
        import_string = 'from %s import %s as api' % (plugin_pack, mod_name)
        try:
            exec(import_string)
        except:
            raise PluginImportError('Can not import %s plugin' % (mod_name,))
        controlpanelname = getattr(api, CONTROLPANELNAME_VAR, None)
        if controlpanelname:
            detect_func = getattr(api, DETECTFUNCNAME_VAR, None)
            if detect_func and detect_func():
                return import_string, controlpanelname
    return None, None


def rebuild_cache(pludins_dir=PLUGINS_DIR):

    CACHE_DIR = 'cache'
    PLUGINS_PATH = 'plugins'  # directory with official supported plugins

    cache_dir = os.path.join(os.path.dirname(__file__), CACHE_DIR)
    # delete all in cache dir
    shutil.rmtree(cache_dir)
    if pludins_dir and os.path.isdir(pludins_dir):
        # copy all from plugins dir to cache
        shutil.copytree(pludins_dir, cache_dir)
    else:
        os.mkdir(cache_dir)
    os.chmod(cache_dir, 0755)

    # create (or rewrite) __init__.py an empty file
    init_path = os.path.join(cache_dir, '__init__.py')
    open(init_path, 'w').close()

    try:
        import_string, cpname = detectplugin(CACHE_DIR)
    except PluginImportError, e:
        import_string, cpname = None, None
        print('WARNING:' + str(e))
    if cpname is None:
        shutil.rmtree(cache_dir)
        os.mkdir(cache_dir)
        open(init_path, 'w').close()
        import_string, cpname = detectplugin(PLUGINS_PATH)
    if cpname is None:
        import_string, cpname = (UNKNOWN_CP_IMPORT, UNKNOWN_CP_NAME)
        print('WARNING: can not detect control panel; the control panel is set to "%s" ' % cpname)
    # write control panel name to cache file
    if cpname:
        # write control panel name to /var/cache/controlpanelname
        cpname_cache = open(CACHE_CPNAME, 'w')
        cpname_cache.write(cpname)
        cpname_cache.close()

        # write import string (for example 'from .plugins import nopanel as api' for fast loading plugin)
        api_link_stream = open(API_LINK_PATH, 'w')
        api_link_stream.write(import_string + '\n')
        api_link_stream.close()
