#!/usr/bin/env bash

# SPDX-FileCopyrightText: 2021 Robin Vobruba <hoijui.quaero@gmail.com>
#
# SPDX-License-Identifier: Unlicense

# Exit immediately on each error and unset variable;
# see: https://vaneyckt.io/posts/safer_bash_scripts_with_set_euxo_pipefail/
set -Eeuo pipefail
#set -Eeu

script_dir=$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")
proj_dir=$(cd "$script_dir/.."; pwd)

function _is_win() {

  if [[ "$OSTYPE" == "cygwin" ]] \
      || [[ "$OSTYPE" == "msys" ]] \
      || [[ "$OSTYPE" == "win32" ]]
  then
    echo "true"
  else
    echo "false"
  fi
}

function _our_version() {

  if [ -n "${GITHUB_REF:-}" ]
  then
    # Apparently, this is the right way to get a tag name. Really?
    # See: https://github.community/t5/GitHub-Actions/How-to-get-just-the-tag-name/m-p/32167/highlight/true#M1027
    echo -n "${GITHUB_REF#refs/tags/}"
  else
    repo_dir="${1:-.}"
    git \
      -C "$repo_dir" \
      describe \
      --long \
      --dirty \
      --candidates=99 \
      --always \
      --first-parent \
      2> /dev/null \
      || echo "<UNKNOWN>"
  fi
}

var_names=()
set -a # All variables get exported when set, even without 'export' in front

# STOML is a simple TOML parser fo BASH.
# We use it to parse Cargo.toml.
# see: https://github.com/freshautomations/stoml/
STOML="$(which stoml || true)"
STOML="${STOML:-"target/tools/stoml"}"
if ! [ -e "$STOML" ]
then
	>&2 echo "ERROR: Please make sure that 'stoml' is available through your PATH or under '$STOML'."
	>&2 echo "       You may get it from <https://github.com/freshautomations/stoml>."
	>&2 echo "       Using these commands:"
	>&2 echo "       mkdir -p \"$(dirname "$STOML")\""
	>&2 echo "       wget https://github.com/freshautomations/stoml/releases/download/v0.7.0/stoml_linux_amd64 -O \"$STOML\""
	>&2 echo "       chmod +x \"$STOML\""
	exit 1
fi

CARGO_TOML="$proj_dir/Cargo.toml"

# Application name
NAME="${NAME:-$($STOML "$CARGO_TOML" package.name)}"
NAME="${NAME:-$(basename "$(pwd)")}"
var_names+=("NAME")

# Application version
VERSION="${VERSION:-$($STOML "$CARGO_TOML" package.version)}"
var_names+=("VERSION")

# Binary name
BINARY="${BINARY:-$NAME}"
var_names+=("BINARY")

# Our version
OUR_VERSION="${OUR_VERSION:-$(_our_version "$script_dir/..")}"
var_names+=("OUR_VERSION")
VERSION="$OUR_VERSION"
var_names+=("VERSION")

# Target specifics (arch, os, base-lib, ...)
TARGET="${TARGET:-}"
var_names+=("TARGET")

# Operating system (rust target string)
OS="${OS:-}"
var_names+=("OS")

# Environment file
ENV_FILE="${ENV_FILE:-${GITHUB_ENV:-}}"
var_names+=("ENV_FILE")

# The cargo executable name (might be `cargo` or `cross`)
CARGO="${CARGO:-cargo}"
var_names+=("CARGO")

# When CARGO is set to CROSS, this is set to `--target matrix.target`.
TARGET_FLAG="${TARGET_FLAG:-}"
var_names+=("TARGET_FLAG")

# Emit backtraces on panics.
RUST_BACKTRACE=1
var_names+=("RUST_BACKTRACE")

if [ -n "$OS" ]
then
  IS_WIN="$([ "$OS" = "windows-2019" ] && echo -n "true" || echo -n "false")"
else
  IS_WIN="${IS_WIN:-$(_is_win)}"
fi
var_names+=("IS_WIN")

STAGING="$NAME-$VERSION"
# When CARGO is set to CROSS, TARGET_DIR includes matrix.target.
TARGET_DIR="${TARGET_DIR:-target}"
if [ -n "$TARGET" ]
then
  #TARGET="$OSTYPE-$(uname -m)"
  STAGING="$STAGING-$TARGET"
  if [ "$CARGO" = "cross" ]
  then
    TARGET_DIR="$TARGET_DIR/$TARGET"
  fi
fi
var_names+=("STAGING")
var_names+=("TARGET_DIR")

if $IS_WIN
then
  BINARY="${BINARY}.exe"
fi
BINARY_DIR="$TARGET_DIR/release"
BINARY_PATH="$BINARY_DIR/$BINARY"
var_names+=("BINARY_DIR")
var_names+=("BINARY_PATH")
BINARY_DIR_MUSL="$TARGET_DIR/x86_64-unknown-linux-musl/release"
BINARY_PATH_MUSL="$BINARY_DIR_MUSL/$BINARY"
var_names+=("BINARY_DIR_MUSL")
var_names+=("BINARY_PATH_MUSL")

if $IS_WIN
then
  PACKAGE_ARCHIVE="${STAGING}.zip"
else
  PACKAGE_ARCHIVE="${STAGING}.tar.gz"
fi
var_names+=("PACKAGE_ARCHIVE")

for var_name in "${var_names[@]}"
do
  if [ "${OUTPUT:-}" = "true" ]
  then
    echo "$var_name=${!var_name}"
  fi
  if [ -n "$ENV_FILE" ]
  then
    echo "$var_name=${!var_name}" >> "$ENV_FILE"
  fi
done

set +a
