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

USAGE="$(cat <<EOF
Installs and selects a Rust toolchain.

Usage: action rust setup [-h,--help] [toolchain] [component...]

Arguments:
  toolchain      Rust toolchain to install and select. Defaults to stable.
  component      Optional rustup components to install, e.g. rustfmt clippy.

Flags:
  -h, --help    Show this help text.
EOF
)"

function main() {
  local toolchain="stable"
  local components=()

  parse_args toolchain components "$@"
  rust_setup "$toolchain" "${components[@]}"
}

function parse_args() {
  local -n _toolchain=$1
  local -n _components=$2
  shift 2

  local toolchain_set=false

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -h|--help) log "$USAGE"; exit 0 ;;
      -*)
        error "Unknown option: $1"
        exit 1
        ;;
      *)
        if [[ "$toolchain_set" == false ]]; then
          _toolchain="$1"
          toolchain_set=true
        else
          _components+=("$1")
        fi
        ;;
    esac
    shift
  done
}

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