#!/usr/local/bin/konoha
/*
 * gen_make.k
 * masahiro@ynu 2009
 *
 * generator for kernel makefile.
 *
 * how to use;
 * $ cd /path/to/konoha/
 * $ konoha ./gensrc/gen_automake.k
 * and then, i generate Makefile
 */


import "walk.k"

DEV_NAME = "konohadev";
MAKEFILE = "Makefile";
SRC_DIR  = "./src";

int main(String[] args)
{
    /*
   */
    OutputStream o = new OutputStream(MAKEFILE,"w");
    o.println("# ")
    o.println("# Automagically generated file. Do not edit! ");
    o.println("# generated by gensrc/gen_make.k");
    o.println("# ");
    o.println("");
    o.println(%("obj-m:= %s{0}.o",DEV_NAME));
    o.println(%("%s{0}-objs := \\",DEV_NAME));

    String[] array = System.walk(SRC_DIR);
    for(i=0;i<|array|;i++){
        line = array[i];
        // 
        // filter
        if(line.indexOf(".svn") >= 0) continue;
        if(line.indexOf("/.") >= 0) continue;
        if(line.indexOf("src/ext/mt") >= 0) continue;
        if(line.indexOf(".c") < 0) continue;
        if(line == "./src/konoha.c") continue;

        o.println(%("%s{0} \\",line.replace(".c",".o")));
    }
    o.println("");
    o << """
KDIR  := /lib/modules/$(shell uname -r)/build
PWD   := $(shell pwd)
KBUILD_CFLAGS += -DKONOHA_ON_LKM
KBUILD_CFLAGS += -Wno-declaration-after-statement
VERBOSE=0
""";
    o.println(%("KBUILD_CFLAGS += -I%s{0}/include/",$env.PWD));

    o << """
default:
	$(MAKE) -C $(KDIR) SUBDIRS=$(PWD) modules KBUILD_VERBOSE=$(VERBOSE)

install-lkm:
	/sbin/insmod ./konohadev.ko  || exit 1

install:install-lkm
	rm -f /dev/konoha
	mknod /dev/konoha c $(shell awk "\$$2==\\"konohadev\\" {print \$$1}" /proc/devices) 0
	chgrp wheel /dev/konoha
	chmod 666   /dev/konoha

uninstall:
	/sbin/rmmod konohadev


clean:
	rm -f *.o *.ko *.mod.c  *~ *.cmd .*.ko.cmd
	rm -f ./modules.order ./Module.* ./.konohadev.* 
	rm -rf .tmp_versions
	rm -f ./src/.*.o.cmd  ./src/*.o
	rm -f ./src/main/.*.o.cmd  ./src/main/*.o
	rm -f ./src/api/.*.o.cmd  ./src/api/*.o
	rm -f ./src/class/.*.o.cmd ./src/class/*.o
	rm -f ./src/ext/.*.o.cmd ./src/ext/*.o
	rm -f ./src/labs/.*.o.cmd ./src/labs/*.o
	rm -f ./src/gen/.*.o.cmd ./src/gen/*.o
	rm -f ./src/deps/.*.o.cmd ./src/deps/*.o
	rm -f ./src/compiler/.*.o.cmd ./src/compiler/*.o

""";
    o.close();
    return 0;
}
