# Download any build-specific configuration that has been uploaded.
# This allows top-level steps to override all subsequent steps.
buildkite-agent artifact download 'tools/bazeldefs/*' . || true

# Install packages we need. Docker must be installed and configured,
# as should Go itself. We just install some extra bits and pieces.
function install_pkgs() {
  export DEBIAN_FRONTEND=noninteractive
  while true; do
    if sudo -E apt-get update -q && sudo -E apt-get install -qy "$@"; then
      break
    fi
  done
}
install_pkgs make linux-libc-dev graphviz jq curl binutils gnupg gnupg-agent \
  gcc pkg-config apt-transport-https ca-certificates \
  software-properties-common rsync kmod systemd

# Install headers, only if available.
if test -n "$(apt-cache search --names-only "^linux-headers-$(uname -r)$")"; then
  install_pkgs "linux-headers-$(uname -r)"
elif test -n "$(apt-cache search --names-only "^linux-gcp-headers-$(uname -r | cut -d- -f1-2)$")"; then
  install_pkgs "linux-gcp-headers-$(uname -r | cut -d- -f1-2)"
fi

set -x

# Setup for parallelization with PARTITION and TOTAL_PARTITIONS.
export PARTITION=${BUILDKITE_PARALLEL_JOB:-0}
PARTITION=$((${PARTITION}+1)) # 1-indexed, but PARALLEL_JOB is 0-indexed.
export TOTAL_PARTITIONS=${BUILDKITE_PARALLEL_JOB_COUNT:-1}

# Set the system-wide Docker runtime name after the BuildKite branch name.
export RUNTIME="${BUILDKITE_BRANCH}-${BUILDKITE_BUILD_ID}"

# Ensure Docker has experimental enabled.
if [[ -n "${STAGED_BINARIES:-}" ]]; then
  # Used `runsc` from STAGED_BINARIES instead of building it from scratch.
  tmpdir="$(mktemp -d)"
  gsutil cat "$(STAGED_BINARIES)" | tar -C "$tmpdir" -zxvf - runsc
  chmod +x "$tmpdir/runsc"
  "$tmpdir/runsc" install --experimental=true --runtime="${RUNTIME}" \
    -- "${RUNTIME_ARGS:-}"
  rm -rf "$tmpdir"
else
  make sudo TARGETS=//runsc:runsc \
    ARGS="install --experimental=true --runtime=${RUNTIME} -- ${RUNTIME_ARGS:-}"
fi
# WARNING: We may be running in a container when this command executes.
# This only makes sense if Docker's `live-restore` feature is enabled.
sudo systemctl restart docker

# Helper for benchmarks, based on the branch.
if test "${BUILDKITE_BRANCH}" = "master"; then
  export BENCHMARKS_OFFICIAL=true
else
  export BENCHMARKS_OFFICIAL=false
fi

# Clear existing profiles.
sudo rm -rf /tmp/profile

# Allow to read dmesg for all users. It is required for the syslog test.
sudo sysctl -w kernel.dmesg_restrict=0

# Download credentials, if a release agent.
if test "${BUILDKITE_AGENT_META_DATA_QUEUE}" = "release"; then
  # Pull down secrets.
  gcloud secrets versions access --secret="repo-key" --format='get(payload.data)' latest | tr '_-' '/+' | base64 -d  > repo.key

  # Configure the Docker credential helper (to push images).
  gcloud auth configure-docker -q
fi
