#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

PACKAGE="thesa"

EXTRA_ARGS=()
DRY_RUN=0

while [[ "$#" -gt 0 ]]; do
  arg="$1"
  shift

  case "$arg" in
    --dry-run)
      DRY_RUN=1
      ;;
    -h|--help)
      echo "Usage: $0 [--dry-run] [additional cargo publish args...]"
      echo "Example: $0 --dry-run"
      echo "Example: $0 -- --allow-dirty"
      exit 0
      ;;
    --)
      EXTRA_ARGS+=("$@")
      break
      ;;
    *)
      EXTRA_ARGS+=("$arg")
      ;;
  esac
done

if [ -z "${CARGO_REGISTRY_TOKEN:-}" ] && [ ! -f "${HOME}/.cargo/credentials" ]; then
  echo "Tip: set CARGO_REGISTRY_TOKEN for unattended publishing"
fi

cd "$PROJECT_DIR"

if [ "$DRY_RUN" -eq 1 ]; then
  echo "Running publish dry-run for package '$PACKAGE'"
  cargo publish --package "$PACKAGE" --dry-run "${EXTRA_ARGS[@]}"
  exit 0
fi

echo "Publishing package '$PACKAGE'"
cargo publish --package "$PACKAGE" "${EXTRA_ARGS[@]}"
