#!/usr/bin/env bash
set -euo pipefail
source "$SHELLOPS_DIR/.envrc"
import "$SHELLOPS_DIR/lib/rust.api.sh"

USAGE="$(cat <<EOF
Runs Rust branch coverage and enforces a minimum threshold.

Usage: action rust coverage [-h,--help] [-t,--threshold PERCENT] [project-dir]

Arguments:
  project-dir    Directory containing the Cargo workspace. Defaults to current directory.

Flags:
  -t, --threshold    Minimum branch coverage percent (default: 90).
  -h, --help         Show this help text.
EOF
)"

function main() {
  local project_dir="."
  local threshold="90"

  parse_args project_dir threshold "$@"
  cd "$project_dir"

  rust_coverage_workspace "$threshold"
}

function parse_args() {
  local -n _project_dir=$1
  local -n _threshold=$2
  shift 2

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -h|--help) log "$USAGE"; exit 0 ;;
      -t|--threshold)
        _threshold="${2:?--threshold requires a value}"
        shift
        ;;
      -*)
        error "Unknown option: $1"
        exit 1
        ;;
      *)
        _project_dir="$1"
        ;;
    esac
    shift
  done
}

if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
  main "$@"
fi
