#!/usr/bin/make

KVERSION=$(shell uname -r)
KERNEL_DIR=/lib/modules/$(KVERSION)/build

DESTDIR=/usr/local
#INSTALL_MOD_PATH:=/tmp

# Add compressloop when it has been fixed
APPS=create_compressed_fs extract_compressed_fs

CFLAGS:=-Wall -Wstrict-prototypes -Wno-trigraphs -O2 -s -I. -fno-strict-aliasing -fno-common -fomit-frame-pointer

all: utils module
install: install-utils install-module

utils: $(APPS)

install-utils: utils
	mkdir -p $(DESTDIR)/bin
	install -m0755 $(APPS) $(DESTDIR)/bin

create_compressed_fs: advancecomp-1.14/advfs
	ln -f $< $@

advancecomp-1.14/advfs: advancecomp-1.14/config.status
	$(MAKE) -C advancecomp-1.14 advfs

advancecomp-1.14/config.status: advancecomp-1.14
	cd advancecomp-1.14 && ./configure

#advancecomp-1.14:
#	bzcat advancecomp-1.14.tar.bz2 | tar -f - -x
#	cd advancecomp-1.14 && bzcat ../advfs-1.14.diff.bz2 | patch -p1

clean:
	rm -rf create_compressed_fs extract_compressed_fs zoom *.o *.ko *.mod.c .*cmd .tmp*
	-$(MAKE) -C advancecomp-1.14 distclean
	rm -f */config.status */config.log tmp

extract_compressed_fs: extract_compressed_fs.o
	$(CC) -o $@ $< -lz

dist: clean
	cd .. ; \
	tar -cf - cloop/{Makefile,*.[ch],CHANGELOG,README} | \
	bzip2 -9 > $(HOME)/redhat/SOURCES/cloop.tar.bz2

# to build packages for Knoppix
packages:
	fakeroot debian/rules binary
	cp -a . ../tmp-cloop-modbuild
	cd ../tmp-cloop-modbuild && fakeroot debian/rules binary-modules && rm -rf ../tmp-cloop-modbuild
	
ifeq ($(shell grep 'UTS.*"2\.6' $(KERNEL_DIR)/include/linux/version.h),)
# oh, oh, a kernel 2.4 style build
#
# try reading kernel configs, ignore if not available
-include $(KERNEL_DIR)/.config
-include $(KERNEL_DIR)/conf.vars
MODVER := $(shell test -f $(KERNEL_DIR)/include/linux/modversions.h && echo -DMODVERSIONS --include $(KERNEL_DIR)/include/linux/modversions.h)
CKERNOPS :=  -D__KERNEL__ -DMODULE -O2 -fno-builtin -nostdlib -DKBUILD_MODNAME="cloop" -DKBUILD_BASENAME="cloop" -pipe -DEXPORT_SYMTAB -I$(KERNEL_DIR)/include $(MODVER)

# Check for SMP in config and #define __SMP__ if necessary.
# This is ESSENTIAL when compiling a SMP version of cloop.o
# Otherwise, the module will block the entire block buffer management on read.

ifdef CONFIG_SMP
CKERNOPS += -D__SMP__
endif

module: cloop.o
cloop.o: compressed_loop.c compressed_loop.h
	$(CC) $(CFLAGS) $(CKERNOPS) $(CFLAGS_$@) -o cloop.o -c compressed_loop.c

install-module: module
	cp cloop.o $(INSTALL_MOD_PATH)/lib/modules/$(KVERSION)/kernel/drivers/extra

else

EXTRA_CFLAGS := -I $(KERNEL_DIR)/include/asm/mach-default 

obj-m := cloop.o
cloop-objs := compressed_loop.o

module: compressed_loop.h compressed_loop.c
	$(MAKE) modules -C $(KERNEL_DIR) M=$(CURDIR) KERNELRELEASE=$(KVERSION)

install-module: module
	$(MAKE) modules_install -C $(KERNEL_DIR) M=$(CURDIR) KERNELRELEASE=$(KVERSION)

endif
