#!/usr/bin/env python2
# -*- coding: utf-8 -*-

# setup.py --- Setup script for calculate-core

# Copyright 2011-2012 Calculate Ltd. http://www.calculate-linux.org
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os, sys
from os import path, system
import glob
import distutils
from distutils.core import setup
from distutils.command.install_data import install_data
import distutils.command.build
import distutils.command.install
import distutils.command.install_egg_info

var_data_files = []

data_files = [('/etc/init.d', ['scripts/calculate-core'])]

__version__ = "3.1.8"
__app__ = "calculate-core"

locales = ("ru",'en')

BUILD_MAN_PATH = "build/man"

class build_man( distutils.core.Command ) :
 
    description = "build man files"
    user_options = []

    def initialize_options( self ) :
        pass
    def finalize_options( self ) :
        pass

    def _install_man(self,man,baseLocale):
        baseMan = path.basename(man)
        man_num = man[-1]
        manPath = path.join(BUILD_MAN_PATH,baseLocale,"man%s"%man_num)
        self.mkpath(manPath)
        manPath = path.join(manPath,baseMan)
        self.copy_file(man,manPath)
        cout("compress %s\n"% manPath)
        system("bzip2 -f %s"%manPath)

    def run( self ) :
        buildManPath = BUILD_MAN_PATH
        self.mkpath(buildManPath)
        for locale in glob.glob("man/*"):
            baseLocale = path.basename(locale)
            if os.path.isfile(locale) and locale[-1].isdigit():
                self._install_man(locale,"")
            else:
                for man in glob.glob("%s/*.[12345678]"%locale) :
                    self._install_man(man,baseLocale)

class install_man( install_data ) :
    description = "install man files"
    user_options = []

    def finalize_options(self):
        install_data.finalize_options(self)
        self.data_files = []
        for root,dirs,files in os.walk(BUILD_MAN_PATH):
            for filename in files:
                self.data_files += [(path.join(self.install_dir,root[6:]),
                                    [path.join(root,filename)])]

class cl_core_data(install_data):
    def run (self):
        install_data.run(self)
        data_file = [("/etc/init.d/calculate-core",0755)]
        fileNames = map(lambda x: os.path.split(x[0])[1], data_file)
        listNames = map(lambda x: filter(lambda y: y, x[0].split("/")),
                        data_file)
        data_find = {}
        for i in range(len(fileNames)):
            listNames[i].reverse()
            data_find[fileNames[i]] =[listNames[i],data_file[i][1]]

        for path in self.get_outputs():
            nameFile = os.path.split(path)[1]
            if nameFile in data_find.keys():
                data = data_find[nameFile][0]
                mode = data_find[nameFile][1]
                flagFound = True
                iMax = len(data)
                pathFile = path
                for i in range(iMax):
                    if data[i] != os.path.split(pathFile)[1]:
                        flagFound = False
                        break
                    pathFile = os.path.split(pathFile)[0]
                if flagFound:
                    os.chmod(path, mode)

class install(distutils.command.install.install):
    def has_man(self):
        return len(glob.glob("build/man/*")) > 0

    sub_commands = distutils.command.install.install.sub_commands + [
        ('install_man',has_man),
    ]

class build(distutils.command.build.build):
    def run (self):
        distutils.command.build.build.run(self)

    def has_man(self):
        return len(glob.glob("man/*")) > 0
    
    sub_commands = distutils.command.build.build.sub_commands + [
        ('build_man',has_man)
    ]
    
 
def cout(string):
    sys.stdout.write(string)
    sys.stdout.flush()
    
class empty_egg_info( distutils.command.install_egg_info.install_egg_info ):
    def run(self):
        pass

setup(
    name = __app__,
    version = __version__,
    description = "The program for configuring WSDL server",
    author = "Calculate Ltd.",
    author_email = "support@calculate.ru",
    url = "http://calculate-linux.org",
    license = "http://www.apache.org/licenses/LICENSE-2.0",
    data_files = data_files,
    package_dir = {'calculate.core': "core"},
    packages = ['calculate.core','calculate.core.variables',
                'calculate.core.utils',
                'calculate.core.server','calculate.core.client'],
    scripts = ['./scripts/cl-core'],
    cmdclass={'install_data': cl_core_data,'build': build,
                'install_egg_info':empty_egg_info,'build_man':build_man, \
              'install':install,'install_man':install_man}
)
