build_package.sh: SPM: Smart retrying when fetching SPM submodules

It turned out that just retrying "git submodule update" command is not
reliable in the presence of some errors. A particlar submodule may get
stuck in a weird state when "git submodule" thinks it's ok, but it's
actually not checked out properly. So, in case an errors happens,
explicitly deinit module and re-init and update again, and do all
operations per-module to be efficient.

Signed-off-by: Paul Sokolovsky <paul.sokolovsky@linaro.org>
Change-Id: I441e2066aefa7e93db5c5e2903775aae16b29fc6
(cherry picked from commit ad274423215ba0a5ac0ad28fb139145247107ead)
diff --git a/script/build_package.sh b/script/build_package.sh
index 1625036..4db1d3f 100755
--- a/script/build_package.sh
+++ b/script/build_package.sh
@@ -1288,10 +1288,22 @@
 	# Query git submodules
 	pushd "$spm_root"
 	# Check if submodules need initialising
-	if git submodule status | grep '^-'; then
-		git submodule init
-		retry git submodule update
-	fi
+
+	# This handling is needed to reliably fetch submodules
+	# in CI environment.
+	for subm in $(git submodule status | awk '/^-/ {print $2}'); do
+		for i in $(seq 1 7); do
+			git submodule init $subm
+			if git submodule update $subm; then
+				break
+			fi
+			git submodule deinit --force $subm
+			echo "Retrying $subm"
+			sleep $((RANDOM % 10 + 5))
+		done
+	done
+
+	git submodule status
 	popd
 
 	show_head "$spm_root"