#!/boot/home/config/bin/python
#
#   Build makefile for the present module collection.
#   Includes platform specific (PPC vs Intel) link options, depending
#   on posix.uname().
#
#   Handles both .dx and .cpp module source files.
#
#   This can be run frequently, as long as you don't need to modify it
#   by hand afterwards (ideally, if you need to change something, you
#   might start with head.mk.)  Should happen if you just type "make"
#   with the default Makefile.  I find it painlessly quick even on my
#   BeBox.
#
import posix
import string
import sys

class Platform:
	def __init__(self):
		#
		#  Which source directory to use?  Current, or older?
		#
		sys, node, rel, ver, mach = posix.uname()
		if rel[:1] == '5':
			self.srcdir = '../source'
		else:
			#  Older versions, 4.5.2 and probably earlier.
			self.srcdir = '../source4'
		if mach == 'BePC':
			self.ldso = '-nostart -Wl -o $@ $< $(BASEOBJS) $(LIBS)'
		else:
			self.ldso = '-xms -nodup -export init$* $< $(BASEOBJS) -o $@ /boot/develop/lib/ppc/glue-noinit.a /boot/develop/lib/ppc/init_term_dyn.o $(LIBS)'

platform = Platform()

class CSource:
	def __init__(self, file):
		self.cfile = file
		self.getmodulename(file)

	def prdeps(self, fp):
		nm = self.module
		fp.write('%smodule.so: %s.o $(BASEOBJS)\n' % (nm, nm))
		fp.write('%s.o: %s $(BASEINCL)\n' % (nm, self.cfile))

	def getmodulename(self, filename):
		filename = string.split(filename, '/')[-1]
		base, suffix = string.split(filename, '.')
		self.module = base

class DSource(CSource):
	def __init__(self, file):
		self.dfile = file
		self.getmodulename(file)
		self.cfile = self.module + '.cpp'

	def prdeps(self, fp):
		CSource.prdeps(self, fp)
		fp.write('%s: %s $(GENDEPS)\n' % (self.cfile, self.dfile))

def mkhead(fp):
	fp.write('# Generated by mkmake\n')
	fp.write('\ninclude head.mk\n')
	fp.write('\nVPATH=%s\n' % (platform.srcdir,))
	fp.write('\n.omodule.so:\n')
	fp.write('\t$(CC) %s\n\n' % (platform.ldso,))

def inventory():
	sources = []
	for file in posix.listdir(platform.srcdir):
		file = '%s/%s' % (platform.srcdir, file)
		if file[-4:] == '.cpp':
			s = CSource(file)
		elif file[-3:] == '.dx':
			s = DSource(file)
		else:
			continue
		sources.append(s)
	return sources

def main():
	#  Get list of all source files.
	sources = inventory()

	makefile = open('xmakefile', 'w')
	mkhead(makefile)

	#  Make default target, all modules.

	makefile.write('all: ')
	for source in sources:
		makefile.write(' %smodule.so' % source.module)
	makefile.write('\n\ninstall: all\n	./install\n\n')

	#  Make target for each module and dependencies.
	for source in sources:
		source.prdeps(makefile)
	makefile.close()

main()
