#!/usr/bin/env bash
set -euo pipefail

GCS_CRIO_SA=${GCS_CRIO_SA:-}

if [[ -z $GCS_CRIO_SA ]]; then
    echo "Skipping artifact upload to Google Cloud Bucket (no \$GCS_CRIO_SA set)"
else
    echo "Uploading artifacts to Google Cloud Bucket"
    echo "$GCS_CRIO_SA" >/tmp/key.json
    gcloud auth activate-service-account --key-file=/tmp/key.json

    # update the latest version marker file for the branch
    MARKER=$(git rev-parse --abbrev-ref HEAD)
    VERSION=$(git rev-parse HEAD)

    # if in detached head state, we assume we're on a tag
    if [[ $MARKER == HEAD ]]; then
        # use the major.minor as marker
        VERSION=$(git describe --tags --exact-match)
        MARKER=$(echo "$VERSION" | cut -c 2-5)
    fi
    echo "$VERSION" >"latest-$MARKER.txt"

    BUCKET=gs://cri-o
    gsutil cp "latest-$MARKER.txt" $BUCKET
fi
