#!/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 executable
  gsutil cp "../target/${target}/release/$artefact" "gs://reinfer-public/cli/bin/${target}/${CLI_VERSION}/$artefact"
  gsutil cp "../target/${target}/release/$artefact" "gs://reinfer-public/cli/bin/${target}/latest/$artefact"
}

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
    gsutil cp "../target/debian/reinfer-cli_${CLI_VERSION}_amd64.deb" "gs://reinfer-public/cli/debian/reinfer-cli_${CLI_VERSION}_amd64.deb"
    gsutil cp "../target/debian/reinfer-cli_${CLI_VERSION}_amd64.deb" "gs://reinfer-public/cli/debian/reinfer-cli_latest_amd64.deb"
    ;;
  "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
