1a066f
#!/usr/bin/python
1a066f
#
1a066f
# createmodule.py - Takes the name of a environment init script and 
1a066f
# produces a modulefile that duplicates the changes made by the init script
1a066f
#
1a066f
# Copyright (C) 2012 by Orion E. Poplawski <orion@cora.nwra.com>
1a066f
#
1a066f
# This program is free software: you can redistribute it and/or modify
1a066f
# it under the terms of the GNU General Public License as published by
1a066f
# the Free Software Foundation, either version 2 of the License, or
1a066f
# (at your option) any later version.
1a066f
1a066f
# This program is distributed in the hope that it will be useful,
1a066f
# but WITHOUT ANY WARRANTY; without even the implied warranty of
1a066f
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1a066f
# GNU General Public License for more details.
1a066f
1a066f
# You should have received a copy of the GNU General Public License
1a066f
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
5352b7
from __future__ import print_function
1a066f
1a066f
from optparse import OptionParser
5352b7
import os,sys,re
1a066f
from subprocess import *
1a066f
1a066f
# Handle options
1a066f
usage = "Usage: %prog [-p prefix] <initscript> [args]"
1a066f
parser = OptionParser()
1a066f
parser.set_usage(usage)
5352b7
parser.add_option('-p', '--prefix', action='store', type='string', dest='prefix', help='Specify path prefix')
5352b7
parser.add_option('--noprefix', action='store_true', dest='noprefix', default=False, help='Do not generate a prefix')
1a066f
(options, args) = parser.parse_args()
1a066f
1a066f
# Need a script name
1a066f
if not args:
1a066f
    parser.print_usage()
1a066f
    exit(1)
1a066f
1a066f
# Return environment after a command
1a066f
def getenv(cmd = ':'):
1a066f
    env = {}
1a066f
    p = Popen(cmd + ";env", shell=True, stdout=PIPE, stderr=PIPE)
1a066f
    (stdout, stderr) = p.communicate()
1a066f
    if p.returncode != 0:
5352b7
        print("EROR: Could not execute initscript:")
5352b7
        print("%s returned exit code %d" % (cmd, p.returncode))
5352b7
        print(stderr)
1a066f
        exit(1)
1a066f
    if stderr != '':
5352b7
        print("WARNING: initscript sent the following to stderr:")
5352b7
        print(stderr)
1a066f
    # Parse the output key=value pairs
5352b7
    skip = False
1a066f
    for line in stdout.splitlines():
5352b7
        if skip:
5352b7
            if line == '}':
5352b7
                skip = False
5352b7
            continue
1a066f
        try:
1a066f
            (var,value) = line.split('=',1)
1a066f
        except ValueError:
5352b7
            print("ERROR: Could not parse output line:")
5352b7
            print(line)
1a066f
            exit(1)
5352b7
        # Exported functions - not handled
5352b7
        if value.find('() {') == 0:
5352b7
            skip = True
5352b7
        else:
5352b7
            env[var] = value
1a066f
    return env
1a066f
1a066f
#Record initial environment
1a066f
env1=getenv()
1a066f
1a066f
#Record environment after sourcing the initscript
1a066f
env2=getenv(". " + " ".join(args))
1a066f
1a066f
# Initialize our variables for storing modifications
1a066f
chdir = None
1a066f
appendpath = {}
1a066f
prependpath = {}
5352b7
unhandled = {}
1a066f
setenv = {}
1a066f
unsetenv = []
1a066f
pathnames = []
1a066f
1a066f
# Function to nomalize all paths in a list of paths and remove duplicate items
1a066f
def normpaths(paths):
1a066f
    newpaths = []
1a066f
    for path in paths:
1a066f
        normpath = os.path.normpath(path)
5352b7
        if normpath not in newpaths and normpath != '.':
1a066f
             newpaths.append(os.path.normpath(path))
1a066f
    return newpaths
1a066f
1a066f
# Start with existing keys and look for changes
1a066f
for key in env1.keys():
1a066f
    # Test for delete
1a066f
    if key not in env2:
1a066f
        unsetenv.append(key)
1a066f
        continue
1a066f
    # No change
1a066f
    if env1[key] == env2[key]:
1a066f
        del env2[key]
1a066f
        continue
1a066f
    #Working directory change
1a066f
    if key == 'PWD':
1a066f
	chdir=os.path.normpath(env2[key])
1a066f
        pathnames.append(chdir)
1a066f
        del env2[key]
1a066f
        continue
1a066f
    # Determine modifcations to beginning and end of the string
5352b7
    try:
5352b7
        (prepend,append) = env2[key].split(env1[key])
5352b7
    except ValueError:
5352b7
         continue
1a066f
    if prepend:
5352b7
        presep = prepend[-1:]
5352b7
        prependpaths = prepend.strip(presep).split(presep)
1a066f
        # LICENSE variables often include paths outside install directory
1a066f
        if 'LICENSE' not in key:
1a066f
            pathnames += prependpaths
5352b7
        if presep not in prependpath:
5352b7
            prependpath[presep] = {}
5352b7
        newpath = presep.join(normpaths(prependpaths))
5352b7
        if newpath:
5352b7
            prependpath[presep][key] = newpath
5352b7
        else:
5352b7
            unhandled[key] = env2[key]
1a066f
    if append:
5352b7
        appsep = append[0:1]
5352b7
        appendpaths = append.strip(appsep).split(appsep)
1a066f
        # LICENSE variables often include paths outside install directory
1a066f
        if 'LICENSE' not in key:
1a066f
            pathnames += appendpaths
5352b7
        if appsep not in appendpath:
5352b7
            appendpath[appsep] = {}
5352b7
        newpath = appsep.join(normpaths(appendpaths))
5352b7
        if newpath:
5352b7
            appendpath[appsep][key] = newpath
5352b7
        else:
5352b7
            unhandled[key] = env2[key]
1a066f
    del env2[key]
1a066f
      
1a066f
# We're left with new keys in env2
1a066f
for key in env2.keys():
1a066f
    # Use prepend-path for new paths
5352b7
    if (re.search('(DIRS|FILES|PATH)$',key)) or (':' in env2[key]):
1a066f
        prependpaths = env2[key].strip(':').split(':')
1a066f
        # MANPATH can have system defaults added it it wasn't previously set
1a066f
        # LICENSE variables often include paths outside install directory
1a066f
        if key != 'MANPATH' and 'LICENSE' not in key:
1a066f
            pathnames += prependpaths
5352b7
        if ':' not in prependpath:
5352b7
            prependpath[':'] = {}
5352b7
        prependpath[':'][key] = ':'.join(normpaths(prependpaths))
1a066f
        continue
1a066f
    # Set new variables
1a066f
    setenv[key] = os.path.normpath(env2[key])
1a066f
    if 'LICENSE' not in key:
1a066f
        pathnames.append(setenv[key])
1a066f
5352b7
# Report unhandled keys
5352b7
for key in unhandled.keys():
5352b7
    print("Unhandled change of", key, file=sys.stderr)
5352b7
    print("Before <%s>" % env1[key], file=sys.stderr)
5352b7
    print("After <%s>" % unhandled[key], file=sys.stderr)
5352b7
    for sepkey in appendpath.keys():
5352b7
        appendpath[sepkey].pop(key, None)
5352b7
    for sepkey in prependpath.keys():
5352b7
        prependpath[sepkey].pop(key, None)
5352b7
1a066f
# Determine a prefix
5352b7
prefix=None
1a066f
if options.prefix:
1a066f
    prefix = options.prefix
5352b7
elif not options.noprefix:
1a066f
    prefix = os.path.commonprefix(pathnames).rstrip('/')
1a066f
    if prefix == '':
1a066f
          prefix = None
1a066f
1a066f
# Print out the modulefile
5352b7
print("#%Module 1.0")
1a066f
1a066f
# Prefix
1a066f
if prefix is not None:
5352b7
    print("\nset prefix " + prefix + "\n")
1a066f
1a066f
# Chdir
1a066f
if chdir is not None:
5352b7
    print("chdir\t" + chdir)
1a066f
1a066f
# Function to format output line with tabs and substituting prefix
1a066f
def formatline(item, key, value=None):
5352b7
    print(item, end=' ')
5352b7
    print("\t"*(2-(len(item)+1)/8), end=' ')
5352b7
    print(key, end=' ')
1a066f
    if value is not None:
5352b7
        print("\t"*(3-(len(key)+1)/8), end=' ')
1a066f
        if prefix is not None:
5352b7
            print(value.replace(prefix,'$prefix'))
1a066f
        else:
5352b7
            print(value)
1a066f
1a066f
# Paths first, grouped by variable name
5352b7
for sepkey in prependpath.keys():
5352b7
    pathkeys = prependpath[sepkey].keys()
5352b7
    pathkeys.sort()
5352b7
    for key in pathkeys:
5352b7
        if sepkey == ":":
5352b7
            formatline("prepend-path",key,prependpath[sepkey][key])
5352b7
        else:
5352b7
            formatline("prepend-path --delim %s" % sepkey,key,prependpath[sepkey][key])
5352b7
5352b7
for sepkey in appendpath.keys():
5352b7
    pathkeys = appendpath[sepkey].keys()
5352b7
    pathkeys.sort()
5352b7
    for key in pathkeys:
5352b7
        if sepkey == ":":
5352b7
            formatline("append-path",key,appendpath[sepkey][key])
5352b7
        else:
5352b7
            formatline("append-path --delim %s" % sepkey,key,appendpath[sepkey][key])
1a066f
1a066f
# Setenv
5352b7
setenvkeys = list(setenv.keys())
1a066f
setenvkeys.sort()
1a066f
if setenvkeys:
5352b7
    print()
1a066f
for key in setenvkeys:
1a066f
    formatline("setenv",key,setenv[key])
1a066f
1a066f
# Unsetenv
1a066f
unsetenv.sort()
1a066f
if unsetenv:
5352b7
    print()
1a066f
for key in unsetenv:
1a066f
    formatline("unsetenv",key)