# vyatta bash completion common functions 
#
# Copyright (c) 2019, AT&T Intellectual Property. All rights reserved.
#
# Copyright (c) 2010-2013, Vyatta, Inc.
# All rights reserved.
#
# Copyright (c) 2014-2015 by Brocade Communications Systems, Inc.
# All rights reserved.
#
# SPDX-License-Identifier: LGPL-2.1-only


# ensure ! is not used by shell for history, as it breaks CLI which uses !
builtin set +o histexpand

get_prefix_filtered_list ()
{
  # $1: prefix
  # $2: \@list
  # $3: \@filtered
  declare -a olist
  local pfx=$1
  pfx=${pfx#\"}
  eval "olist=( \"\${$2[@]}\" )"
  local idx=0
  for elem in "${olist[@]}"; do
    local sub=${elem#$pfx}
    if [[ "$elem" == "$sub" ]] && [[ -n "$pfx" ]]; then
      continue
    fi
    eval "$3[$idx]=\"$elem\""
    (( idx++ ))
  done
}

get_prefix_filtered_list2 ()
{
  # $1: prefix
  # $2: \@list
  # $3: \@filtered
  # $4: \@list2
  # $5: \@filtered2
  declare -a olist
  local pfx=$1
  pfx=${pfx#\"}
  eval "olist=( \"\${$2[@]}\" )"
  eval "local orig_len=\${#$2[@]}"
  local orig_idx=0
  local idx=0
  for (( orig_idx = 0; orig_idx < orig_len; orig_idx++ )); do
    eval "local elem=\${$2[$orig_idx]}"
    eval "local elem2=\${$4[$orig_idx]}"
    local sub=${elem#$pfx}
    if [[ "$elem" == "$sub" ]] && [[ -n "$pfx" ]]; then
      continue
    fi
    eval "$3[$idx]=\"$elem\""
    eval "$5[$idx]=\"$elem2\""
    (( idx++ ))
  done
}

is_elem_of () {
  local elem=$1
  local -a olist
  if [[ -z $2 ]]; then
    return 1
  fi
  eval "olist=( \"\${$2[@]}\" )"
  for e in ${olist[*]}; do
    if [[ "$e" == "$elem" ]]; then
      return 0
    fi
  done
  return 1
}
