# Copyright(c) 2013 OMICRON electronics GmbH. All rights reserved.

# We switch on endian checking.  This means that when we run sparse,
# we are a little more choosy about endian-ness.
OMIPPC_PWR_FAIL_CFLAGS += -D__CHECK_ENDIAN__

BLDDIR = build

# Set to 'y' to enable Xenomai optimizations, 'n' otherwise
XENO ?= n

ifneq ($(KERNELRELEASE),)

obj-m += omippc_pwr_fail.o

omippc_pwr_fail-objs := omippc_pwr_fail_drv.o

KBUILD_CFLAGS += $(OMIPPC_PWR_FAIL_CFLAGS)

else

# Try to detect correct build settings automatically
ifneq (,$(findstring powerpc,$(shell $(CC) -dumpmachine)))
AUTO_ARCH      = powerpc
AUTO_KERNELDIR = $(shell cd `$(CC) -print-sysroot`/../usr/src/linux-headers-* && pwd)
AUTO_TOOLCHAIN = $(CC:gcc=)

# Xenomai Kernel optimizations
ifeq ($(XENO),y)

XENO_ROOT    =
XENO_CONF    = $(XENO_ROOT)/usr/xenomai/bin/xeno-config
OMIPPC_PWR_FAIL_CFLAGS += -DXENO_CONFIG

override CC    = $(shell DESTDIR=$(XENO_ROOT) $(XENO_CONF) --cc --skin=posix --cflags --ldflags)
override CXX   = $(AUTO_CC)
XENO_CFLAGS    = -O2 -lnative -lrtdm
else
AUTO_CC        = $(AUTO_TOOLCHAIN)gcc
AUTO_CXX       = $(AUTO_TOOLCHAIN)g++
endif

else
AUTO_CC   = gcc
AUTO_CXX  = g++
AUTO_ARCH = x86
AUTO_KERNELDIR = /lib/modules/$(shell uname -r)/build
AUTO_TOOLCHAIN =
endif

# Auto settings can be overwritten from command line
CC        ?= $(AUTO_CC)
CXX       ?= $(AUTO_CXX)
ARCH      ?= $(AUTO_ARCH)
KERNELDIR ?= $(AUTO_KERNELDIR)
TOOLCHAIN ?= $(AUTO_TOOLCHAIN)

PROGS      = detect_pwr_fail
OBJS       = 

CHECKFILES = detect_pwr_fail.c omippc_pwr_fail_drv.c

RESULTS    = omippc_pwr_fail.ko detect_pwr_fail

# TODO Find better solution for the clean workaround
all: clean module userland
	mkdir -p $(OBJDIR)
	cp -r $(RESULTS) $(OBJDIR)

CFLAGS = -Wall -Wextra $(OMIPPC_PWR_FAIL_CFLAGS) $(XENO_CFLAGS) -D_GNU_SOURCE \
		 -iquote$(KERNELDIR)/include -iquote$(KERNELDIR)/usr/include -O9

OBJDIR ?= $(addprefix $(BLDDIR)-,$(shell $(CXX) -dumpmachine | sed -e "s/-.*//"))

module:
	$(MAKE) -C $(KERNELDIR) ARCH=$(ARCH) CROSS_COMPILE=$(TOOLCHAIN) M=$(CURDIR) modules

userland: $(PROGS)

detect_pwr_fail: detect_pwr_fail.o
	$(LINK.c) $^ -o $@

clean:
	rm -f *.o
	rm -f *.mod.c
	rm -f .*.cmd
	rm -f test/*.pyc
	rm -rf .tmp_versions

distclean: clean
	rm -f $(PROGS)
	rm -f *.ko
	rm -f Module.symvers
	rm -f modules.order
	rm -f Module.markers
	rm -rf $(BLDDIR)*

checkstyle:
	$(KERNELDIR)/scripts/checkpatch.pl --file $(CHECKFILES) --no-tree --emacs --terse

runtests:
#	nosetests -v -a cf,type=ut,pph=none -a cf,type=ut,pph=loopback

runtests_bclamp:
#	nosetests -v -a cf,type=ut,pph=none -a cf,type=ut,pph=loopback -a cf,type=ut,pph=bclamp

runtests_ltt:
#	nosetests -v -a cf,type=ltt,pph=none -a cf,type=ltt,pph=loopback

disasm: module
	objdump -S omippc_pwr_fail.ko > omippc_pwr_fail.disasm

TARGET ?= /tmp

install:
ifndef IP
	$(error No IP address given, e.g. make install IP=172.1.1.1)
endif
	scp -r $(RESULTS) root@$(IP):$(TARGET)

endif
