#!/usr/bin/python
"""
This code is used for deployment in order to create or update these
environement variables to enable the deployment scripts to run successfully.
    DeployPath      - Root path for the deployment tool file tree
    PATH/Path       - updated PATH/Path for deployment executables
    LD_LIBRARY_PATH - Linux load library path
    PYTHONPATH      - path for deployment Python modules
    DeploymentStore - Location of the data files SystemInfo.xml and SystemLog.xml
    StoreDevice     - The path or DOS drive letter of the DeploymentStore
    BootDevice      - The path or DOS drive letter of the current boot device

setDeploymentEnv sets $DeployPath when setDeploymentEnv is invoked with the full path
For Linux environments invoke by:
   . `/opt/deploy/bin/setDeploymentEnv`
to set the environment variables from within a bash shell script.
For Windows environments invoke by:
    call %SystemDrive%\deploy\bin\setDeploymentEnv.cmd
to set the environment variables from within a Windows command shell script.

This script can be customized to accommodate actual runtime deployment environments
"""

import string, os, os.path, sys, shutil

if os.environ.has_key('DeployPath') and os.path.exists(os.environ['DeployPath']):
    DeployPath = os.environ['DeployPath']
else:
    if sys.platform == 'win32':
        if __file__[1] == ':':
            DeployPath = os.path.dirname(os.path.dirname(__file__))
        else:
            DeployPath = os.path.join('%s:%s'%(os.environ['RAMDrive'],os.sep),'deploy')
    else:
        try:
            __file__
        except:
            __file__ = os.path.abspath(__name__)
        try:
            if __file__[0] == os.sep:
                DeployPath = os.path.dirname(os.path.dirname(__file__))
            else:
                DeployPath = os.path.abspath(__file__)
        except:
            DeployPath = os.path.join(os.sep,'opt','deploy')
assert os.path.exists(DeployPath)
if os.environ.has_key('DeploymentStore') and os.path.exists(os.environ['DeploymentStore']):
    DeploymentStore = os.environ['DeploymentStore']
else:
    DeploymentStore = os.path.join(DeployPath,'DeploymentStore')
    if sys.platform == 'win32':
        # look for USB WinPE location
        for c in string.ascii_uppercase:
            if os.path.exists(os.path.join('%s:%s'%(c,os.sep),'winPDK.SDI')) or os.path.exists(os.path.join('%s:%s'%(c,os.sep),'winPDK.iso')):
                if os.environ.has_key('DeploymentStore'):
                    DeploymentStore = c + os.environ['DeploymentStore'][1:]
                else:
                    DeploymentStore = os.path.join('%s:%s'%(c,os.sep),'DeploymentStore')
                break
        else:
            print"echo no WinPE USB path found to set 'DeploymentStore'"
    elif sys.platform == 'linux2':
        for c in string.ascii_lowercase:
            # look for USB SLAX location
            if os.path.exists(os.path.join('%s'%os.sep,'mnt','sd%s1'%c,'slax','livecd.sgn')):
                if os.environ.has_key('DeploymentStore'):
                    DeploymentStore = os.environ['DeploymentStore']
                    offset = DeploymentStore.find('1_removable')
                    DeploymentStore = DeploymentStore.replace('sd%s1_removable'%DeploymentStore[offset-1],'sd%s1'%c)
                else:
                    DeploymentStore = os.path.join('%s'%os.sep,'mnt','sd%s1'%c,'DeploymentStore')
                break
            # look for USB syslinux location
            if os.path.exists(os.path.join('%s'%os.sep,'mnt','sd%s1'%c,'boot','syslinux')):
                if os.environ.has_key('DeploymentStore'):
                    DeploymentStore = os.environ['DeploymentStore']
                    offset = DeploymentStore.find('1_removable')
                    DeploymentStore = DeploymentStore.replace('sd%s1_removable'%DeploymentStore[offset-1],'sd%s1'%c)
                else:
                    DeploymentStore = os.path.join('%s'%os.sep,'mnt','sd%s1'%c,'DeploymentStore')
                break
            if os.path.exists(os.path.join('%s'%os.sep,'mnt','sd%s1_removable'%c,'rootcopy')):
                if os.environ.has_key('DeploymentStore'):
                    DeploymentStore = os.environ['DeploymentStore']
                    offset = DeploymentStore.find('1_removable')
                    DeploymentStore = DeploymentStore.replace('sd%s1_removable'%DeploymentStore[offset-1],'sd%s1_removable'%c)
                else:
                    DeploymentStore = os.path.join('%s'%os.sep,'mnt','sd%s1_removable'%c,'DeploymentStore')
                break
            # look for USB syslinux location
            if os.path.exists(os.path.join('%s'%os.sep,'mnt','sd%s1_removable'%c,'syslinux')):
                if os.environ.has_key('DeploymentStore'):
                    DeploymentStore = os.environ['DeploymentStore']
                    offset = DeploymentStore.find('1_removable')
                    DeploymentStore = DeploymentStore.replace('sd%s1_removable'%DeploymentStore[offset-1],'sd%s1_removable'%c)
                else:
                    DeploymentStore = os.path.join('%s'%os.sep,'mnt','sd%s1_removable'%c,'DeploymentStore')
                break
        #else:
            # echo doesn't work right when script is run as: `/opt/deploy/bin/setDeploymentEnv`
            # the first 'echo' echos all succeeding output from the script
            #print "echo no SLAX/syslinux USB path found to set 'DeploymentStore'"
    if not os.path.exists(DeploymentStore):
        try:
            shutil.copytree(os.path.join(DeployPath,'xml'),DeploymentStore)
        except OSError: # likely a CD was being written on WinPE
            DeploymentStore = os.path.join(DeployPath,'DeploymentStore')
            shutil.copytree(os.path.join(DeployPath,'xml'),DeploymentStore)

if os.environ.has_key('BootDevice') and os.path.exists(os.environ['BootDevice']):
    BootDevice = os.environ['BootDevice']
else:
    BootDevice = ''
    if sys.platform == 'win32':
        # look for USB WinPE location
        for c in string.ascii_uppercase:
            if os.path.exists(os.path.join('%s:%s'%(c,os.sep),'winPDK.SDI')) or os.path.exists(os.path.join('%s:%s'%(c,os.sep),'winPDK.iso')):
                BootDevice = c + ":"
                break
        else:
            print"echo no WinPE USB path found to set 'BootDevice'"
    elif sys.platform == 'linux2':
        for c in string.ascii_lowercase:
            # look for USB SLAX location
            if os.path.exists(os.path.join('%s'%os.sep,'mnt','sd%s1'%c,'slax','livecd.sgn')):
                BootDevice = os.path.join('%s'%os.sep,'mnt','sd%s1'%c)
                break
            # look for USB syslinux location
            if os.path.exists(os.path.join('%s'%os.sep,'mnt','sd%s1'%c,'boot','syslinux')):
                BootDevice = os.path.join('%s'%os.sep,'mnt','sd%s1'%c)
                break
            # look for USB SLAX location
            if os.path.exists(os.path.join('%s'%os.sep,'mnt','sd%s1_removable'%c,'rootcopy')):
                BootDevice = os.path.join('%s'%os.sep,'mnt','sd%s1_removable'%c)
                break
            # look for USB syslinux location
            if os.path.exists(os.path.join('%s'%os.sep,'mnt','sd%s1_removable'%c,'syslinux')):
                BootDevice = os.path.join('%s'%os.sep,'mnt','sd%s1_removable'%c)
                break
        #else:
            # 'echo' doesn't work right when script is run as: `/opt/deploy/bin/setDeploymentEnv`
            # the first 'echo' echos all succeeding output from the script
            #print "echo no SLAX/syslinux USB path found to set 'BootDevice'"

if sys.platform == 'win32':
    export = 'set '
    DeployDevice = os.path.splitdrive( DeploymentStore  )[0]
    path = 'Path'
elif sys.platform == 'linux2':
    export = 'export '
    DeployDevice = os.path.dirname( DeploymentStore )
    path = 'PATH'

prePath = ''
postPath = ''
seg = DeployPath + os.sep + "bin"
if os.environ[path].find(seg) < 0:
    prePath = prePath + seg + os.pathsep
if sys.platform == 'win32':
    seg = DeployPath + os.sep + "win32"
    if os.environ[path].find(seg) < 0:
        prePath = prePath + seg + os.pathsep
    seg = DeployPath + os.sep + "win32" + os.sep +"dlls"
    if os.environ[path].find(seg) < 0:
        prePath = prePath + seg + os.pathsep
    seg = DeployPath + os.sep + "Python23"
    if os.environ[path].find(seg) < 0:
        postPath = postPath + os.pathsep + seg
elif sys.platform == 'linux2':
    seg = DeployPath + os.sep + "Linux"
    if os.environ[path].find(seg) < 0:
        prePath = prePath + seg + os.pathsep

print export + "DeployPath=" + DeployPath
print export + path + "=" + prePath + os.environ[path]+ postPath
if sys.platform == 'linux2':
    if os.environ.has_key('LD_LIBRARY_PATH'):
        print export + "LD_LIBRARY_PATH="+os.environ['LD_LIBRARY_PATH']+ os.pathsep + DeployPath + os.sep + "Linux" + os.sep + "libs"
    else:
        print export + "LD_LIBRARY_PATH=" + DeployPath + os.sep + "Linux" + os.sep + "libs"
if os.environ.has_key('PYTHONPATH'):
    print export + "PYTHONPATH="+os.environ['PYTHONPATH']+ os.pathsep + DeployPath + os.sep + "Python" + os.pathsep + DeployPath + os.sep + "doc"
else:
    print export + "PYTHONPATH=" + DeployPath + os.sep + "Python" + os.pathsep + DeployPath + os.sep + "doc"
print export + "DeploymentStore=" + DeploymentStore
print export + "StoreDevice=" + DeployDevice
print export + "BootDevice=" + BootDevice
