DESCR = "Linux with PerfCtr $(VERSION) patch and library"

ifneq (/usr,$(PERFCTR_PREFIX))
PWD = $(shell pwd)
ifeq (,$(PERFCTR_LIB_PATH))
ifeq (,$(PERFCTR_ROOT))
	PERFCTR_ROOT := $(PWD)/perfctr-$(VERSION)
endif
	PERFCTR_LIB_PATH := $(PERFCTR_ROOT)/usr.lib
	CC_SHR += -Wl,-rpath-link -Wl,$(PERFCTR_LIB_PATH)
endif
ifeq (,$(PERFCTR_INC_PATH))
ifeq (,$(PERFCTR_ROOT))
	PERFCTR_ROOT := $(PWD)/perfctr-$(VERSION)
endif
	PERFCTR_INC_PATH := $(PERFCTR_ROOT)/usr.lib
	PERFCTR_KINC_PATH := $(PERFCTR_ROOT)/linux/include
else
	PERFCTR_KINC_PATH := $(PERFCTR_INC_PATH)
endif
ifneq (/usr/include,$(PERFCTR_INC_PATH))
CFLAGS += -I$(PERFCTR_INC_PATH) 
endif
ifneq (/usr/include/linux/include,$(PERFCTR_KINC_PATH))
CFLAGS += -I$(PERFCTR_KINC_PATH) 
endif
endif

CFLAGS-2.6.x := -DPERFCTR26
CFLAGS-2.7.x := $(CFLAGS-2.6.x)
CFLAGS += $(CFLAGS-$(VERSION))
MISCHDRS += linux-lock.h mb.h
MISCSRCS +=  $(ARCH_SPEC_EVTS)
SHLIBDEPS = -Bdynamic -L$(PERFCTR_LIB_PATH) -lperfctr
PERFCTR_OBJS = $(shell $(AR) t $(PERFCTR_LIB_PATH)/libperfctr.a 2> /dev/null)
MISCOBJS = $(PERFCTR_OBJS) $(MISCSRCS:.c=.o) 

ifeq (,$(PERFCTR_OBJS))
$(PERFCTR_LIB_PATH)/libperfctr.a:
ifneq (,${PERFCTR_ROOT})
 ifeq (ppc64,${ARCH})
	$(MAKE) CC='$(CC) $(BITFLAGS)' -C $(PERFCTR_ROOT)
 endif
 ifeq (x86_64,${ARCH})
   ifeq (-m32,${BITFLAGS})
	$(MAKE) CC='$(CC) $(BITFLAGS)' LD_FLAGS="-melf_i386" ARCH="i386" -C $(PERFCTR_ROOT)
   else
	$(MAKE) -C $(PERFCTR_ROOT)
   endif
 else
	$(MAKE) -C $(PERFCTR_ROOT)
 endif
else
	@echo '$@ not installed!'; exit 1
endif
	$(MAKE)
endif

#Dynamic linking loader needs correct version of libperfctr
ifeq ($(VERSION),2.7.x)
	SO_ABIVER=6
else
ifeq ($(VERSION),2.6.x)
	i386_ABIVER=5
	x86_64_ABIVER=6
	ppc_ABIVER=5
	SO_ABIVER=$($(ARCH)_ABIVER)
endif
endif

POST_BUILD = cp $(PERFCTR_LIB_PATH)/libperfctr.so .;ln -fs libperfctr.so libperfctr.so.$(SO_ABIVER)

include Makefile.inc

config.h:
	@echo 'Please clobber your build and run ./configure. Direct Makefile access has been deprecated.'

$(PERFCTR_OBJS): $(PERFCTR_LIB_PATH)/libperfctr.a
	$(AR) xv $<
	
$(CPU)_events.o: $(CPU)_events.c $(HEADERS)
	$(CC) $(LIBCFLAGS) $(OPTFLAGS) -c $(CPU)_events.c -o $@

#perfctr.o: perfctr.c $(HEADERS)
#	$(CC) $(LIBCFLAGS) $(OPTFLAGS) -c perfctr.c -o $@

native_clean:
	-rm -f $(MISCOBJS) libperfctr.so*
ifneq (,${PERFCTR_ROOT})
	$(MAKE) -C $(PERFCTR_ROOT) clean
endif

native_install: 
ifeq ($(ARCH),ppc64)
	-mkdir -p $(DESTDIR)$(DATADIR)
	-chmod go+rx $(DESTDIR)$(DATADIR)
	cp -Rf ./event_data $(DESTDIR)$(DATADIR)
endif
ifneq (,${PERFCTR_ROOT})
ifeq (-m32,${BITFLAGS})
	$(MAKE) -C $(PERFCTR_ROOT) PREFIX=$(DESTDIR)$(PREFIX) DESTDIR=$(DESTDIR) BINDIR=$(DESTDIR)$(BINDIR) LIBDIR=$(DESTDIR)$(LIBDIR) INCLDIR=$(DESTDIR)$(INCDIR) ARCH="i386" install
else
	$(MAKE) -C $(PERFCTR_ROOT) PREFIX=$(DESTDIR)$(PREFIX) DESTDIR=$(DESTDIR) BINDIR=$(DESTDIR)$(BINDIR) LIBDIR=$(DESTDIR)$(LIBDIR) INCLDIR=$(DESTDIR)$(INCDIR) install
endif
endif

native_clobber:
ifneq (,${PERFCTR_ROOT})
	$(MAKE) -C $(PERFCTR_ROOT) distclean
endif
