# Zerocat Coreboot Machines --- Create very satisfying free software devices.
#
# Copyright (C) 2019, 2020, 2021, 2022  Kai Mertens <kmx@posteo.net>
#
# This file is part of Zerocat Coreboot Machines.
#
# Zerocat Coreboot Machines is free software: you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Zerocat Coreboot Machines is distributed in the hope that it will be
# useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with Zerocat Coreboot Machines.  If not, see <http://www.gnu.org/licenses/>.


# $1: message string, optional
yes_no_abort()
{
  declare reply=

  _read "${1:-Continue (yes|no|abort)? }"
  while [[ 1 ]]; do
    read -r reply
    [ "${reply,,}" = 'yes' ] &&
      return 0
    [ "${reply,,}" = 'no' ] &&
      return 1
    [ "${reply,,}" = 'abort' ] &&
      go_exit "$BASH_SOURCE" "$FUNCNAME" "$LINENO" "abort by user"
    _read "Please type “yes”, “no” or “abort”: "
  done
}

hit_enter()
{
  _read "Hit <return> to continue: "
  read -rs
  echo
}

# $1: variable (name reference) containing options, separated by space
#     Note: If dealing with paths, separate them with “/ ” instead of just “ ”.
select_option ()
{
  # Note all <space> characters will be replaced by a <space-tag>, and all combinations of “/<space-tag> ”
  # will be turned back to “/<space>”. This helps to distiguish options from substrings in case we are
  # dealing with paths containing white space.
  declare space='<%%space%%>'
  declare -n poptions=$1
  poptions=${poptions// /$space}
  poptions=${poptions//\/$space/\/ }
  declare -a adir=(${poptions})

  # multiple options?
  [ ${#adir[*]} -gt 1 ] && {
    _info "Multiple (${#adir[*]}) options found."
    _mesg "Please make your choice."
    poptions=''
    for i in ${adir[@]}
    do
      i=${i//$space/ }
      i=${i%\/}
      _mesg "${LIITEM}${i}"
      yes_no_abort "Select (yes|no|abort)? " && {
        poptions=${i}
        break
      }
    done
    [ "$poptions" != '' ] ||
      go_exit "$BASH_SOURCE" "$FUNCNAME" "$LINENO" "no option selected"
    return
  }
  poptions=${poptions%\/}
}
