do_writable_rootfs_defaults() {
	if [ -f /cfg/failed-uci-defaults ]; then
		hash_old="$(cat /cfg/dbversion)"
		hash="$(software_version_hash.sh)"

		if [ "$hash" != "$hash_old" ] || [ -n "$(mount | grep 'overlayfs:/tmp/.* / ')" ]; then
			echo "Reset uci-defaults state"
			rm /cfg/failed-uci-defaults
		fi
	fi

	if [ -f "/etc/writable_locations" ]; then
		if ! mount | grep -q " on /rom " ; then
			mount -o rebind / /rom || return
		fi

		if cd "/rom/tmp" ; then
			for path in *; do
				cp -rp "$path" /tmp
			done
		fi

		if [ ! -f /cfg/failed-uci-defaults ]; then
			echo "Reset writable locations to factory default"
			locations=$(cat "/etc/writable_locations")
			for dir in $locations; do
				cd "/rom$dir" || continue
				mkdir -p "$dir"
				for path in *; do
					rm -rf "$dir/$path"
					cp -rp "$path" "$dir"
				done
			done
		fi
	fi
}

boot_hook_add preinit_main do_writable_rootfs_defaults
