import sys
import os
from Carbon import Res
import string
import cfmfile
import macfs


MACFREEZEPATH = os.path.join(sys.prefix, ":Mac:Tools:macfreeze")
if MACFREEZEPATH not in sys.path:
	sys.path.append(MACFREEZEPATH)

import buildtools
import macgen_bin

# XXX !!!
#sys.path.append('Titaantje:DevDev:python:reportlab')


def makeCompactDistro(script, output, template, module_dict=None, architecture='fat', debug=0):
	"""Replacement for macgen_bin.generate(), which was factored in such a
	way we can't reuse it as is (mea culpa)."""
	buildtools.DEBUG = debug  # sorry, this stuff is a mess...

	# try to remove old file
	try:
		os.remove(output)
	except:
		pass
	
	if module_dict is None:
		import macmodulefinder
		print "Searching for modules..."
		module_dict, missing = macmodulefinder.process(script, [], [], 1)
	
	if template is None:
		template = buildtools.findtemplate()
	corepath = macgen_bin.findpythoncore()
	
	dynamicmodules, dynamicfiles, extraresfiles = macgen_bin.findfragments(module_dict, architecture)
	
	print 'Adding "__main__"'
	buildtools.process(template, script, output, 0)
	
	outputref = Res.FSpOpenResFile(output, 3)
	try:
		Res.UseResFile(outputref)
		
		print "Adding Python modules"
		macgen_bin.addpythonmodules(module_dict)
		
		print "Adding PythonCore resources"
		macgen_bin.copyres(corepath, outputref, ['cfrg', 'Popt', 'GU\267I'], 1)
		
		print "Adding resources from shared libraries"
		for ppcpath, cfm68kpath in extraresfiles:
			if os.path.exists(ppcpath):
				macgen_bin.copyres(ppcpath, outputref, ['cfrg'], 1)
			elif os.path.exists(cfm68kpath):
				macgen_bin.copyres(cfm68kpath, outputref, ['cfrg'], 1)
		
		print "Fixing sys.path prefs"
		Res.UseResFile(outputref)
		try:
			res = Res.Get1Resource('STR#', 228) # from PythonCore
		except Res.Error: pass
		else:
			res.RemoveResource()
		# setting pref file name to empty string
		res = Res.Get1NamedResource('STR ', "PythonPreferenceFileName")
		res.data = macgen_bin.Pstring("")
		res.ChangedResource()
		syspathpref = "$(APPLICATION)"
		res = Res.Resource("\000\001" + macgen_bin.Pstring(syspathpref))
		res.AddResource("STR#", 229, "sys.path preference")
		
		print "Creating 'PYD ' resources"
		for modname, (ppcfrag, cfm68kfrag) in dynamicmodules.items():
			res = Res.Resource(macgen_bin.Pstring(ppcfrag) + macgen_bin.Pstring(cfm68kfrag))
			id = 0
			while id < 128:
				id = Res.Unique1ID('PYD ')
			res.AddResource('PYD ', id, modname)
	finally:
		Res.CloseResFile(outputref)
	print "Merging code fragments"
	cfmfile.mergecfmfiles([template, corepath] + dynamicfiles.keys(), 
			output, architecture)
	
	macfs.FSSpec(output).SetCreatorType("????", "shlb")
	print "done!"



makeCompactDistro(
		":mmm.py",
		"Diagra.slb",
		":rl_embed_std.slb",
)
