+# This needs to make /tmp/_sys/sysupgrade.tgz an empty file prior to
+# sysupgrade, as otherwise it will implant the old configuration from
+# OEM firmware when writing rootfs from factory.bin
+define Build/engenius-tar-gz
+ -[ -f "$@" ] && \
+ mkdir -p $@.tmp && \
+ echo '#!/bin/sh' > $@.tmp/before-upgrade.sh && \
+ echo ': > /tmp/_sys/sysupgrade.tgz' >> $@.tmp/before-upgrade.sh && \
+ $(CP) $(KDIR)/loader-$(DEVICE_NAME).uImage \
+ $@.tmp/openwrt-$(word 1,$(1))-uImage-lzma.bin && \
+ $(CP) $@ $@.tmp/openwrt-$(word 1,$(1))-root.squashfs && \
+ $(TAR) -cp --numeric-owner --owner=0 --group=0 --mode=a-s --sort=name \
+ $(if $(SOURCE_DATE_EPOCH),--mtime="@$(SOURCE_DATE_EPOCH)") \
+ -C $@.tmp . | gzip -9n > $@ && \
+ rm -rf $@.tmp
+endef
+
+define Build/mkdapimg2
+ $(STAGING_DIR_HOST)/bin/mkdapimg2 \
+ -i $@ -o $@.new \
+ -s $(DAP_SIGNATURE) \
+ -v $(VERSION_DIST)-$(firstword $(subst +, , \
+ $(firstword $(subst -, ,$(REVISION))))) \
+ -r Default \
+ $(if $(1),-k $(1))
+ mv $@.new $@
+endef
+
+define Build/mkmylofw_16m
+ $(eval device_id=$(word 1,$(1)))
+ $(eval revision=$(word 2,$(1)))
+
+ # On WPJ344, WPJ531, and WPJ563, the default boot command tries 0x9f680000
+ # first and fails if the remains of the stock image are sill there
+ # - resulting in an infinite boot loop.
+ # The size parameter is grown to have that block deleted if the firmware
+ # isn't big enough by itself.
+
+ let \
+ size="$$(stat -c%s $@)" \
+ pad="$(subst k,* 1024,$(BLOCKSIZE))" \
+ pad="(pad - (size % pad)) % pad" \
+ newsize='size + pad' ; \
+ [ $$newsize -lt $$((0x660000)) ] && newsize=0x660000 ; \
+ $(STAGING_DIR_HOST)/bin/mkmylofw \
+ -B WPE72 -i 0x11f6:$(device_id):0x11f6:$(device_id) -r $(revision) \
+ -s 0x1000000 -p0x30000:$$newsize:al:0x80060000:"OpenWRT":$@ \
+ $@.new
+ @mv $@.new $@
+endef
+
+define Build/mkwrggimg
+ $(STAGING_DIR_HOST)/bin/mkwrggimg -b \
+ -i $@ -o $@.imghdr -d /dev/mtdblock/1 \
+ -m $(DEVICE_MODEL)-$(DEVICE_VARIANT) -s $(DAP_SIGNATURE) \
+ -v $(VERSION_DIST) -B $(REVISION)
+ mv $@.imghdr $@
+endef
+