--- /dev/null
+export autoresize autoresize_unit
+
+define autoresize :=
+#!/bin/sh
+
+rootfs="$$(mount |grep -w / |cut -d' ' -f1)"
+
+case $$rootfs in
+ /dev/mmcblk?p2) rootdev="$${rootfs%p2}";;
+ /dev/[sh]d?2) rootdev="$${rootfs%2}";;
+ *) exit 0;;
+esac
+
+before="$$(sfdisk --dump "$$rootdev")"
+
+sfdisk --dump "$$rootdev" |sed '$$s;, size=.*,;,;;' \
+| sfdisk --force "$$rootdev"
+
+after="$$(sfdisk --dump "$$rootdev")"
+
+if [ "$$before" = "$$after" ]; then
+ # second stage
+ resize2fs "$$rootfs"
+ systemctl disable autoresize
+else
+ # finish first stage
+ shutdown -r now
+fi
+
+endef
+
+define autoresize_unit :=
+[Unit]
+Description=Resize root filesystem at boot
+
+[Service]
+ExecStart=/opt/autoresize.sh
+
+[Install]
+WantedBy=multi-user.target
+endef
+
+.PHONY: _autoresize
+_config: _autoresize
+
+_autoresize: ${CFGROOT}
+ mkdir -p "$${CFGROOT}/etc/systemd/system/"
+ printf '%s\n' "$$autoresize" >"$${CFGROOT}/opt/autoresize.sh"
+ chmod 755 "$${CFGROOT}/opt/autoresize.sh"
+ printf '%s\n' "$$autoresize_unit" >"$${CFGROOT}/etc/systemd/system/autoresize.service"
+ chroot "$${CFGROOT}" systemctl enable autoresize