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

USAGE="$(cat <<EOF
Runs cargo-fuzz checks.

Usage: action rust fuzz [-h,--help] <check|replay|explore|explore-minutes> [project-dir] [target] [duration]

Arguments:
  mode           Fuzz mode: check, replay, explore, or explore-minutes.
  project-dir    Directory containing the fuzz package. Defaults to engine/parser.
  target         Fuzz target name. Defaults to lexer.
  duration       Exploration duration. Seconds for explore, minutes for explore-minutes. Defaults to 300.

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

function main() {
  local mode="" project_dir="engine/parser" target="lexer" seconds="300"

  parse_args mode project_dir target seconds "$@"

  case "$mode" in
    check) rust_fuzz_check "$project_dir" "$target" ;;
    replay) rust_fuzz_replay "$project_dir" "$target" ;;
    explore) rust_fuzz_explore "$project_dir" "$target" "$seconds" ;;
    explore-minutes) rust_fuzz_explore_minutes_nonblocking "$project_dir" "$target" "$seconds" ;;
    *)
      error "Unknown fuzz mode: $mode"
      log "$USAGE"
      exit 1
      ;;
  esac
}

function parse_args() {
  local -n _mode=$1
  local -n _project_dir=$2
  local -n _target=$3
  local -n _seconds=$4
  shift 4

  if [[ $# -eq 0 ]]; then
    log "$USAGE"
    exit 1
  fi

  if [[ "$1" == "-h" || "$1" == "--help" ]]; then
    log "$USAGE"
    exit 0
  fi

  _mode="$1"
  shift

  [[ $# -gt 0 ]] && _project_dir="$1" && shift
  [[ $# -gt 0 ]] && _target="$1" && shift
  [[ $# -gt 0 ]] && _seconds="$1" && shift

  while [[ $# -gt 0 ]]; do
    case "$1" in
      -h|--help) log "$USAGE"; exit 0 ;;
      *)
        error "Unknown argument: $1"
        log "$USAGE"
        exit 1
        ;;
    esac
  done
}

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