#!/usr/bin/env python

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

# Copyright 2008-2010 Mir Calculate. 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
import glob
import sys
import re
from distutils.core import setup
from distutils.command.build_scripts import build_scripts
from distutils.command.install_scripts import install_scripts
from distutils.command.install_data import install_data

def cmp(a, b):
    return (a > b) - (b < a)

data_files = []

var_data_files = [("/var/calculate/server-profile",[]),
                  ("/var/calculate/server-data",[])]

data_dirs_local = ['profile','ldif']
share_calculate_dir = "/usr/share/calculate-2.0/"
data_dirs_share = ['i18n']

data_files += var_data_files

def scanDirs(profilesDirs):
    """Recursive scanning directories"""
    dirs_total = []
    class dirProf:
        def __init__(self):
            self.baseDir = False
            self.dirs = []
            self.files = []
    for profileDir in profilesDirs:
        if profileDir:
            dirP = dirProf()
            dirP.baseDir = profileDir
            for dirname, dirs, files in os.walk(profileDir):
                if '/.svn' in dirname:
                    return False
                for nameFile in files:
                    absNameFile = dirname + "/" + nameFile
                    if '/.svn' in absNameFile:
                        continue
                    dirP.files.append(absNameFile)
                for nameDir in dirs:
                    absNameDir = dirname + "/" + nameDir
                    if '/.svn' in absNameDir:
                        continue
                    dirP.dirs.append(absNameDir)
            dirs_total.append(dirP)
    return dirs_total

def create_data_files (data_dirs, prefix=""):
    test1_files = []
    dirs = scanDirs(data_dirs)
    i = 0
    for obj in dirs:
        if not obj.dirs:
            obj.dirs.append(data_dirs[i])
        i += 1
    for obj in dirs:
        files_obj_dirs = []
        for dir_name in obj.dirs:
            for file_name in obj.files:
                if re.match(dir_name,file_name):
                    files_obj_dirs.append(dir_name)
                    break
        for files_obj_dir in files_obj_dirs:
            obj.dirs.remove(files_obj_dir)
        files_obj_dirs.sort(key=len, reverse=True)
        for dir_name in files_obj_dirs:
            wr_sp = (prefix + dir_name,[])
            file_dirs = []
            for file_name in obj.files:
                if re.match(dir_name,file_name):
                    file_dirs.append(file_name)
            for file_name in file_dirs:
                wr_sp[1].append(file_name)
                obj.files.remove(file_name)
            test1_files.append(wr_sp)
    test1_files.reverse()
    test2_files = []
    for obj in dirs:
        for dir_name in obj.dirs:
            wr_sp = (prefix + dir_name,[])
            test2_files.append(wr_sp)

    test1_files = test2_files + test1_files
    return test1_files

data_files += create_data_files(data_dirs_local)
data_files += create_data_files(data_dirs_share, share_calculate_dir)
data_files += [('/etc/conf.d', ['data/sortmilter.conf']),
               ('/etc/init.d', ['data/sortmilter.init'])]

class cl_build_scripts(build_scripts):
    """Class for build scripts"""
    def run (self):
        scripts = ['./scripts/proxy', './scripts/dhcp',
                   './scripts/execserv',
                   './scripts/execsamba']
        backup_build_dir = self.build_dir
        backup_scripts = [x for x in self.scripts if x not in scripts]
        self.scripts = scripts
        self.build_dir = self.build_dir + "-bin"
        build_scripts.run(self)
        self.scripts = backup_scripts
        self.build_dir = backup_build_dir
        build_scripts.run(self)

class cl_install_scripts(install_scripts):
    """Class for install scripts"""
    def run (self):
        backup_install_dir = self.install_dir
        backup_build_dir = self.build_dir
        cl_cmd_obj = self.distribution.get_command_obj("install")
        self.build_dir = self.build_dir + "-bin"
        self.install_dir = os.path.join(cl_cmd_obj.install_data, "bin")
        install_scripts.run(self)
        self.build_dir = backup_build_dir
        self.install_dir = backup_install_dir
        install_scripts.run(self)

class cl_install_data(install_data):
    def run (self):
        install_data.run(self)
        data_file = \
            [("/etc/init.d/sortmilter.init", "sortmilter", 0o755),
             ("/etc/conf.d/sortmilter.conf", "sortmilter", None)]
        data_find = \
            dict(
            [(os.path.basename(x[0]), 
                    [list(reversed([y for y in x[0].split("/") if y])), x[1],x[2]]) 
                    for x in data_file])

        for path in self.get_outputs():
            nameFile = os.path.split(path)[1]
            if nameFile in data_find.keys():
                data = data_find[nameFile][0]
                newname = data_find[nameFile][1]
                mode = data_find[nameFile][2]
                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:
                    if not mode is None:
                        os.chmod(path, mode)
                    if not newname is None:
                        newname = os.path.join(os.path.dirname(path), newname)
                        os.rename(path, newname)

setup(
    name = 'calculate-server',
    version = "2.1.16",
    description = "The program for configuring server-data linux",
    author = "Calculate Pack",
    author_email = "support@calculate.ru",
    url = "http://www.calculate-linux.org",
    license = "http://www.apache.org/licenses/LICENSE-2.0",
    package_dir = {'calculate-server': "."},
    packages = ['calculate-server.pym'],
    data_files = data_files,
    scripts=["./scripts/cl-useradd",
             "./scripts/cl-userdel",
             "./scripts/cl-usermod",
             "./scripts/cl-groupadd",
             "./scripts/cl-groupmod",
             "./scripts/cl-groupdel",
             "./scripts/cl-passwd",
             "./scripts/cl-setup",
             "./scripts/cl-backup-server",
             "./scripts/cl-update-server",
             "./scripts/cl-rebuild",
             "./scripts/cl-replication",
             "./scripts/execserv",
             "./scripts/execsamba",
             "./scripts/replcron",
             "./scripts/cl-info",
             "./scripts/proxy",
             "./scripts/cl-dns-recadd",
             "./scripts/cl-dns-recdel",
             "./scripts/cl-dns-recmod",
             "./scripts/cl-dns-zoneadd",
             "./scripts/cl-dns-zonedel",
             "./scripts/cl-dns-zonemod",
             "./scripts/cl-dhcp-netadd",
             "./scripts/cl-dhcp-netdel",
             "./scripts/cl-dhcp-netmod",
             "./scripts/cl-dhcp-hostadd",
             "./scripts/cl-dhcp-hostdel",
             "./scripts/cl-dhcp-hostmod",
             "./scripts/dhcp",
             "./scripts/sortmilter"],
    cmdclass={
              'build_scripts':cl_build_scripts,
              'install_scripts':cl_install_scripts,
              'install_data': cl_install_data},
)
