mod_image_for_recovery: change return trap to EXIT

copy_stateful() sets a RETURN trap that deletes a folder. Then there
are 2 calls of safe_umount function on two different mountpoints.

In bash 4.3 the RETURN trap doesn’t get executed, when those
functions return, so the trap executes after copy_stateful exits.
In bash 4.4 the trap does get executed when each of them gets
executed. As a result, the second attempt to remove said folder
fails, and the script stops execution.

This CL changes trap type to EXIT and directly deletes the folder at
the end of the function to ensure that we still does clean up on
error and on successful execution, and do not delete the folder
prematurely.

BUG=chromium:1180660
TEST=ran script manually, `cros tryjob -g '2713386 2713867 2713564 2717166'  arkham-release-tryjob`

Change-Id: I0860122bb81bd128bc63ae89f330b3044d06175a
Reviewed-on: https://chromium-review.googlesource.com/c/chromiumos/platform/crosutils/+/2717166
Tested-by: Sergey Frolov <sfrolov@google.com>
Reviewed-by: Mike Frysinger <vapier@chromium.org>
Reviewed-by: Nicholas Verne <nverne@chromium.org>
Commit-Queue: Mike Frysinger <vapier@chromium.org>
diff --git a/build_library/disk_layout_util.sh b/build_library/disk_layout_util.sh
index daa435a..e73ee27 100644
--- a/build_library/disk_layout_util.sh
+++ b/build_library/disk_layout_util.sh
@@ -516,7 +516,6 @@
   fs_umount "${part_dev}" "${mount_dir}" "${fs_format}" "${fs_options}"
   fs_remove_mountpoint "${mount_dir}"
   sudo losetup -d ${image_dev}
-  trap - RETURN
 }
 
 # Creates the gpt image for the given disk layout. In addition to creating
diff --git a/mod_image_for_recovery.sh b/mod_image_for_recovery.sh
index f595907..60e5749 100755
--- a/mod_image_for_recovery.sh
+++ b/mod_image_for_recovery.sh
@@ -94,7 +94,6 @@
 
   safe_umount "$stateful_mnt"
   sudo losetup -d ${IMAGE_DEV}
-  trap - RETURN
   rmdir "$stateful_mnt"
   switch_to_strict_mode
   echo "$out"
@@ -249,7 +248,6 @@
     safe_umount "$esp_mnt"
     rmdir "$esp_mnt"
     sudo losetup -d ${RECOVERY_DEV}
-    trap - RETURN
     switch_to_strict_mode
   fi
 
@@ -306,7 +304,9 @@
   small_stateful=$(mktemp)
   dd if=/dev/zero of="${small_stateful}" bs=512 \
     count="${sectors_needed}" 1>&2
-  trap "rm ${small_stateful}; sudo losetup -d ${IMAGE_DEV} || true" RETURN
+  trap "rm ${small_stateful}; sudo losetup -d ${IMAGE_DEV} || true; cleanup" \
+    EXIT
+
   # Don't bother with ext3 for such a small image.
   /sbin/mkfs.ext2 -F -b 4096 "${small_stateful}" 1>&2
 
@@ -336,13 +336,14 @@
   rmdir "$old_stateful_mnt"
   rmdir "$new_stateful_mnt"
   sudo losetup -d ${IMAGE_DEV}
-  trap - RETURN
+  trap cleanup EXIT
   switch_to_strict_mode
 
   local dst_start
   dst_start="$(cgpt show -i "${partition_num_state}" -b "${dst_img}")"
   dd if="${small_stateful}" of="${dst_img}" conv=notrunc bs=512 \
     seek="${dst_start}" count="${sectors_needed}" status=none
+  rm "${small_stateful}"
   return 0
 }