#
# Copyright (c) 2005 Martin Decky
# Copyright (c) 2007 Jakub Jermar
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
#   notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# - The name of the author may not be used to endorse or promote products
#   derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
# OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
# IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
# NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
# THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#

# Individual makefiles set:
#
#   USPACE_PREFIX  (*) relative path to uspace/ directory
#   SOURCES        (*) list of source files
#   LIBS               libraries to link with
#   DEFS               compiler defines
#   EXTRA_CFLAGS       additional flags to pass to C compiler
#   LINKER_SCRIPT      linker script
#   PRE_DEPEND         targets required for dependency check
#
#   BINARY         (/) binary output name (like appname)
#   LIBRARY        (/) library output name (like libname)
#
#   EXTRA_OUTPUT       additional output targets
#   EXTRA_CLEAN        additional cleanup targets
#
#   POSIX_COMPAT       set to 'y' to use POSIX compatibility layer
#
# Optionally, for a binary:
#   STATIC_NEEDED      set to 'y' for init binaries, will build statically
#                      linked version
#   STATIC_ONLY        set to 'y' if binary cannot be linked dynamically
#                      (e.g. uses thread-local variables)
#
# Optionally, for a libary:
#   SLIBRARY           Name with full version, e.g. libfoo.so.0.0 
#   LSONAME            Soname / name with short version, e.g. libfoo.so.0
#
# (x) required variables
# (/) exactly one of the variables must be defined
#

ROOT_PATH = $(USPACE_PREFIX)/..

VERSION_DEF = $(ROOT_PATH)/version

COMMON_MAKEFILE = $(ROOT_PATH)/Makefile.common
COMMON_HEADER = $(ROOT_PATH)/common.h

CONFIG_MAKEFILE = $(ROOT_PATH)/Makefile.config
CONFIG_HEADER = $(ROOT_PATH)/config.h

-include $(VERSION_DEF)
-include $(COMMON_MAKEFILE)
-include $(CONFIG_MAKEFILE)

ifneq ($(BINARY),)
	JOB = $(BINARY).job
	OUTPUT = $(BINARY)
	EXTRA_OUTPUT += $(BINARY).disasm
	EXTRA_CLEAN += $(BINARY).map
endif

ifneq ($(LIBRARY),)
	JOB = $(LIBRARY).job
	OUTPUT = $(LIBRARY).a
endif

ifeq ($(CONFIG_BUILD_SHARED_LIBS), y)
	ifneq ($(SLIBRARY),)
		LARCHIVE = $(LIBRARY).la
		LOUTPUT = $(SLIBRARY)
		EXTRA_OUTPUT += $(LOUTPUT).disasm $(LIBRARY).so $(LSONAME)
		EXTRA_CLEAN += $(LOUTPUT).map $(LOUTPUT).ldisasm \
		    $(LIBC_PREFIX)/shared/arch/$(UARCH)/_lib.ld \
		    $(LIBRARY).so $(LSONAME)
	endif
endif

DEPEND = Makefile.depend
DEPEND_PREV = $(DEPEND).prev

LIB_PREFIX = $(USPACE_PREFIX)/lib

LIBC_PREFIX = $(LIB_PREFIX)/c
LIBSOFTFLOAT_PREFIX = $(LIB_PREFIX)/softfloat
LIBSOFTINT_PREFIX = $(LIB_PREFIX)/softint

LIBPOSIX_PREFIX = $(LIB_PREFIX)/posix

LIBBLOCK_PREFIX = $(LIB_PREFIX)/block
LIBFS_PREFIX = $(LIB_PREFIX)/fs
LIBIMGMAP_PREFIX = $(LIB_PREFIX)/imgmap
LIBCLUI_PREFIX = $(LIB_PREFIX)/clui
LIBFMTUTIL_PREFIX = $(LIB_PREFIX)/fmtutil

LIBEXT2_PREFIX = $(LIB_PREFIX)/ext2

LIBUSB_PREFIX = $(LIB_PREFIX)/usb
LIBUSBHOST_PREFIX = $(LIB_PREFIX)/usbhost
LIBUSBDEV_PREFIX = $(LIB_PREFIX)/usbdev
LIBUSBHID_PREFIX = $(LIB_PREFIX)/usbhid
LIBUSBVIRT_PREFIX = $(LIB_PREFIX)/usbvirt

LIBDRV_PREFIX = $(LIB_PREFIX)/drv
LIBPACKET_PREFIX = $(LIB_PREFIX)/packet
LIBNET_PREFIX = $(LIB_PREFIX)/net
LIBMINIX_PREFIX = $(LIB_PREFIX)/minix
LIBSCSI_PREFIX = $(LIB_PREFIX)/scsi

ifeq ($(STATIC_NEEDED),y)
	STATIC_BUILD = y
else
	ifeq ($(STATIC_ONLY),y)
		STATIC_BUILD = y
	else
		ifeq ($(CONFIG_USE_SHARED_LIBS), y)
			STATIC_BUILD = n
		else
			STATIC_BUILD = y
		endif
	endif
endif

# Build static whenever we use libusb because that library uses 
# thread local variables
ifneq ($(findstring usb, $(LIBS)),)
	STATIC_BUILD = y
endif

ifeq ($(STATIC_BUILD), y)
BASE_LIBS = $(LIBC_PREFIX)/libc.a $(LIBSOFTINT_PREFIX)/libsoftint.a
LINKER_SCRIPT ?= $(LIBC_PREFIX)/arch/$(UARCH)/_link.ld
else
BASE_LIBS = $(LIBC_PREFIX)/libc.so0 $(LIBSOFTINT_PREFIX)/libsofti.so0
LFLAGS = -Bdynamic
LINKER_SCRIPT ?= $(LIBC_PREFIX)/arch/$(UARCH)/_link-dlexe.ld
endif

ifeq ($(CONFIG_OPTIMIZE_FOR_SIZE),y)
	OPTIMIZATION = s
else
	OPTIMIZATION = 3
endif

.PHONY: all clean

all: $(VERSION_DEF) $(COMMON_MAKEFILE) $(CONFIG_MAKEFILE) $(CONFIG_HEADER) $(LIBS) $(OUTPUT) $(LOUTPUT) $(EXTRA_OUTPUT)
	-[ -f $(DEPEND) ] && cp -a $(DEPEND) $(DEPEND_PREV)

clean:
	rm -f $(DEPEND) $(DEPEND_PREV) $(JOB) $(OUTPUT) $(LARCHIVE) $(LOUTPUT) $(EXTRA_OUTPUT) $(EXTRA_CLEAN)
	find . -name '*.o' -follow -exec rm \{\} \;
	find . -name '*.lo' -follow -exec rm \{\} \;

GCC_CFLAGS = -I$(LIBC_PREFIX)/include -O$(OPTIMIZATION) -imacros $(CONFIG_HEADER) \
	-fexec-charset=UTF-8 -fwide-exec-charset=UTF-32$(ENDIANESS) \
	-finput-charset=UTF-8 -ffreestanding -fno-builtin -nostdlib -nostdinc \
	-Wall -Wextra -Wno-clobbered -Wno-unused-parameter -Wmissing-prototypes \
	-std=gnu99 -Werror-implicit-function-declaration -Wwrite-strings \
	-pipe -g -D__$(ENDIANESS)__

ICC_CFLAGS = -I$(LIBC_PREFIX)/include -O$(OPTIMIZATION) -imacros $(CONFIG_HEADER) \
	-fexec-charset=UTF-8 -fwide-exec-charset=UTF-32$(ENDIANESS) \
	-finput-charset=UTF-8 -ffreestanding -fno-builtin -nostdlib -nostdinc \
	-Wall -Wextra -Wno-clobbered -Wno-unused-parameter -Wmissing-prototypes \
	-Werror-implicit-function-declaration -Wwrite-strings \
	-pipe -g -D__$(ENDIANESS)__

CLANG_CFLAGS = -I$(LIBC_PREFIX)/include -O$(OPTIMIZATION) -imacros $(CONFIG_HEADER) \
	-fexec-charset=UTF-8 -fwide-exec-charset=UTF-32$(ENDIANESS) \
	-finput-charset=UTF-8 -ffreestanding -fno-builtin -nostdlib -nostdinc \
	-Wall -Wextra -Wno-unused-parameter -Wmissing-prototypes \
	-Werror-implicit-function-declaration -Wwrite-strings \
	-pipe -g -arch $(CLANG_ARCH) -D__$(ENDIANESS)__

LIB_CFLAGS = $(CFLAGS) -fPIC -D__IN_SHARED_LIBC__
LIB_LFLAGS = $(LFLAGS) -shared -soname $(LSONAME) --whole-archive

ifeq ($(CONFIG_DEBUG),y)
	GCC_CFLAGS += -Werror
	ICC_CFLAGS += -Werror
endif

ifeq ($(CONFIG_LINE_DEBUG),y)
	GCC_CFLAGS += -g
	ICC_CFLAGS += -g
	SUNCC_CFLAGS += -g
	CLANG_CFLAGS += -g
endif

## Setup platform configuration
#

-include $(LIBC_PREFIX)/arch/$(UARCH)/Makefile.common

## Compilation options
#

JOBFILE = $(LIBC_PREFIX)/../../../tools/jobfile.py

ifeq ($(POSIX_COMPAT),y)
	CFLAGS = -I$(LIBPOSIX_PREFIX)
	LIBS += $(LIBPOSIX_PREFIX)/libposix.a
endif

ifeq ($(COMPILER),gcc_cross)
	CFLAGS += $(GCC_CFLAGS) $(EXTRA_CFLAGS)
	DEPEND_DEFS = $(DEFS) $(CONFIG_DEFS)
endif

ifeq ($(COMPILER),gcc_native)
	CFLAGS += $(GCC_CFLAGS) $(EXTRA_CFLAGS)
	DEPEND_DEFS = $(DEFS) $(CONFIG_DEFS)
endif

ifeq ($(COMPILER),icc)
	CFLAGS += $(ICC_CFLAGS) $(EXTRA_CFLAGS)
	DEPEND_DEFS = $(DEFS) $(CONFIG_DEFS)
endif

ifeq ($(COMPILER),clang)
	CFLAGS += $(CLANG_CFLAGS) $(EXTRA_CFLAGS)
	DEPEND_DEFS = $(DEFS) $(CONFIG_DEFS)
endif

-include $(DEPEND)

OBJECTS := $(addsuffix .o,$(basename $(SOURCES)))
LOBJECTS := $(addsuffix .lo,$(basename $(SOURCES)))

ifneq ($(BINARY),)
%.disasm: $(BINARY)
ifeq ($(CONFIG_LINE_DEBUG),y)
	$(OBJDUMP) -d -S $< > $@
else
	$(OBJDUMP) -d $< > $@
endif

$(BINARY): $(LINKER_SCRIPT) $(OBJECTS) $(LIBS) $(BASE_LIBS)
	$(LD) -n $(LFLAGS) -T $(LINKER_SCRIPT) -M -Map $(BINARY).map -o $(BINARY) $(OBJECTS) $(LIBS) $(BASE_LIBS)
ifeq ($(CONFIG_STRIP_BINARIES),y)
	$(STRIP) $(BINARY)
endif
endif

ifneq ($(SLIBRARY),)
%.disasm: $(LOUTPUT)
ifeq ($(CONFIG_LINE_DEBUG),y)
	$(OBJDUMP) -d -S $< > $@
else
	$(OBJDUMP) -d $< > $@
endif

$(LOUTPUT): $(LARCHIVE) $(LIBC_PREFIX)/arch/$(UARCH)/_link-shlib.ld
	$(LD) -T $(LIBC_PREFIX)/arch/$(UARCH)/_link-shlib.ld $(LIB_LFLAGS) $(LARCHIVE) -o $@ -Map $(LOUTPUT).map

$(LIBRARY).so:
	ln -s $(SLIBRARY) $@

$(LSONAME):
	ln -s $(SLIBRARY) $@
endif

ifneq ($(LIBRARY),)
%.a: $(OBJECTS)
	$(AR) rc $@ $(OBJECTS)
endif

ifneq ($(SLIBRARY),)
%.la: $(LOBJECTS)
	$(AR) rc $@ $(LOBJECTS)
endif

%.o: %.S $(DEPEND)
	$(CC) $(DEFS) $(CFLAGS) -D__ASM__ -c $< -o $@
ifeq ($(PRECHECK),y)
	$(JOBFILE) $(JOB) $< $@ as asm/preproc $(DEFS) $(CFLAGS) -D__ASM__
endif

%.o: %.s $(DEPEND)
	$(AS) $(AFLAGS) -o $@ $<
ifeq ($(PRECHECK),y)
	$(JOBFILE) $(JOB) $< $@ as asm
endif

%.o: %.c $(DEPEND)
	$(CC) $(DEFS) $(CFLAGS) -c $< -o $@
ifeq ($(PRECHECK),y)
	$(JOBFILE) $(JOB) $< $@ cc core $(DEFS) $(CFLAGS)
endif

%.lo: %.S $(DEPEND)
	$(CC) $(DEFS) $(LIB_CFLAGS) -D__ASM__ -c $< -o $@
ifeq ($(PRECHECK),y)
	$(JOBFILE) $(JOB) $< $@ as asm/preproc $(DEFS) $(CFLAGS) -D__ASM__
endif

%.lo: %.s $(DEPEND)
	$(AS) $(AFLAGS) -o $@ $<
ifeq ($(PRECHECK),y)
	$(JOBFILE) $(JOB) $< $@ as asm
endif

%.lo: %.c $(DEPEND)
	$(CC) $(DEFS) $(LIB_CFLAGS) -c $< -o $@
ifeq ($(PRECHECK),y)
	$(JOBFILE) $(JOB) $< $@ cc core $(DEFS) $(CFLAGS)
endif

$(DEPEND): $(PRE_DEPEND)
	makedepend -f - -- $(DEPEND_DEFS) $(CFLAGS) -- $(SOURCES) > $@ 2> /dev/null
	-[ -f $(DEPEND_PREV) ] && diff -q $(DEPEND_PREV) $@ && mv -f $(DEPEND_PREV) $@

##
# This explicit dependecy of the output binary on the object files seems to be
# necessary to prevent parallel build failures (GNU make bug #26893 ???).
$(OUTPUT): $(OBJECTS)

$(LARCHIVE): $(LOBJECTS)
