[cipd] Copy cipd to Metadir/bin/cipd when jiri init.

As buildtools/cipd is moving away from Fuchsia, jiri must expose
the cipd binary to other Fuchsia tools. This change makes a copy
of cipd whenever jiri init is executed to ensure cipd is available
to other tools.

Test: Local and CQ
Change-Id: I35755b7640a4625bca91d4e0e2879be1775d2883
diff --git a/cipd/cipd.go b/cipd/cipd.go
index 105aca1..07ed44f 100644
--- a/cipd/cipd.go
+++ b/cipd/cipd.go
@@ -17,6 +17,7 @@
 	"os"
 	"os/exec"
 	"path"
+	"path/filepath"
 	"regexp"
 	"runtime"
 	"strings"
@@ -110,6 +111,11 @@
 		return errors.New("cipd failed integrity test")
 	}
 	// cipd binary verified. Save to disk
+	if _, err := os.Stat(filepath.Dir(binaryPath)); os.IsNotExist(err) {
+		if err := os.MkdirAll(filepath.Dir(binaryPath), 0755); err != nil {
+			return fmt.Errorf("failed to create parent directory %q for cipd: %v", filepath.Dir(binaryPath), err)
+		}
+	}
 	return writeFile(binaryPath, data)
 }
 
@@ -937,3 +943,18 @@
 		Platform{"mac", "amd64"},
 	}
 }
+
+// CopyCIPDToDirectory makes a copy of bootstrapped cipd to another location
+// by re-bootstrap cipd to dirname so it can be used by other Fuchsia tools.
+func CopyCIPDToDirectory(dirname string) error {
+	originalCIPD := cipdBinary
+	defer func() {
+		cipdBinary = originalCIPD
+	}()
+	cipdBinary = filepath.Join(dirname, "cipd")
+	_, err := Bootstrap()
+	if err != nil {
+		return err
+	}
+	return nil
+}
diff --git a/cmd/jiri/init.go b/cmd/jiri/init.go
index 117ab34..735b127 100644
--- a/cmd/jiri/init.go
+++ b/cmd/jiri/init.go
@@ -14,6 +14,7 @@
 
 	"fuchsia.googlesource.com/jiri"
 	"fuchsia.googlesource.com/jiri/analytics_util"
+	"fuchsia.googlesource.com/jiri/cipd"
 	"fuchsia.googlesource.com/jiri/cmdline"
 )
 
@@ -206,6 +207,10 @@
 		return err
 	}
 
+	if err := cipd.CopyCIPDToDirectory(filepath.Join(jiri.RootMetaDir, "bin")); err != nil {
+		return fmt.Errorf("failed copy cipd to %q: %v", filepath.Join(jiri.RootMetaDir, "bin"), err)
+	}
+
 	// TODO(phosek): also create an empty manifest
 
 	return nil