#!/bin/bash
# Copyright (C) 2021 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -e

# cd into the repo root so all commands are independent of the cwd.
cd -P ${BASH_SOURCE[0]%/*}/..

GN_ARGS="$GN_ARGS"  # Allow to expand GN_ARGS from env for ccache.

set -u

DIR=out/tmp_tracebox
mkdir -p $DIR

function cleanup {
  rm -rf "$DIR"
  echo "Deleted temp working directory $DIR"
}

#trap cleanup EXIT

function is_mac {
  ! test -d /proc
  return $?
}

VERSION="$(tools/write_version_header.py --stdout)"

# Allow overriding the build targets via the cmdline (for testing).
if [ "$#" -gt 0 ]; then
  COMBOS="$@"
else
  COMBOS="android-arm android-arm64 android-x86 android-x64"
fi

for COMBO in $COMBOS; do
  IFS=- read PLATFORM ARCH <<< "$COMBO"
  echo "Building for $COMBO"
  rm -rf $DIR
  mkdir -p $DIR
  GN_ARGS="$GN_ARGS is_debug=false monolithic_binaries = true"
  GN_ARGS="$GN_ARGS target_os = \"$PLATFORM\" target_cpu = \"$ARCH\""
  set -x
  tools/gn gen $DIR --args="$GN_ARGS"
  tools/ninja -C $DIR tracebox
  set +x
  BINARY=$DIR/stripped/tracebox
if which shasum; then
  NEW_SHA=$(shasum $BINARY | cut -f1 -d' ') # Mac OS
else
  NEW_SHA=$(sha1sum $BINARY | cut -f1 -d' ') # Linux
fi
  FULL_NAME=tracebox-$COMBO-$NEW_SHA

  set -x
  gsutil cp -n -a public-read $BINARY gs://perfetto/$FULL_NAME
  sed -e \
      "s/'$COMBO': '.*/'$COMBO': '$NEW_SHA',  # $VERSION/" \
      -i .tmp tools/record_android_trace
  set +x
  rm -f tools/record_android_trace.tmp
  echo ""
done
