# encoding: utf-8

import os

from libsvn import repos

from trac.perm import IPermissionRequestor
from trac.web.chrome import ITemplateProvider
from trac.admin import IAdminPanelProvider
from trac.core import *
from trac.config import Option
from trac.util.translation import _
from trac.admin.console import run

class TraMAdminModule(Component):
    implements(IAdminPanelProvider, ITemplateProvider)
    repository_type = Option('trac', 'repository_type', 'svn',
        """リポジトリの種類を指定します。(''0.10 以降'')""")
    repository_dir = Option('trac', 'repository_dir', '',
        """ローカルリポジトリへのパスを指定します。相対パスを使用できます
        (''0.11 以降'')。""")
    inherit_config = Option('tram', 'inherit.file', None,
        """設定を継承するtrac.iniファイルを指定します""")

    def get_admin_panels(self, req):
        if 'TRAC_ADMIN' in req.perm:
            yield ('general', u'一般設定', 'create_project', u'プロジェクト作成')

    def render_admin_panel(self, req, cat, page, path_info):
        if req.method == 'POST':
            if req.args.get('projname'):
                trac_env = req.environ.get('trac.env_parent_dir') + "/" + req.args.get('projname')
                svn_env = ""
                if self.repository_dir != "":
                    head, tail = os.path.split(self.repository_dir)
                    svn_env = head + "\\" + req.args.get('projname')
                    repos.svn_repos_create(svn_env, None,None,None,None)

                if self.inherit_config != None:
                    run([trac_env.encode('ascii'),"initenv", '--inherit=' + self.inherit_config ,req.args.get('projname'),"sqlite:db/trac.db", "svn", svn_env])
                    run([trac_env.encode('ascii'),"upgrade"])
                else:
                    run([trac_env.encode('ascii'),"initenv", req.args.get('projname'),"sqlite:db/trac.db", "svn", svn_env])
                run([trac_env.encode('ascii'),"permission", "add", req.authname , "TRAC_ADMIN"])

        return 'tram_admin.html',{'projname': req.args.get('projname')}

    # ITemplateProvider methods
    def get_templates_dirs(self):
        from pkg_resources import resource_filename
        return [resource_filename(__name__,'templates')]
        
    def get_htdocs_dirs(self):
        return []

