-include		MCONFIG
PERL			?= perl

RELOC_OBJS		= $(patsubst %.c,%.o,$(wildcard reloc/*.c)) \
			  $(patsubst %.S,%.o,$(wildcard reloc/*.S))

HIGHMOVE_OBJS		= $(patsubst %.c,%.o,$(wildcard highmove/*.c)) \
			  $(patsubst %.S,%.o,$(wildcard highmove/*.S))

all: wraplinux

reloc/%.o: reloc/%.c
	$(CC_FOR_TARGET) $(CFLAGS_FOR_TARGET) -c -o $@ $<

reloc/%.o: reloc/%.S
	$(CC_FOR_TARGET) $(CFLAGS_FOR_TARGET) -c -D__ASSEMBLY__ -o $@ $<

highmove/%.o: highmove/%.c
	$(CC_FOR_TARGET) $(CFLAGS_FOR_TARGET) -c -o $@ $<

highmove/%.o: highmove/%.S
	$(CC_FOR_TARGET) $(CFLAGS_FOR_TARGET) -c -D__ASSEMBLY__ -o $@ $<

%.o: %.S
	$(CC) $(CFLAGS) -c -o $@ $<

%.s: %.S
	$(CC) $(CFLAGS) -E -o $@ $<

%.o: %.c
	$(CC) $(CFLAGS) -c -o $@ $<

%.s: %.c
	$(CC) $(CFLAGS) -S -o $@ $<

%.i: %.c
	$(CC) $(CFLAGS) -E -o $@ $<

reloc/reloc.bin: reloc/reloc.elf
	$(OBJCOPY_FOR_TARGET) -O binary $< $@

reloc/reloc.elf: $(RELOC_OBJS) reloc/reloc.ld
	$(LD_FOR_TARGET) $(LDFLAGS_FOR_TARGET) -T reloc/reloc.ld \
		-o $@ $(RELOC_OBJS)

reloc.o: reloc.S reloc/reloc.bin

highmove/highmove.bin: highmove/highmove.elf
	$(OBJCOPY_FOR_TARGET) -O binary $< $@

highmove/highmove.elf: $(HIGHMOVE_OBJS) reloc/reloc.ld
	$(LD_FOR_TARGET) $(LDFLAGS_FOR_TARGET) -T reloc/reloc.ld \
		-o $@ $(HIGHMOVE_OBJS)

highmove.o: highmove.S highmove/highmove.bin

wraplinux: main.o linux.o reloc.o highmove.o elf.o nbi.o segment.o mapfile.o \
	   cwrite.o xmalloc.o
	$(CC) $(LDFLAGS) -o $@ $^

#
# Install
#
install: all
	$(MKDIR_P) $(INSTALLROOT)$(bindir)
	$(INSTALL_PROGRAM) wraplinux $(INSTALLROOT)$(bindir)
	$(MKDIR_P) $(INSTALLROOT)$(mandir)/man1
	$(INSTALL_DATA) wraplinux.1 $(INSTALLROOT)$(mandir)/man1

#
# Cleanup
#
clean:
	rm -f wraplinux *.o *.s *.i
	rm -f reloc/*.o reloc/*.bin reloc/*.elf
	rm -f highmove/*.o highmove/*.bin highmove/*.elf

cleaner: clean
	rm -rf MCONFIG config.h *.cache config.status config.log

distclean: cleaner
	find . -name '*~' -print0 | xargs -0rt rm -f

spotless: distclean
	rm -rf configure config.h.in wraplinux.spec .depend

#
# Prepare a release
#
release:
	$(MAKE) depend
	$(MAKE) spec
	$(MAKE) distclean

#
# Autoconf
#
config:	MCONFIG

MCONFIG: configure MCONFIG.in config.h.in
	./configure

config.h: MCONFIG
	: Generated by side effect

config.h.in: configure.in
	rm -f config.h.in
	autoheader

configure: configure.in aclocal.m4
	autoconf
	rm -f MCONFIG config.cache config.log config.status config.h

#
# Version header
#
VERSION = $(shell cat version)

version.h: version
	echo "#define WRAPLINUX_VERSION \"$(VERSION)\"" > version.h

#
# RPM specfile
#
spec: wraplinux.spec

wraplinux.spec: wraplinux.spec.in version
	$(SED) -e 's/@@VERSION@@/$(VERSION)/g' < $< > $@

#
# Dependencies
#
depend: .depend

.depend:
	: > $@
	$(PERL) mkdep.pl -M $@ -- . reloc highmove

-include .depend
