E2FSPROGS:=e2fsprogs-1.45.5
E2FSPROGS_TAR:=$(E2FSPROGS).tar.gz

PREFIX := $(shell pwd)

PC_DIR := $(shell pwd)/$(E2FSPROGS)_pc
BOARD_DIR := $(shell pwd)/$(E2FSPROGS)_board

OSDRV_CROSS ?= aarch64-mix210-linux
OSDRV_CROSS_CFLAGS := -fstack-protector-strong -fPIC
OSDRV_CROSS_LDFLAGS := -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack

LOCAL_CFLAGS := -fPIC
LOCAL_LDFLAGS := -Wl,-z,relro -Wl,-z,now -Wl,-z,noexecstack
GCC_VERSION_GE49 := $(shell echo `gcc -dumpversion | cut -f1-2 -d.` \>= 4.9 | sed -e 's/\./*100+/g' | bc)
ifeq ($(GCC_VERSION_GE49),1)
LOCAL_CFLAGS += -fstack-protector-strong
else
LOCAL_CFLAGS += -fstack-protector-all
endif

all: e2fsprogs_pc  e2fsprogs_board

prepare:
ifneq ($(PREFIX)/out, $(wildcard $(PREFIX)/out))
	mkdir $(PREFIX)/out
	mkdir $(PREFIX)/out/pc
	mkdir $(PREFIX)/out/board
endif

e2fsprogs_pc: $(PC_DIR)/mkfs.ext4
$(PC_DIR)/mkfs.ext4: $(PC_DIR)/sbin/mkfs.ext4
	@test -d $(@D) || mkdir -p $(@D)
	install -vs -t $(PC_DIR) $<
	@test -d $(PC_DIR)/contrib || mkdir -p $(PREFIX)/out/pc/contrib
	@test -d $(PC_DIR)/debugfs || mkdir -p $(PREFIX)/out/pc//debugfs
	cp -rf $(PC_DIR)/$(E2FSPROGS)/contrib/populate-extfs.sh $(PREFIX)/out/pc/contrib
	cp -rf $(PC_DIR)/$(E2FSPROGS)/debugfs/debugfs $(PREFIX)/out/pc/debugfs
	cp -rf $(PC_DIR)/sbin $(PREFIX)/out/pc/
	rm $(PC_DIR) -rf

$(PC_DIR)/sbin/mkfs.ext4: prepare
ifneq ($(PC_DIR), $(wildcard $(PC_DIR)))
	mkdir $(PC_DIR)
	tar -xf $(E2FSPROGS_TAR) -C $(PC_DIR)
endif
	cd $(PC_DIR)/$(E2FSPROGS) && \
		./configure --prefix="$(PC_DIR)" CFLAGS="$(LOCAL_CFLAGS)" \
		LDFLAGS="$(LOCAL_LDFLAGS)" --disable-tls \
		--with-udev-rules-dir=$(PC_DIR)/obj/rootfs/etc/udev/rules.d \
		--with-systemd-unit-dir=$(PC_DIR)/obj/rootfs/lib \
		--with-crond-dir=$(PC_DIR)/obj/rootfs/etc/cron.d && \
		make 1>/dev/null  && \
		make install 1>/dev/null

e2fsprogs_board: $(BOARD_DIR)/sbin/mkfs.ext4
$(BOARD_DIR)/sbin/mkfs.ext4: prepare
ifneq ($(BOARD_DIR), $(wildcard $(BOARD_DIR)))
	mkdir $(BOARD_DIR)
	tar -xf $(E2FSPROGS_TAR) -C $(BOARD_DIR)
endif
	cd $(BOARD_DIR)/$(E2FSPROGS) && \
		./configure --host=$(OSDRV_CROSS) CFLAGS="$(OSDRV_CROSS_CFLAGS)" \
		LDFLAGS="$(OSDRV_CROSS_LDFLAGS)" --prefix=$(BOARD_DIR)  --disable-tls \
		--with-udev-rules-dir=$(BOARD_DIR)/obj/rootfs/etc/udev/rules.d \
		--with-systemd-unit-dir=$(BOARD_DIR)/obj/rootfs/lib \
		--with-crond-dir=$(BOARD_DIR)/obj/rootfs/etc/cron.d && \
		make CFLAGS="-static" LDFLAGS="-static" -j1 1>/dev/null && \
		make install 1>/dev/null

	cp $(BOARD_DIR)/sbin  $(PREFIX)/out/board -rf
	rm $(BOARD_DIR) -rf
clean:
	rm out -rf;
	rm $(E2FSPROGS)_* -rf
distclean: clean
