#!/usr/bin/env bash
set -Eeuo pipefail
command_name=${0##*/}
: "${TEST_MOCK_LOG:?TEST_MOCK_LOG must identify the isolated test log}"
printf '%q' "$command_name" >>"$TEST_MOCK_LOG"
for argument in "$@"; do printf ' %q' "$argument" >>"$TEST_MOCK_LOG"; done
printf '\n' >>"$TEST_MOCK_LOG"
if (($# == 1)) && [[ $1 == --version ]]; then printf 'gum version 0.14.0\n'; exit 0; fi
subcommand=${1:-}
if [[ $subcommand == --help || $subcommand == '' ]]; then exit 0; fi
if (($# >= 2)) && [[ ${!#} == --help ]]; then
  [[ ${GUM_FAIL_CAPABILITY:-} == "$subcommand" ]] && exit 98
  exit 0
fi
case $subcommand in
  style)
    [[ $# -gt 1 ]] && [[ ${!#} != *'\n'* ]] || exit 98
    if [[ -n ${GUM_STYLE_CAPTURE:-} ]]; then printf '%s' "${!#}" >"$GUM_STYLE_CAPTURE"; fi
    printf '%s\n' "${!#}"
    exit 0
    ;;
  table|pager)
    if [[ -n ${GUM_PAGER_CAPTURE:-} ]]; then cat >"$GUM_PAGER_CAPTURE"; else cat >/dev/null; fi
    exit 0
    ;;
  spin) exit 0 ;;
  choose|filter|input|confirm)
    if [[ -n ${GUM_CHOICES_CAPTURE:-} && ( $subcommand == choose || $subcommand == filter ) ]]; then
      : >"$GUM_CHOICES_CAPTURE"
      if [[ $subcommand == filter ]]; then
        shift 3
      else
        shift
      fi
      printf '%s\n' "$@" >>"$GUM_CHOICES_CAPTURE"
    fi
    script=${GUM_SCRIPT_FILE:-}; answer=''
    if [[ -n $script && -f $script ]]; then
      IFS= read -r answer <"$script" || answer=''
      tail -n +2 -- "$script" >"${script}.next"
      mv -- "${script}.next" "$script"
    fi
    case $subcommand in
      confirm) [[ $answer == y || $answer == Y ]] || exit 1; exit 0 ;;
      input) printf '%s\n' "$answer"; exit 0 ;;
      *) [[ -n $answer ]] && printf '%s\n' "$answer" || exit 1; exit 0 ;;
    esac
    ;;
  *) printf 'Unexpected gum subcommand: %s\n' "$subcommand" >&2; exit 99 ;;
esac
