#!/usr/bin/env bash

# Copyright 2016 The Fuchsia Authors
#
# Use of this source code is governed by a MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT

# This script builds Magenta and uploads various binaries to Google Storage.

# This script is expected to be executed on Jenkins, as part of a continuous
# builds infrastructure.

set -e
set -x

# We assume the following directory path:
# ./magenta/scripts
readonly SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
readonly MAGENTA_ROOT="$( cd "${SCRIPT_DIR}/.." && pwd )"
readonly GS_BUCKET="gs://fuchsia-build/magenta"

# Fetch the current git SHA: we upload the prebuilts with a SHA that corresponds
# to the SHA of the tree we built from.
cd "${MAGENTA_ROOT}"
readonly GIT_SHA="$(git log -1 --format=%H)"

# The list of targets to build.
readonly TARGETS=(
  "magenta-qemu-arm32"
  "magenta-qemu-arm64"
  "magenta-pc-x86-64"
)

# The list of output files to upload.
declare -A PREBUILTS=(
  ["build-magenta-qemu-arm32/magenta.bin"]="qemu-arm32/magenta.bin"
  ["build-magenta-qemu-arm32/magenta.elf"]="qemu-arm32/magenta.elf"
  ["build-magenta-qemu-arm32/upload/sysroot.tgz"]="qemu-arm32/sysroot.tgz"
  ["build-magenta-qemu-arm64/magenta.bin"]="qemu-arm64/magenta.bin"
  ["build-magenta-qemu-arm64/magenta.elf"]="qemu-arm64/magenta.elf"
  ["build-magenta-qemu-arm64/upload/sysroot.tgz"]="qemu-arm64/sysroot.tgz"
  ["build-magenta-pc-x86-64/magenta.bin"]="pc-x86-64/magenta.bin"
  ["build-magenta-pc-x86-64/magenta.elf"]="pc-x86-64/magenta.elf"
  ["build-magenta-pc-x86-64/upload/sysroot.tgz"]="pc-x86-64/sysroot.tgz"
  ["build-magenta-pc-x86-64/tools/bootserver"]="tools/bootserver"
  ["build-magenta-pc-x86-64/tools/loglistener"]="tools/loglistener"
  ["build-magenta-pc-x86-64/tools/mkbootfs"]="tools/mkbootfs"
)

# Make sure the build directory is clean
make spotless

# Build all the things.
for target in "${TARGETS[@]}"; do
  ENABLE_BUILD_SYSROOT=true make -j6 "${target}"  # -j option reflects the Fuchsia build bot servers.
done

# Bundle up sysroot tarballs
for target in "${TARGETS[@]}"; do
 mkdir -p "build-${target}/upload"
 tar cvzf "build-${target}/upload/sysroot.tgz" "build-${target}/sysroot"
done

# Upload the prebuilts to Google Storage.  We don't do any authentication here
# because we assume that the environment has been set up with auth already.
# For documentation, see: https://cloud.google.com/storage/docs/authentication
for key in "${!PREBUILTS[@]}"; do
  gsutil cp "${key}" "${GS_BUCKET}/${PREBUILTS[$key]}/${GIT_SHA}"
done
