#!/usr/bin/env bash
set -euo pipefail

usage() {
  cat <<'EOF'
Usage:
  HYPERTWIST_REMOTE_WINDOWS_PASSWORD=... \
    scripts/run-hypertwist-remote-unreal-automation-sequence.sh \
      --filter HyperTwist.FirstParty.Skill.PhaseS3A.ContinuityResumeCoverage \
      --filter HyperTwist.FirstParty.Skill.PhaseS3A.AuthoritativeStoreRead

Options:
  --filter <automation-filter>
      Required. May be repeated. Filters are run sequentially in the order given.

  --report-prefix <name>
      Optional prefix for per-filter report names.

  --extra-arg <value>
      Append an extra UnrealEditor-Cmd.exe argument to every filter run.

  --dry-run
      Print the underlying wrapper invocations instead of executing them.
EOF
}

filters=()
report_prefix=""
dry_run="false"
extra_args=()

while [[ $# -gt 0 ]]; do
  case "$1" in
    --filter)
      filters+=("${2:-}")
      shift 2
      ;;
    --report-prefix)
      report_prefix="${2:-}"
      shift 2
      ;;
    --extra-arg)
      extra_args+=("${2:-}")
      shift 2
      ;;
    --dry-run)
      dry_run="true"
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      usage >&2
      exit 1
      ;;
  esac
done

if [[ ${#filters[@]} -eq 0 ]]; then
  echo "Provide at least one --filter." >&2
  exit 1
fi

script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
single_wrapper="${script_dir}/run-hypertwist-remote-unreal-automation.sh"

if [[ ! -x "$single_wrapper" ]]; then
  echo "Expected executable wrapper at $single_wrapper" >&2
  exit 1
fi

sanitize_report_name() {
  printf '%s' "$1" | sed 's/[^[:alnum:]._+-]/_/g'
}

for filter in "${filters[@]}"; do
  report_name="$(sanitize_report_name "$filter")"
  if [[ -n "$report_prefix" ]]; then
    report_name="${report_prefix}-$(sanitize_report_name "$filter")"
  fi

  command=(
    "$single_wrapper"
    --filter "$filter"
    --report-name "$report_name"
  )

  for extra_arg in "${extra_args[@]}"; do
    command+=(--extra-arg "$extra_arg")
  done

  if [[ "$dry_run" == "true" ]]; then
    printf '%q ' "${command[@]}"
    printf '\n'
    continue
  fi

  echo "Running remote Unreal automation filter: $filter"
  "${command[@]}"
done
