#!/usr/bin/env bash

# Copyright 2020 Google LLC
#
# 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
#
#     https://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 -eu
cd "${0%/*}"/..

source ./hack/util.sh

project_id="${PROJECT_ID:=$(gcloud config get-value project)}"
bucket="${RELEASE_BUCKET:=${project_id}_cloudbuild}"
git_sha="$(git rev-parse HEAD)"

VERSION="${VERSION:-$(version)}"

if [[ -z ${EXTRA_TAG+x} ]]; then
  EXTRA_TAG=""
fi

if ! gsutil ls "gs://${bucket}/${VERSION}" > /dev/null 2>&1; then
  >&2 gcloud builds submit . \
    "--project=${project_id}" \
    --config=cmd/generate-release/cloudbuild.yaml \
    "--substitutions=_GIT_SHA=${git_sha},_RELEASE_BUCKET=${bucket},_VERSION=${VERSION},_EXTRA_TAG=${EXTRA_TAG}"
else
  >&2 echo "Using cached build"
fi

echo "${bucket}/${VERSION}"
