# Minimal makefile for a one-file kernel module which uses the same
# source for 2.4 and 2.6 kernels.

ifeq ($(KERNELRELEASE),)

# This fragment chains to the toplevel kernel makefile to set flags
# and such...

# If $(KSRC) is not writable, then prevent the kernel Makefile
# from trying to remake include/config/MARKER (this is a problem
# with at least some Debian kernel-headers packages). However,
# finding out whether we can write to $(KSRC) is tricky because
# we may be running under fakeroot.
#
# The trick of the below code is that the standalone test binary uses
# access() which is immune to fakeroot, whereas most shells use
# stat(), which is. At least that happens with GNU coreutils. The
# old shellutils use stat() even in /usr/bin/test, but you can't win
# always.
#
# On systems where this strategy does not work, one has to not use
# fakeroot for the build stage when the kernel source directory is
# not readable.

build: build-stamp
build-stamp: Makefile vaiostat.c vaiostat.h
	$(RM) build-stamp
	[ -x /bin/test ] || plususr=/usr ; \
	$$plususr/bin/test -w $(KSRC)/include/config || \
		plus='-o include/config/MARKER' ; \
	$(MAKE) -C $(KSRC) SUBDIRS=$(shell pwd) $$plus modules
clean:
	$(RM) *.o *.ko *.mod.c .*.cmd
	$(RM) build-stamp
	$(RM) -r .tmp_versions

.PHONY: build clean

# The 'install' target of the original Makefile used uname -r to find
# the release part of the directory to install into. This does not work
# when building for another kernel than the currently running one. So
# we sneakily write the correct release into build-stamp during the
# build phase and retrieve it again here
PREFIX=
INSTDIR=$(PREFIX)/lib/modules
INSTALL=install -D -m644
install: build-stamp
	release=`cat build-stamp` ; \
	case $$release in 2.[01234].*) ext=o ;; *) ext=ko ;; esac ; \
	$(INSTALL) vaiostat.$$ext $(INSTDIR)/$$release/misc/vaiostat.$$ext

else

ifneq ($(KBUILD_EXTMOD),)

# This fragment is for building on 2.6 kernels; tested with 2.6.8.
# We get a lot of magic build machinery from the main kernel tree
# for free, and only need to specify what to build.

obj-m := vaiostat.o

else

# This fragment is for building on 2.4 kernels; tested with 2.4.27
# The main kernel tree has invoked this file with appropriate
# CFLAGS overrides and a target of 'modules', so we can leave
# the actual compilation to the built-in .c.o rule. Again we
# need only specify which files to build.

.PHONY: modules
modules: ./vaiostat.o

src=.
obj=.

endif

$(src)/vaiostat.c: $(obj)/build-stamp

$(obj)/build-stamp:
	echo $(KERNELRELEASE) > $@

endif
