#!/usr/bin/python
# -*- coding: latin-1 -*-
# INTEL CONFIDENTIAL
# Copyright 2007 Intel Corporation All Rights Reserved.
#
# The source code contained or described herein and all documents related to the
# source code (“Material”) are owned by Intel Corporation or its suppliers or
# licensors. Title to the Material remains with Intel Corporation or its
# suppliers and licensors. The Material may contain trade secrets and
# proprietary and confidential information of Intel Corporation and its
# suppliers and licensors, and is protected by worldwide copyright and trade
# secret laws and treaty provisions. No part of the Material may be used,
# copied, reproduced, modified, published, uploaded, posted, transmitted,
# distributed, or disclosed in any way without Intel’s prior express written
# permission.
# No license under any patent, copyright, trade secret or other intellectual
# property right is granted to or conferred upon you by disclosure or delivery
# of the Materials, either expressly, by implication, inducement, estoppel or
# otherwise. Any license under such intellectual property rights must be express
# and approved by Intel in writing.
#
# Include any supplier copyright notices as supplier requires Intel to use.
#
# Include supplier trademarks or logos as supplier requires Intel to use, preceded
# by an asterisk. An asterisked footnote can be added as follows:
# *Third Party trademarks are the property of their respective owners.
#
# Unless otherwise agreed by Intel in writing, you may not remove or alter this
# notice or any other notice embedded in Materials by Intel or Intel’s suppliers
# or licensors in any way.

"""
This script builds a 'rootcopy' tree from a source 'PDK' tree
 with the option of including RH drivers rather that the demo SLAX drivers
 for testing in RH deployment environments.
"""
__author__ = 'Todd C Davis'
__Product__ = 'Intel_PDK'

Usage = """Usage: %s [src]
    if 'src' then app and driver source files included in the 'rootcopy' tree
Usage: 'buildLinux.py ?' displays this usage statement
"""
import string, sys, os, os.path, shutil, glob

# Globals based on environment variables
PDKroot = os.path.join(os.environ['PDK'])
factoryPDKroot = os.path.join(os.environ['FACTORYPDK'])
#LinuxTree = ''
#rootcopy = ''
#optinstall = ''

kitdirs = [
    'bin',
    'Python',
    'xml',
    'doc',
    'Linux']

def removesvn(dst):
    cwd = os.getcwd()
    os.chdir(dst)
    files = os.listdir(os.getcwd())
    for file in files:
        if os.path.isdir(file):
            if file == '.':
                continue
            elif file == '..':
                continue
            elif file == '.svn':
                os.system('rmdir /s /q .svn')
                continue
            removesvn(file)
    os.chdir(cwd)

def extractZip(zip,dst):
    """ Note: paths are removed """
    if not os.path.exists(dst):
        os.mkdir(dst, 0777)
    import zipfile
    myZipFile = zipfile.ZipFile( zip, "r" )
    for fileName in myZipFile.namelist():
        if fileName.endswith('/'):
            #os.mkdir(os.path.join(dst, fileName))
            continue
        else:
            outfile = open(os.path.join(dst, os.path.basename(fileName)), 'wb')
            outfile.write(myZipFile.read(fileName))
            outfile.close()

def buildBaseTree():
    #install basic PDK files
    for kitdir in kitdirs:
        shutil.copytree(os.path.join(PDKroot,kitdir),os.path.join(optinstall,kitdir))
        if kitdir == 'bin':
            for f in glob.glob(os.path.join(optinstall,kitdir,'*.cmd')):
                os.remove(f)
        #if kitdir == 'Linux':
        #    shutil.rmtree(os.path.join(optinstall,kitdir,'drivers'))

def addFactoryFiles():
    for kitdir in kitdirs:
        if not kitdir == 'bin':
            if os.path.exists(os.path.join(factoryPDKroot,kitdir)):
                dirs = os.listdir(os.path.join(factoryPDKroot,kitdir))
                for d in dirs:
                    if d == 'drivers':
                        continue
                    if d == 'libs':
                        continue
                        #files = os.listdir(os.path.join(factoryPDKroot,kitdir,d))
                        #for f in files:
                        #    shutil.copytree(os.path.join(factoryPDKroot,kitdir,d,f),os.path.join(optinstall,kitdir,d,f))
                    elif os.path.isdir(os.path.join(factoryPDKroot,kitdir,d)):
                        shutil.copytree(os.path.join(factoryPDKroot,kitdir,d),os.path.join(optinstall,kitdir,d))
                    else:
                        shutil.copy2(os.path.join(factoryPDKroot,kitdir,d),os.path.join(optinstall,kitdir,d))


    #copy factory only files
    shutil.copy2(os.path.join(os.environ['FACTORY'],'LAD_Tools_07Q1DL1_PV','TOOLS','Linux32','OEM_Mfg','eeupdate32'),os.path.join(optinstall,'Linux','eeupdate32'))

def add_etcFiles():
    etc = os.path.join(PDKroot,'Demos','Linux','Slax','deployment','rootcopy','etc')
    shutil.copytree(etc,os.path.join(rootcopy,'etc'))
    shutil.copy2(os.path.join(PDKroot,'Demos','Linux','Slax','deployment','rootcopy','opt','deploy','Linux','dmidecode'),os.path.join(LinuxTree,'rootcopy','opt','deploy','Linux','dmidecode'))

def add_rootFiles():
    root = os.path.join(PDKroot,'Demos','Linux','Slax','deployment','rootcopy','root')
    shutil.copytree(root,os.path.join(rootcopy,'root'))

def add_usrFiles():
    slaxbuild = os.path.join('packages','Slax','Slax-5.1.8')
    usr = os.path.join(slaxbuild,'rootcopy','usr')
    shutil.copytree(usr,os.path.join(rootcopy,'usr'))
    removesvn(os.path.join(rootcopy,'usr'))
    shutil.copy2(os.path.join(slaxbuild,'rootcopy','lib.PIIX.zip'),rootcopy)
    os.mkdir(os.path.join(LinuxTree,'slax5'))
    shutil.copy2(os.path.join(slaxbuild,'vmlinuz.PIIX'),os.path.join(LinuxTree,'slax5'))

"""
def addSLAXdrivers():
    #The driver package drivers-slax5.tar.gz in the PDK replaces this
    # setup SLAX files
    slaxDrivers = os.path.join(PDKroot,'Demos','Linux','Slax','deployment','rootcopy','opt','deploy','Linux','drivers')
    files = os.listdir(slaxDrivers)
    dst = os.path.join(optinstall,'Linux','drivers')
    if not os.path.exists(dst):
        os.mkdir(dst)
    dst = os.path.join(dst,'slax')
    if not os.path.exists(dst):
        os.mkdir(dst)
    for f in files:
        s = os.path.join(slaxDrivers,f)
        if f == '.svn':
            pass
        elif os.path.isdir(s):
            shutil.copytree(s,os.path.join(dst,f))
        else:
            shutil.copy2(s,os.path.join(dst,f))
"""

def rh3update():
    syscfgtar = 'syscfg-el3.tar.gz'
    dstdir = os.path.join(optinstall,'Linux','syscfg')
    if not os.path.exists(dstdir):
        os.mkdir(dstdir)
    shutil.copy2(os.path.join(PDKroot,'Linux','drivers',syscfgtar),os.path.join(dstdir,syscfgtar))
    """
    cwd = os.getcwd()
    os.chdir(dstdir)
    if os.path.exists('ENUS'):
        os.system('rmdir /s /q ENUS')
    import tarfile
    tar = tarfile.open(syscfgtar, "r:gz")
    tar.extractall()
    tar.close()
    os.chdir('lib')
    for f in glob.glob('*.1.0'):
        shutil.copy2(f,os.path.join('..','..','libs',f[:-4]))
    os.chdir('..')
    os.system('rmdir /s /q lib')
    os.system('rmdir /s /q drivers')
    os.chdir(cwd)
    """

"""
def addDrivers(drv):
    # C:\Toolkit\trunk\packages\s5000_drivers\drivers-*.tar.gz
    dstdir = os.path.join(optinstall,'Linux','drivers')
    if not os.path.exists(dstdir):
        os.mkdir(dstdir)
    dstdir = os.path.join(dstdir,drv)
    if not os.path.exists(dstdir):
        os.mkdir(dstdir)
    shutil.copy2(os.path.join(PDKroot,'Linux','drivers',OSdrivers[drv]),os.path.join(dstdir,OSdrivers[drv]))
    cwd = os.getcwd()
    os.chdir(dstdir)
    for f in glob.glob('*.ko'):
        os.remove(f)
    import tarfile
    tar = tarfile.open(OSdrivers[drv], "r:gz")
    tar.extractall()
    tar.close()
    #cp -f amifldrv_mod.o-dmiedit $pdk_dir/Linux/drivers/s5000/amifldrv_mod.o
    for arch in ['S3000','S5000']:
        if not os.path.exists(arch):
            os.mkdir(arch)
        shutil.copy2('amifldrv_mod.o-dmiedit',os.path.join(arch,'amifldrv_mod.o'))
        #shutil.copy2('amifldrv_mod.o-dmiedit',os.path.join('S5000','amifldrv_mod.o'))
    os.remove('amifldrv_mod.o-dmiedit')
    for f in glob.glob('*.sh'):
        os.remove(f)
    # need some startup scripts from SLAX
    if not drv == 'slax':
        for f in ['imbdrv','smidrv']:
            shutil.copy2(os.path.join('..','slax',f),f)
    os.chdir(cwd)
"""

"""
def addResources2Tree():
    #setup resources for custom deployment demo
    for system in ['S3000','S5000']:
        resources = os.path.join(os.environ['UPDATES'],system)
        files = os.listdir(resources)
        for f in files:
            if not f == '.svn':
                s = os.path.join(resources,f)
                if f == 'restore':
                    shutil.copytree(s,os.path.join(optinstall,'doc','ofu',system,f))
                    removesvn(os.path.join(optinstall,'doc','ofu',system,f))
                else:
                    dataPath = os.path.join(optinstall,'doc','ofu',system)
                    shutil.copy2(s,os.path.join(dataPath,f))
        # don't unpack default resource images for deployment demo
        #if system == 'S3000':
        #    zipFile = 'S3000AH_BIOS_R42.zip'
        #else:
        #    zipFile = 'telco-wd_060807.zip'
        #    #shutil.copy2(os.path.join(resources,'TIGW1U_MASTER.CFG-ac'),os.path.join(dataPath,'MASTER.CFG-ac'))
        #zipPath = os.path.join(dataPath,zipFile)
        # watch caps here for SLAX, expand in rc scripts later.
        # extractZip(zipPath,dataPath)
"""

def addSources2Tree():
    #setup SLAX 'development' tree for compiling SLAX drivers and apps
    #slaxdev = os.path.join(PDKroot,'Demos','Linux','Slax','development','rootcopy')
    #shutil.copytree(slaxdev,rootcopy)
    shutil.copytree(os.path.join(PDKroot,'Linux','drivers'),os.path.join(rootcopy,'root','drivers'))
    shutil.copytree(os.path.join(os.environ['SOURCE'],'apps'),os.path.join(rootcopy,'root','apps'))
    removesvn(os.path.join(rootcopy,'root','apps'))
    #shutil.copytree(os.path.join(rootcopy,'opt'),os.path.join(LinuxTree,'development','rootcopy','opt'))

def addSlaxModules():
    slaxtools = os.path.join('packages','Slax','Slax-5.1.8')
    slaxmodules = [
        'Python_2_4_3.mo',
        'PDKdemo.mo',
        'tk-8.4.6-i486-1.mo',
        'tcl_8_4_11.mo',
        'Firefox_2_0_0_3_EN.mo',
        'gdb_6_4.mo',
        'kdevelop_3_3_5.mo',
        'Kernel_headers_2_6_16.mo',
        'Linux_Kernel_2_6_16_2_6_16.mo',
        'Linux_kernel_sources_2_6_16.mo',
        'Official_Development_module_5_1_4.mo',
    ]

    dstdir = os.path.join(LinuxTree,'slax5')
    for obj in ['MySLAX_Creator.exe','slax-5.1.8.iso']:
        shutil.copy2(os.path.join(slaxtools,obj),dstdir)

    for obj in slaxmodules:
        shutil.copy2(os.path.join(slaxtools,obj),dstdir)

    print
    print "run MySLAX Creator: (install with %s)" % os.path.join(dstdir,'MySLAX_Creator.exe')
    print "\t1. Use ISO: %s" % os.path.join(dstdir,'slax-5.1.8.iso')
    print "\t2. Add module: %s" % os.path.join(dstdir,'Python_2_4_3.mo')
    print "\t       Any other modules are optional"
    print "\t       The TKdemo module requires tk-8.4.6-i486-1.mo and tcl_8_4_11.mo"
    print "\t       The other Slax modules are for compiling apps and drivers"
    print "\t3. Add 'rootcopy' folder: %s" % os.path.join(LinuxTree,'rootcopy')
    print "To enable SATA RAID on the target media:"
    print "\t1. Replace vmlinuz with vmlinuz.PIIX"
    print "\t2. unzip rootcopy/lib.PIIX.zip"

    slaxtools = os.path.join('packages','Slax','Slax-6.0.7')
    slaxmodules = [
        'python-2.5.2-i486-1.lzm',
        'vim-7.1.lzm',
        'krusader-1.90.0.lzm',
        'firefox-2.0.0.14.lzm',
    ]

    dstdir = os.path.join(LinuxTree,'slax6')
    os.mkdir(dstdir)
    for obj in ['slax-6.0.7.tar','slax-6.0.7.iso']:
        shutil.copy2(os.path.join(slaxtools,obj),dstdir)

    for obj in slaxmodules:
        shutil.copy2(os.path.join(slaxtools,obj),dstdir)

    print
    print "unzip %s onto USB media" % os.path.join(dstdir,'slax-6.0.7.tar')
    print "\t1. or use %s to make a CD" % os.path.join(dstdir,'slax-6.0.7.iso')
    print "\t2. Copy module %s to the /slax/modules directory " % os.path.join(dstdir,'python-2.5.2-i486-1.lzm')
    #print "\t       Any other modules are optional"
    #print "\t       The TKdemo module requires tk-8.4.6-i486-1.mo and tcl_8_4_11.mo"
    #print "\t       The other Slax modules are for compiling apps and drivers"
    print "\t3. Copy %s to the /slax/rootcopy directory " % os.path.join(LinuxTree,'rootcopy')
    #print "To enable SATA RAID on the target media:"
    #print "\t1. Replace vmlinuz with vmlinuz.PIIX"
    #print "\t2. unzip rootcopy/lib.PIIX.zip"


if __name__ == '__main__':
    global LinuxTree, rootcopy, optinstall
    LinuxTree = os.path.join('..','build','Linux-%s'%(os.environ['PDK_VERSION']))
    rootcopy = os.path.join(LinuxTree,'rootcopy')
    optinstall = os.path.join(rootcopy,'opt','deploy')
    if os.path.exists(LinuxTree):
        shutil.rmtree(LinuxTree)

    buildBaseTree()
    addFactoryFiles()
    add_etcFiles()
    add_rootFiles()
    add_usrFiles()
    #addSLAXdrivers()
    #drvs = OSdrivers.keys()
    #drvs.sort(reverse=True)
    #for arg in drvs:
    #    if arg == 'rh3':
    #        rh3update()
    #    addDrivers(arg)
    rh3update()
    #addResources2Tree()
    if len(sys.argv) > 1 and sys.argv[1] == 'src':
        addSources2Tree()
    addSlaxModules()

