androidtest.bash: robust cleanup in case of failure.

Change-Id: I69ed001bca4987e08b46a8288f6feae2aca6a142
Reviewed-on: https://go-review.googlesource.com/12380
Reviewed-by: David Crawshaw <crawshaw@golang.org>
diff --git a/src/androidtest.bash b/src/androidtest.bash
index 39e73c3..0010738 100755
--- a/src/androidtest.bash
+++ b/src/androidtest.bash
@@ -35,6 +35,13 @@
 	-o ../bin/go_android_${GOARCH}_exec \
 	../misc/android/go_android_exec.go
 
+export ANDROID_TEST_DIR=/tmp/androidtest-$$
+
+function cleanup() {
+	rm -rf ${ANDROID_TEST_DIR}
+}
+trap cleanup EXIT
+
 # Push GOROOT to target device.
 #
 # The adb sync command will sync either the /system or /data
@@ -42,7 +49,7 @@
 # on the host. We copy the files required for running tests under
 # /data/local/tmp/goroot. The adb sync command does not follow
 # symlinks so we have to copy.
-export ANDROID_PRODUCT_OUT=/tmp/androidtest-$$
+export ANDROID_PRODUCT_OUT="${ANDROID_TEST_DIR}/out"
 FAKE_GOROOT=$ANDROID_PRODUCT_OUT/data/local/tmp/goroot
 mkdir -p $FAKE_GOROOT
 mkdir -p $FAKE_GOROOT/pkg
@@ -54,17 +61,15 @@
 adb shell mkdir -p /data/local/tmp/goroot
 time adb sync data &> /dev/null
 
-export CLEANER=/tmp/androidcleaner-$$
+export CLEANER=${ANDROID_TEST_DIR}/androidcleaner-$$
 cp ../misc/android/cleaner.go $CLEANER.go
 echo 'var files = `' >> $CLEANER.go
 (cd $ANDROID_PRODUCT_OUT/data/local/tmp/goroot; find . >> $CLEANER.go)
 echo '`' >> $CLEANER.go
 go build -o $CLEANER $CLEANER.go
 adb push $CLEANER /data/local/tmp/cleaner
-rm $CLEANER $CLEANER.go
 adb shell /data/local/tmp/cleaner
 
-rm -rf "$ANDROID_PRODUCT_OUT"
 echo ''
 
 # Run standard tests.