#!/bin/bash

set -e

# Run the default make target in a Go docker image with SSH agent forwarding.
# SSH agent forwarding is necessary to pull internal Go dependencies.

BUILDER_IMAGE=${BUILDER_IMAGE-golang:1.12.5}

# Return true if this script is running inside jenkins
function in_jenkins() {
  [ ! -z "${JENKINS_HOME-}" ]
}

# In jenkins, run using a Go docker image and forward the ssh agent
if in_jenkins; then
  # Create a clone to a temporary directory because docker produced files can be owned by root
  # which can cause issues cleaning the current workspace
  tmp_dir="$(mktemp -d)"
  git clone --local --no-hardlinks . "$tmp_dir"

  # Mount the tmp directory as /app and make it the working directory
  docker_args="${docker_args} -v $tmp_dir:/app -w /app"

  # Forward SSH agent
  docker_args="${docker_args} -v $SSH_AUTH_SOCK:$SSH_AUTH_SOCK -e SSH_AUTH_SOCK -e ADD_GHE=1"

  # Rerun this script in docker
  exec docker run ${docker_args} ${BUILDER_IMAGE} "./$(basename "$0")"
fi

if [ -n "$ADD_GHE" ]; then
  # Add GHE to known_hosts
  mkdir -p ~/.ssh/
  touch ~/.ssh/known_hosts
  ssh-keygen -f ~/.ssh/known_hosts -R git-aws.internal.justin.tv # remove old
  ssh-keyscan -t rsa git-aws.internal.justin.tv >> ~/.ssh/known_hosts
fi

make
