#!/bin/bash

set -euxo pipefail

cd "$(dirname "$0")"

# requires toml package (apt-get install python3-toml)
CLI_VERSION="$(python -c 'import toml; fh = open("Cargo.toml"); data = toml.load(fh); print(data["package"]["version"])')"
export CLI_VERSION

build_and_upload() {
  local target="$1"
  local artefact="$2"
  echo "Building version $CLI_VERSION ($target: $artefact)"

  cargo build --release --target "$target"

  # Upload executables if they do not already exist
  export VERSIONED_GS_PATH="gs://reinfer-public/cli/bin/${target}/${CLI_VERSION}/$artefact"
  export LATEST_GS_PATH="gs://reinfer-public/cli/bin/${target}/latest/$artefact"

  if ! gsutil -q stat "$VERSIONED_GS_PATH"; then
    gsutil cp "../target/${target}/release/$artefact" "$VERSIONED_GS_PATH"
  fi

  # TODO (tommmiligan) Disable until we can overwrite files from CI
  # if ! gsutil -q stat "$LATEST_GS_PATH"; then
  #   gsutil cp "../target/${target}/release/$artefact" "$LATEST_GS_PATH"
  # fi
}

case $BUILD_PLATFORM in
  "ubuntu-20.04")
    build_and_upload "x86_64-unknown-linux-musl" "re"
    build_and_upload "x86_64-unknown-linux-gnu" "re"

    # Build and upload deb package
    cargo deb

    export VERSIONED_DEB_PATH="gs://reinfer-public/cli/debian/reinfer-cli_${CLI_VERSION}_amd64.deb"
    export LATEST_DEB_PATH="gs://reinfer-public/cli/debian/reinfer-cli_latest_amd64.deb"

    if ! gsutil -q stat "$VERSIONED_DEB_PATH"; then
            gsutil cp "../target/debian/reinfer-cli_${CLI_VERSION}_amd64.deb" "$VERSIONED_DEB_PATH"
    fi

    # TODO (tommmiligan) Disable until we can overwrite files from CI
    # if ! gsutil -q stat "$LATEST_DEB_PATH"; then
    #         gsutil cp "../target/debian/reinfer-cli_${CLI_VERSION}_amd64.deb" "$LATEST_DEB_PATH"
    # fi
    ;;
  "macos-10.15")
    build_and_upload "x86_64-apple-darwin" "re"
    build_and_upload "x86_64-pc-windows-gnu" "re.exe"

    ;;
  *)
    >&2 echo "fatal: unknown BUILD_PLATFORM '$BUILD_PLATFORM'"
    exit 1
    ;;
esac
