internal/coordinator/remote: set up enviroment for SSH clients

Fixes golang/go#32430

Change-Id: I84281077328c864fb3ba6f81e3a4453848ce741e
Reviewed-on: https://go-review.googlesource.com/c/build/+/418104
Reviewed-by: Bryan Mills <bcmills@google.com>
Reviewed-by: Jenny Rakoczy <jenny@golang.org>
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gopher Robot <gobot@golang.org>
diff --git a/internal/coordinator/remote/ssh.go b/internal/coordinator/remote/ssh.go
index 702071d..2860271 100644
--- a/internal/coordinator/remote/ssh.go
+++ b/internal/coordinator/remote/ssh.go
@@ -332,6 +332,7 @@
 		}
 	}()
 	go func() {
+		ss.setupRemoteSSHEnv(bconf, workDir, f)
 		io.Copy(f, s) // stdin
 	}()
 	io.Copy(s, f) // stdout
@@ -476,6 +477,7 @@
 		}
 	}()
 	go func() {
+		ss.setupRemoteSSHEnv(bconf, workDir, f)
 		io.Copy(f, s) // stdin
 	}()
 	io.Copy(s, f) // stdout
@@ -483,6 +485,31 @@
 	cmd.Wait()
 }
 
+// setupRemoteSSHEnv sets up environment variables on the remote system.
+// This makes the new SSH session easier to use for Go testing.
+func (ss *SSHServer) setupRemoteSSHEnv(bconf *dashboard.BuildConfig, workDir string, f io.Writer) {
+	switch bconf.GOOS() {
+	default:
+		// A Unix system.
+		for _, env := range bconf.Env() {
+			fmt.Fprintln(f, env)
+		}
+		fmt.Fprintf(f, "GOPATH=%s/gopath\n", workDir)
+		fmt.Fprintf(f, "PATH=$PATH:%s/go/bin\n", workDir)
+		fmt.Fprintf(f, "export GOPATH PATH\n")
+		fmt.Fprintf(f, "cd %s/go/src\n", workDir)
+	case "windows":
+		for _, env := range bconf.Env() {
+			fmt.Fprintf(f, "set %s\n", env)
+		}
+		fmt.Fprintf(f, `set GOPATH=%s\gopath`+"\n", workDir)
+		fmt.Fprintf(f, `set PATH=$PATH;%s\go\bin`+"\n", workDir)
+		fmt.Fprintf(f, `cd %s\go\src`+"\n", workDir)
+	case "plan9":
+		// TODO
+	}
+}
+
 // WriteSSHPrivateKeyToTempFile writes a key to a temporary file on the local file system. It also
 // sets the permissions on the file to what is expected by OpenSSH implementations of SSH.
 func WriteSSHPrivateKeyToTempFile(key []byte) (path string, err error) {