setup: cros_docker: Use cached resources if possible.

There are few resources that cros_docker will try to download remotely:
pbzip2 and docker client. Currently pbzip2 allows caching but it won't
check if the file is good; docker client is always re-downloaded.

To allow building locally and to speed up development cycle, we should
re-download these files only if they do not exist, or is corrupted.

time ./cros_docker.sh build

Before:
 real    0m6.101s
 user    0m5.750s
 sys     0m1.387s

After:
 real    0m5.554s
 user    0m5.118s
 sys     0m1.352s

BUG=None
TEST=cros_docker.sh build

Change-Id: I7b7a95820b9edbc296f897dc24f12546905ebf72
Reviewed-on: https://chromium-review.googlesource.com/429950
Commit-Ready: Hung-Te Lin <hungte@chromium.org>
Tested-by: Hung-Te Lin <hungte@chromium.org>
Reviewed-by: Mao Huang <littlecvr@chromium.org>
diff --git a/setup/cros_docker.sh b/setup/cros_docker.sh
index d4e244c..f1ffe14 100755
--- a/setup/cros_docker.sh
+++ b/setup/cros_docker.sh
@@ -104,6 +104,12 @@
 PREBUILT_IMAGE_DIR_URL="${PREBUILT_IMAGE_SITE}/chromeos-localmirror/distfiles"
 GSUTIL_BUCKET="gs://chromeos-localmirror/distfiles"
 
+# Remote resources
+RESOURCE_PBZIP2_URL="https://launchpad.net/pbzip2/1.1/1.1.13/+download/pbzip2-1.1.13.tar.gz"
+RESOURCE_PBZIP2_SHA1="f61e65a7616a3492815d18689c202d0685fe167d"
+RESOURCE_DOCKER_URL="https://get.docker.com/builds/Linux/i386/docker-${DOCKER_VERSION}.tgz"
+RESOURCE_DOCKER_SHA1="a07cc33579a6e0074a53f148b26103723f81dab1"
+
 # Directories inside docker
 DOCKER_BASE_DIR="/usr/local/factory"
 DOCKER_DOME_DIR="${DOCKER_BASE_DIR}/py/dome"
@@ -143,6 +149,18 @@
   fi
 }
 
+fetch_resource() {
+  local local_name="$1"
+  local url="$2"
+  local sha1="$3"
+
+  if [[ ! -f "${local_name}" ]] || \
+     ! echo "${sha1} ${local_name}" | sha1sum -c; then
+    rm -f "${local_name}"
+    wget "${url}" -O "${local_name}"
+  fi
+}
+
 # Section for Umpire subcommand
 do_umpire_run() {
   check_docker
@@ -527,10 +545,9 @@
   TEMP_OBJECTS=("${temp_dir}" "${TEMP_OBJECTS[@]}")
 
   mkdir -p "${BUILD_DIR}"
-  if [[ ! -f "${BUILD_DIR}/pbzip2.tgz" ]]; then
-    wget "https://launchpad.net/pbzip2/1.1/1.1.13/+download/pbzip2-1.1.13.tar.gz" \
-      -O "${BUILD_DIR}/pbzip2.tgz"
-  fi
+  fetch_resource "${BUILD_DIR}/pbzip2.tgz" \
+    "${RESOURCE_PBZIP2_URL}" "${RESOURCE_PBZIP2_SHA1}"
+
   cp "${BUILD_DIR}/pbzip2.tgz" "${temp_dir}"
   cp -r "${host_vboot_dir}" "${temp_dir}"
   cp "${deps_builder_dockerfile}" "${temp_dir}/Dockerfile"
@@ -619,8 +636,8 @@
 
   local dockerfile="${SCRIPT_DIR}/Dockerfile"
 
-  wget "https://get.docker.com/builds/Linux/i386/docker-${DOCKER_VERSION}.tgz" \
-    -O "${BUILD_DIR}/docker.tgz"
+  fetch_resource "${BUILD_DIR}/docker.tgz" \
+    "${RESOURCE_DOCKER_URL}" "${RESOURCE_DOCKER_SHA1}"
 
   # need to make sure we're using the same version of docker inside the container
   ${DOCKER} build \