#
# Makefile for gfs2-utils
#
.PHONY: all install clean test testprog testlib libraries programs strings
.SUFFIXES: .po .pot .d

subdir = $(patsubst %/target.mk,%,$(word $(words $(MAKEFILE_LIST)), $(MAKEFILE_LIST)))

# $(call make-binary, name, libs)
#
# This is used to make a binary from all the sources in a
# directory. The name should be that of the final installed
# binary.
#
define make-binary
  $(eval local_bin = $(subdir)/$(notdir $(strip $1)))
  $(eval local_src = $(wildcard $(subdir)/*.c))

  programs += $(local_bin)
  install += install-$(local_bin)
  sources += $(local_src)

$(local_bin): $2 $(subst .c,.o,$(local_src))
	$(LINK.c) $$^ $2 -o $$@
install-$(local_bin): $(local_bin)
	$(INSTALL) -m 0755 $(local_bin) $(strip $1)
endef

# $(call make-trans-binary,name,libs)
# 
# As above, but binary has translatable strings
#
define make-trans-binary
  $(call make-binary,$1,$2)
  posources += $(wildcard $(subdir)/*.c)
endef

# $(call make-library, name)
#
# This is called to make a library from all the sources
# in a directory/
#
define make-library
  $(eval local_libs = $(subdir)/$(notdir $(strip $1)))
  $(eval local_src = $(wildcard $(subdir)/*.c))
  $(eval local_objs = $(subst .c,.o,$(local_src)))
  libraries += $(local_libs)
  sources += $(local_src)

$(local_libs): $(local_objs)
	$(AR) $(ARFLAGS) $$@ $$^
$(local_objs): %.o: %.c
	$(COMPILE.c) -fPIC $$< -o $$@
endef


CC=gcc
LD=gcc
AR=ar
SED=sed
MV=mv
GT=xgettext
INSTALL=install
CFLAGS=-O2 -Wall -D_GNU_SOURCE -D_FILE_OFFSET_BITS=64 -fno-strict-aliasing -Werror -DVERSION=\"3.1.0\"
LDFLAGS=
ARFLAGS=rcs

# Programs
programs :=
# Install
install :=
# All source files
sources :=
# All source files from which translatable strings are extracted
posources :=
# All libraries
libraries :=
# All man pages
manpages :=

# These are created automatically from the above
objects		= $(subst .c,.o,$(sources))
dependencies    = $(subst .o,.d,$(objects))

#
# Need to trim down the list of include dirs to something more reasonable
#
include_dirs := gfs2/include gfs2/libgfs2 group/include group/libgfscontrol make group/gfs_controld
CFLAGS += $(addprefix -I ,$(include_dirs))
vpath %.h $(include_dirs)


all:
include $(shell find . -mindepth 2 -type f -name target.mk -print)
all: $(programs)

libraries: $(libraries)
programs: $(programs)
strings: po/gfs2-utils.pot
po/gfs2-utils.pot: $(posources)
	$(GT) -k_ -o po/gfs2-utils.pot $^
install: $(install)

clean:
	rm -f $(objects) $(programs) $(libraries) $(dependencies)

test: progtest libtest
progtest: $(programs)
libtest: $(libraries)

ifneq "$(MAKECMDGOALS)" "clean"
-include $(dependencies)
endif

%.po: %.pot
	mv %< $(basename %<).pp
	msgmerge -o %< ($basename %<).pp $(basename %<).pot
	rm -f $(basename %<).pp

%.d: %.c
	$(CC) $(CFLAGS) $(CPPFLAGS) $(TARGET_ARCH) -M $< | \
	$(SED) 's,\($(nodir $*)\.o\) *:,$(dir $@)\1 $@: ,' > $@.tmp
	$(MV) $@.tmp $@

%: %.o
	$(LINK.c) $(LDLIBS) $^ -o $@
