#!/usr/bin/python
import os, os.path, sys
#from template import *
from pygenlib  import *

CC='gcc'
CFLAGS='-O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP'

bdir = '..'

def add_clists(dir, fn, clists):
	cpath = dir + '/' + fn
	if cpath.startswith('../'):
		cpath = cpath.replace('../', '')
	oname = cpath.split('/')[-1].replace('.c', '.o')
	clists.append((cpath, oname))

def find_c(dir, clists):
	fl = os.listdir(dir)
	for fn in fl:
		if fn.startswith('.'): continue
		if fn.startswith('_'): continue
		if fn.endswith('.c'): 
			add_clists(dir, fn, clists)
		if os.path.isdir(dir + '/' + fn):
			find_c(dir + '/' + fn, clists)

def gen_make(f, bdir):
	clists = []
	find_c(bdir, clists)
	objs = ''
	for cf in clists:
		objs += '%s ' % cf[1]

	f.write('''# makefile for konoha

CC = gcc
CFLAGS = -g -Wall -O2
#LDLIBS = -lm -ldl

program = konoha
objs = %s

.PHONY: all
all: $(program)

$(program): $(objs)
	$(CC) -o $(program) $^ $(LDLIBS)

.PHONY: clean
clean:
	$(RM) $(program) $(objs)

''' % objs)

	for cf in clists:
		f.write('''
%s : ../%s
	$(CC) $(CFLAGS) -I"../include" -c "../%s"
''' % (cf[1], cf[0], cf[0]))

f = open('makefile', 'w')
gen_make(f, '..')
f.close()
