#!/usr/bin/python

#/****************************************************************************
#*                                                                           *
#*  OpenNI 2.x Alpha                                                         *
#*  Copyright (C) 2012 PrimeSense Ltd.                                       *
#*                                                                           *
#*  This file is part of OpenNI.                                             *
#*                                                                           *
#*  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 re
import sys
import shutil
import platform
import stat
import xml.dom.minidom

class Harvest:
    def __init__(self, rootDir, outDir, arch):
        self.rootDir = rootDir
        self.outDir = outDir
        self.arch = arch
        self.osName = platform.system()
        self.binDir = os.path.join(rootDir, 'Bin', arch + '-Release')
        self.platformSuffix = ''
        self.glutSuffix = '32'
        
        if self.osName == 'Windows':
            if arch == 'x86':
                self.binDir = os.path.join(rootDir, 'Bin', 'Win32-Release')
            elif arch == 'x64':
                self.platformSuffix = '64'
                self.glutSuffix = '64'

    def copySharedObject(self, sourceDir, name, targetDir):
        if self.osName == 'Windows':
            shutil.copy(os.path.join(sourceDir, name + '.dll'), targetDir)
            shutil.copy(os.path.join(sourceDir, name + '.pdb'), targetDir)
        elif self.osName == 'Linux':
            shutil.copy(os.path.join(sourceDir, 'lib' + name + '.so'), targetDir)
        elif self.osName == 'Darwin':
            shutil.copy(os.path.join(sourceDir, 'lib' + name + '.dylib'), targetDir)
        else:
            raise 'Unsupported platform!'
            
    def copyExecutable(self, sourceDir, name, targetDir):
        if self.osName == 'Windows':
            shutil.copy(os.path.join(sourceDir, name + '.exe'), targetDir)
            shutil.copy(os.path.join(sourceDir, name + '.pdb'), ta
rgetDir)
        else:
            shutil.copy(os.path.join(sourceDir, name), targetDir)
            
    def regxReplace(sel
f, findStr, repStr, filePath):
        "replaces all findStr by repStr in file filePath using regualr expression"
        findStrRegx = re.compile(findStr)
        tempName = filePath+'~~~'
        fileMode = os.stat(filePath).st_mode
        os.chmod(filePath, fileMode | stat.S_IWRITE)
        input = open(filePath)
        output = open(tempName, 'w')
        for s in input:
            output.write(findStrRegx.sub(repStr, s))
        output.close()
        input.close()
        os.remove(filePath)
        os.rename(tempName, filePath)
        
    def copyRedistFiles(self, targetDir):
        os.makedirs(targetDir)
        # start with OpenNI itself
        self.copySharedObject(self.binDir, 'OpenNI2', targetDir)
        self.copySharedObject(self.binDir, 'OpenNI2.jni', targetDir)
        shutil.copy(os.path.join(self.binDir, 'org.openni.jar'), targetDir)
        shutil.copy(os.path.join(self.rootDir, 'Config', 'OpenNI.ini'), targetDir)
        # and now all drivers
        binDriversDir = os.path.join(self.binDir, 'OpenNI2', 'Drivers')
        targetDriversDir = os.path.join(targetDir, 'OpenNI2', 'Drivers')
        os.makedirs(targetDriversDir)
        self.copySharedObject(binDriversDir, 'OniFile', targetDriversDir)
        self.copySharedObject(binDriversDir, 'PS1080', targetDriversDir)
        self.copySharedObject(binDriversDir, 'PSLink', targetDriversDir)
        shutil.copy(os.path.join(self.rootDir, 'Config', 'OpenNI2', 'Drivers', 'PS1080.ini'), targetDriversDir)
        shutil.copy(os.path.join(self.rootDir, 'Config', 'OpenNI2', 'Drivers', 'PSLink.ini'), targetDriversDir)
        if self.osName == 'Windows':
            self.copySharedObject(binDriversDir, 'Kinect', targetDriversDir)
        
    def copySample(self, samplesDir, name, isLibrary = False, isGL = False, isJava = False):
        if self.arch == 'Arm' and isGL:
            return
            
        sampleTargetDir = os.path.join(samplesDir, name)
        sampleSourceDir = os.path.join(self.rootDir, 'Samples', name)

        # copy sources
        for root, dirs, files in os.walk(sampleSourceDir):
            # take dir name without 'root' and append to target
            dst = os.path.join(samplesDir, name, os.path.relpath(root, sampleSourceDir))
            #print dst
            for file in files:
                if (isJava and file.endswith('.java')) or (not isJava and (file.endswith('.h') or file.endswith('.cpp'))):
                    if not os.path.exists(dst):
                        os.makedirs(dst)
                    shutil.copy(os.path.join(root, file), dst)
                    
        # copy common header
        if not isJava and not isLibrary:
            shutil.copy(os.path.join(self.rootDir, 'Samples', 'Common', 'OniSampleUtilities.h'), sampleTargetDir)
            
        # copy GL headers
        if self.osName == 'Windows' and isGL:
            shutil.copytree(os.path.join(self.rootDir, 'ThirdParty', 'GL', 'GL'), os.path.join(sampleTargetDir, 'GL'))
            shutil.copytree(os.path.join(self.rootDir, 'ThirdParty', 'GL', 'glh'), os.path.join(sampleTargetDir, 'glh'))
            # and lib
            shutil.copy(os.path.join(self.rootDir, 'ThirdParty', 'GL', 'glut32.lib'), sampleTargetDir)
            shutil.copy(os.path.join(self.rootDir, 'ThirdParty', 'GL', 'glut64.lib'), sampleTargetDir)
            shutil.copy(os.path.join(self.rootDir, 'ThirdParty', 'GL', 'glut32.dll'), sampleTargetDir)
            shutil.copy(os.path.join(self.rootDir, 'ThirdParty', 'GL', 'glut64.dll'), sampleTargetDir)
                    
        # and project file / makefile
        if self.osName == 'Windows':
            if isJava:
                shutil.copy(os.path.join(sampleSourceDir, 'Build.bat'), sampleTargetDir)
                shutil.copy(os.path.join(self.rootDir, 'ThirdParty', 'PSCommon', 'BuildSystem', 'BuildJavaWindows.py'), sampleTargetDir)
                # fix call
                buildFile = open(os.path.join(sampleTargetDir, 'Build.bat'))
                buildScript = buildFile.read()
                buildFile.close()

                buildScript = re.sub('..\\\\..\\\\ThirdParty\\\\PSCommon\\\\BuildSystem\\\\', '', buildScript)
                buildScript = re.sub('..\\\\..\\\\Bin', 'Bin', buildScript)

                buildFile = open(os.path.join(sampleTargetDir, 'Build.bat'), 'w')
                buildFile.write('@echo off\n')
                buildFile.write('IF "%1"=="x64" (\n')
                buildFile.write('\txcopy /D /S /F /Y "%OPENNI2_REDIST64%\\*" "Bin\\x64-Release\\"\n')
                buildFile.write(') ELSE (\n')
                buildFile.write('\txcopy /D /S /F /Y "%OPENNI2_REDIST%\\*" "Bin\\Win32-Release\\"\n')
                buildFile.write(')\n')
                buildFile.write(buildScript)
                buildFile.close()
                
            else:
                shutil.copy(os.path.join(sampleSourceDir, name + '.vcxproj'), sampleTargetDir)
                projFi