'''
Wrapping system for publishing modules with Bobo on NT systems.

This module works around the poor and inconsistent symlinks
available on NT systems to allow the publishing of Bobo-enabled
content under common NT web servers.

This wrapping function follows Jeff's approach of using a more
complex cgi script which is copied to the cgi-directory, instead
of a less complex script which imports the boilerplate mechanism.

The interface is completely different from Jeff's, and it allows
for a number of options including whether or not to include the
IIS3.0 fix (by me), whether to print out a traceback at the level
of this module, and specifying the site-local string for invoking
the python interpretter in a Unix shell.

By:

        Mike Fletcher, 1997, based (in part) on the work of Jeff Bauer.

Modified by:

        Jim Fulton, 1998, changed UI to use dashes for options so I 
        could test on Unix.

Warnings:

        This module is a hacked together kludge.  I make no warranties
        or guarantees about its usefulness, correctness, or suitability
        for any purpose.  If you use it, you use it at your own risk.

        Bobo is the property of Digital Creations, and this module is in
        no way intended to infringe on their rights to Bobo.

Freedoms:

        Anyone wanting to use this module for some reason is free to do
        so as far as I'm concerned.  You can recode it, turn it into
        windows wallpaper, read it backwards, whatever you feel like,
        just as long as you hold me blameless.
'''
id="$Id: win_wrap,v 1.2 1998/09/09 18:06:52 jim Exp $"
########## DATA SECTION ###########
BOILERPLATE = '''\
%(sitepython)s
#Auto-generated with: %(argsv)s
#Wrapper file built: %(timestring)s

import traceback, sys
try:
        sys.path[0:0] = ["%(workpath)s","%(workpath)s\\Components","%(workpath)s\\Components\\%(platform)s"]
%(fixiis)s

        import cgi_module_publisher
        cgi_module_publisher.publish_module("%(modulename)s")

except:
        print 'Content-type: text/plain\\n\\n'
        print 'An error occured in attempting to set up the environment for this application.'
%(allowtraceback)s
'''  # the skeleton file


allowtraceback = '''    print 'The python trace follows:'
        print traceback.print_exc()'''

fixiis = '''    ### HACK TO FIX IIS 3.0 PATH_INFO variable
        import string, os
        script = filter(None,string.split(string.strip(os.environ['SCRIPT_NAME']),'/'))
        path = filter(None, string.split( string.strip(os.environ['PATH_INFO']),'/'))
        os.environ['PATH_INFO'] = string.join(path[len(script):],'/')
        ### END IIS HACK''' # PATH_INFO includes the path to the script under some IIS versions, possibly all

sitepython = '''#!/usr/bin/env python''' # in case you're using Unix or a Unix shell

########## FUNCTIONAL SECTION ###########

import sys,os,string,time

def main(cgidirectory,fullpathofscript,sitepython=sitepython,fixiis=fixiis,allowtraceback=allowtraceback,autooverwrite=None):
        '''
        Determine the correct values for the substitution variables,
        load them into the local namespace.  Open the output file and
        write the BOILERPLATE template out substituting with the locals
        dictionary.
        '''
        # HEADER INFORMATION
        argsv= string.join(sys.argv,' ')
        timestring = time.asctime(time.localtime(time.time()))
        # workpath (in this simple version) is just fullpathofscript stripped of the module name
        if not os.path.isfile(fullpathofscript):
                sys.stderr.write('''Warning, couldn't find the target script''')
        workpath,modulename = os.path.split(fullpathofscript)
        workpath = string.join(string.split(workpath,'\\'),'\\\\')
        platform = sys.platform
        # module name needs to have the extension split off, if it's not py, then use the original
        tempval = os.path.splitext(modulename)
        if tempval[1] == '.py':
                modulename = tempval[0]
        # open the file, checking to see if it already exists
        if cgidirectory[-1] == '\\':
                cgidirectory = cgidirectory[:-1]
        outfile = cgidirectory+os.sep+modulename+'.py'
        if os.path.isfile(outfile) and not autooverwrite:
                if string.lower(raw_input('''Output file %s exists: Overwrite Y/<N> ? '''%outfile)) != 'y':
                        print '''Exiting with error'''
                        raise '''User Abort'''
        outfile_h = open(outfile,'w')
        outfile_h.write(BOILERPLATE%locals())

usage = '''win_wrap [options] cgi_directory full_path_to_module

Options:

  -sitepython "magic_for_unix"
        Magic text for your unix system if you are for some reason
        using this script on unix.
        Default is #!/usr/bin/env/python
        Note, if there is whitespace in your magic string,
                make sure to surround it in quotes.

  -fixiis
        Flag to include support for fixing the PATH_INFO bug on IIS
        Default is not to include support.

  -allowtraceback
        Flag whether to provide a traceback printout if the wrapper module fails
        Default is not to provide traceback printing.

  -autooverwrite
        Flag whether to automatically overwrite the destination file in your
        cgi directory
        Default is to prompt before overwrite

win_wrap creates a python module of the same name as the
full_path_to_module module in the cgi_directory.  This module
will handle the setup of an environment suitable for the
standard cgi_module_publisher.py of the Bobo package.
Mike Fletcher, 1997. Use at your own risk.
'''

if __name__ == '__main__':
        argset = sys.argv[1:]
        argdict = {'sitepython':sitepython,'fixiis':'','allowtraceback':'','autooverwrite':None}
        try:
                while argset[0][0] == '-':
                        if string.lower(argset[0]) == '-sitepython':
                                argdict['sitepython'] = argset[1]
                                argset = argset[2:]
                        elif string.lower(argset[0]) in ('-fixiis','-allowtraceback'):
                                # no allowtraceback really should kill the entire try set IMHO, but
                                # I suppose it's useful to get the info during the testing phase...
                                # of course, you should then be able to turn it off for security
                                # under hostile operating conditions.
                                name = string.lower(argset[0])[1:]
                                argdict[name] = globals()[name]
                                argset = argset[1:]
                        elif string.lower(argset[0]) == '-autooverwrite':
                                argdict['autooverwrite'] = 1
                                argset = argset[1:]
                        else:
                                sys.stderr.write('Invalid option:'+argset[0])
                                argset = argset[1:]
                if len(argset) != 2:
                        sys.stderr.write(usage)
                else:
                        apply(main, tuple(argset), argdict)
        except IndexError:
                sys.stderr.write(usage)

