#!/usr/bin/python
import os, os.path, sys

#########################################################


LIBS = {
	'curl': '-lcurl'
}

def write_libs(f, pkgname):
	libs = ''
	if LIBS.has_key(pkgname): libs = LIBS[pkgname]
	fmt = '''
# %s
%slibs = %s ''' % (pkgname, pkgname, libs)
	f.write(fmt)
	
def write_gcc_o(f, pkgname, pkgpath):
	fmt = '''
$PKGNAME.o : 
	$(CC) $(CFLAGS) -I"konoha-0.3/include" -o$PKGNAME.o -c "$PKGPATH/$PKGNAME.c"

'''
	fmt = fmt.replace('$PKGNAME', pkgname).replace('$PKGPATH', pkgpath)
	f.write(fmt)

def write_gcc_dylib(f, pkgname, pkgpath):
	fmt = '''

$PKGPATH/$PKGNAME.dylib : $PKGNAME.o
	$(CC) -dynamiclib -o $PKGPATH/$PKGNAME.dylib $PKGNAME.o -lkonoha $(%slibs)

'''
	fmt = fmt.replace('$PKGNAME', pkgname).replace('$PKGPATH', pkgpath)
	f.write(fmt % pkgname)

def write_gcc_tar(f, pkgname, pkgpath):
	fmt = '''
$PKGPATH.tar.gz : 
	$(RM) -rf $PKGPATH.tar.gz
	tar zcfv $PKGPATH.tar.gz $PKGPATH/$PKGNAME*

'''
	fmt = fmt.replace('$PKGNAME', pkgname).replace('$PKGPATH', pkgpath)
	f.write(fmt)

def write_gcc_macosx(f, pkgname, pkgpath):
	fmt = '''$PKGPATH/$PKGNAME.dylib\\\n\t'''
	fmt = fmt.replace('$PKGNAME', pkgname).replace('$PKGPATH', pkgpath)
	f.write(fmt)

def write_gcc_dist(f, pkgname, pkgpath):
	fmt = '''$PKGPATH.tar.gz\\\n\t'''
	fmt = fmt.replace('$PKGNAME', pkgname).replace('$PKGPATH', pkgpath)
	f.write(fmt)

def gen_makefile(bdir, pkgpaths):
	f = open(bdir + '/Makefile', 'w')
	f.write('''# Makefile generated by gen_pkgmake.py by Kimio

CC = gcc
CFLAGS = -O2 -g -Wall -fPIC

''')

	f.write('''
dylibs =''')
	for pkgpath in pkgpaths:
		pkgname = pkgpath.split('-')[0]
		write_gcc_macosx(f, pkgname, pkgpath)
	
	f.write('''

tarfiles =''')
	for pkgpath in pkgpaths:
		pkgname = pkgpath.split('-')[0]
		write_gcc_dist(f, pkgname, pkgpath)

	for pkgpath in pkgpaths:
		pkgname = pkgpath.split('-')[0]
		write_libs(f, pkgname)
		write_gcc_dylib(f, pkgname, pkgpath)
		write_gcc_o(f, pkgname, pkgpath)
		write_gcc_tar(f, pkgname, pkgpath)

	f.write('''

.PHONY: macosx
macosx: $(dylibs)

.PHONY: dist
dist: $(tarfiles)

.PHONY: clean
clean:
	$(RM) -rf $(dylibs) $(tarfiles) *.o

''')
	f.close()

def read_pkgpaths(bdir):
	pkgpaths = []
	for fn in os.listdir(bdir):
		if fn.startswith('.') or fn.startswith('konoha-'): continue
		if fn.find('-') == -1: continue 
		if not os.path.isdir(bdir +'/' + fn): continue
		print fn
		pkgpaths.append(fn)
	return pkgpaths

#############

if __name__ == '__main__':
	bdir = '../..'
	pkgpaths = read_pkgpaths(bdir)
	gen_makefile(bdir, pkgpaths)
