#!/bin/bash

[ -n "$GCLOUD_AUTH" ] || {
  exit 0
}
[ -x "$1" ] || {
  echo "First argument should be an executable" >&2
  exit 1
}
[ -n "$2" ] || {
  echo "Second argument should be a commit hash" >&2
  exit 1
}

umask 077

TMPDIR=$(mktemp -d)
cleanup() {
  exit_code=$?
  trap - EXIT INT
  rm -rf ${TMPDIR}
  exit ${exit_code}
}
trap cleanup EXIT INT

GCLOUD_JSON=${TMPDIR}/.gcloud.json
[ -z "${GCLOUD_AUTH}" ] || echo "${GCLOUD_AUTH}" >${GCLOUD_JSON}
[ -s "${GCLOUD_JSON}" ] || {
  echo "gcloud auth not defined" >&2
  exit 1
}

BOTO_CONF=${TMPDIR}/.boto
[ -s "${BOTO_CONF}" ] || cat >${BOTO_CONF} <<END
[Credentials]
gs_service_key_file = ${GCLOUD_JSON}
[Boto]
https_validate_certificates = True
[GSUtil]
content_language = en
default_api_version = 2
default_project_id = rancher-dev
END

BUILD_NAME=$(basename $1)-$2
(cd $(dirname $1) && sha256sum $(basename $1)) >${TMPDIR}/${BUILD_NAME}.sha256sum
cp $1 ${TMPDIR}/${BUILD_NAME}

[ -d "${TMPDIR}/gsutil" ] || curl -sfL https://storage.googleapis.com/pub/gsutil.tar.gz | tar xz -C ${TMPDIR}

HOME=${TMPDIR}
PATH=${PATH}:${HOME}/gsutil

gsutil cp ${TMPDIR}/${BUILD_NAME}* gs://k3s-ci-builds || exit 1

echo "Build uploaded" >&2
echo "https://storage.googleapis.com/k3s-ci-builds/${BUILD_NAME}"