# bash completion for the opensim command.
#
# No list of its own: the commands are the ones bin/opensim names (COMMANDOPTS), and what follows a command comes from the usage of
# that command (USAGE of libexec/<command>, one form a line): a word of the usage as it is (add, oar, caddy), a value by what its
# name says it is (GRID: the grids, SIMULATOR: the simulators of the grid given, REGION: its regions, INSTANCE: the instances,
# FILE, DIR, ARCHIVE: files), then the options the usage names. A value the usage gives another name (a name to choose, a port)
# is not completed.

# Where the suite is: beside the command, or OPENSIM_CLI_ROOT
_opensim_root()
{
  if [ -n "${OPENSIM_CLI_ROOT:-}" ]; then
    echo "$OPENSIM_CLI_ROOT"
    return
  fi
  local bin
  bin=$(command -v opensim 2>/dev/null) || return
  bin=$(readlink -f "$bin" 2>/dev/null || echo "$bin")
  dirname "$(dirname "$bin")"
}

# The etc folders to look in (OPENSIM_ETC_DIRS overrides them)
_opensim_etc()
{
  echo ${OPENSIM_ETC_DIRS:-/etc/opensim}
}

# The enabled instances (the links of robust.d and opensim.d), in lower case
_opensim_instances()
{
  local etc file
  for etc in $(_opensim_etc); do
    for file in "$etc"/*.d/*.ini; do
      [ -e "$file" ] && basename "$file" .ini
    done
  done | tr '[:upper:]' '[:lower:]' | sort -u
}

# Every instance, the disabled ones too (the configs of the grids and of their simulators)
_opensim_all_instances()
{
  local etc dir file
  for etc in $(_opensim_etc); do
    for dir in "$etc"/grids/*/; do
      [ -d "$dir" ] || continue
      basename "$dir"
      for file in "$dir"sims/*.ini; do
        [ -e "$file" ] && basename "$file" .ini
      done
    done
  done | tr '[:upper:]' '[:lower:]' | sort -u
}

# The nicks of the grids of this machine
_opensim_grids()
{
  local etc dir
  for etc in $(_opensim_etc); do
    for dir in "$etc"/grids/*/; do
      [ -d "$dir" ] && basename "$dir"
    done
  done | sort -u
}

# The simulators of a grid by their own names (without the grid before them); of every grid when none is given
_opensim_simulators() # grid
{
  local etc file name grid
  for etc in $(_opensim_etc); do
    for file in "$etc"/grids/${1:-*}/sims/*.ini; do
      [ -e "$file" ] || continue
      name=$(basename "$file" .ini)
      grid=$(basename "$(dirname "$(dirname "$file")")")
      name=${name#"$grid".}
      echo "${name#"$grid"_}"
    done
  done | sort -u
}

# The regions of a grid by their names, one a line
_opensim_regions() # grid
{
  local etc file
  for etc in $(_opensim_etc); do
    for file in "$etc"/grids/${1:-*}/sims/*/regions/*.ini; do
      [ -e "$file" ] && sed -n 's/^\[\(.*\)\][[:space:]]*$/\1/p' "$file"
    done
  done | sort -u
}

# The usage of a command, one form a line (opensim <command> ...), as its script says it
_opensim_usage() # command
{
  local file
  file=$(_opensim_root)/libexec/$1
  [ -r "$file" ] || return 0
  awk -v q="'" '
    !p && index($0, "USAGE=" q) == 1 { p = 1; $0 = substr($0, 8) }
    p {
      line = $0; last = (substr(line, length(line)) == q)
      if (last) line = substr(line, 1, length(line) - 1)
      sub(/^[ \t]+/, "", line)
      if (line ~ /^opensim /) print line
      if (last) exit
    }' "$file"
}

# A form of a usage as its parts, in _opensim_p (what stands at each place: a word, or a value by its name), _opensim_po (1: that
# place may be left out) and _opensim_o (an option, a tab, the name of its value or nothing)
_opensim_parse() # form
{
  local s=${1#opensim } token group=0 next=1 n i path=
  local -a tokens=() groups=() stack=() paths=() pathstack=()
  _opensim_p=() _opensim_po=() _opensim_pp=() _opensim_o=() _opensim_adds=0
  # A form that makes something (add, create): the name it takes in quotes is one to choose, not one that is there
  [[ " $1 " == *" add "* || " $1 " == *" create "* ]] && _opensim_adds=1
  s=${s#* }
  [ "$s" = "$1" ] && s=
  [ "${1#opensim }" = "${1#opensim * }" ] && s=
  while [ -n "$s" ]; do
    s=${s#"${s%%[![:space:]]*}"}
    [ -n "$s" ] || break
    case $s in
      \[*|\(*) stack+=("$group"); pathstack+=("$path"); group=$next; path="$path.$next"; next=$((next + 1)); s=${s#?}; continue ;;
      \]*|\)*) n=${#stack[@]}; if [ "$n" -gt 0 ]; then group=${stack[n-1]}; path=${pathstack[n-1]}; unset "stack[n-1]" "pathstack[n-1]"; fi; s=${s#?}; continue ;;
      \"*) token=${s#\"}; token=${token%%\"*}; s=${s#\"$token\"}; token="\"$token\"" ;;
      *) token=${s%%[][()[:space:]]*}; s=${s#"$token"} ;;
    esac
    [ -n "$token" ] || { s=${s#?}; continue; }
    tokens+=("$token"); groups+=("$group"); paths+=("$path.")
  done
  n=${#tokens[@]}
  for ((i = 0; i < n; i++)); do
    token=${tokens[i]}
    case $token in
      '|'|--|-|...) ;;
      -[a-z][a-z]*) ;;
      -*)
        # An option: several in one word (--publish|--ufw), its value after = or in the next word of the same group
        if [[ $token == *=* ]]; then
          _opensim_o+=("${token%%=*}"$'\t'"${token#*=}")
        elif [[ $token == *'|'-* ]]; then
          local part
          for part in ${token//|/ }; do _opensim_o+=("$part"$'\t'); done
        elif ((i + 1 < n)) && [ "${groups[i+1]}" = "${groups[i]}" ] && [[ ${tokens[i+1]} != -* && ${tokens[i+1]} != '|' && ${tokens[i+1]} != ... ]]; then
          _opensim_o+=("$token"$'\t'"${tokens[i+1]}")
          i=$((i + 1))
        else
          _opensim_o+=("$token"$'\t')
        fi
        ;;
      *)
        _opensim_p+=("$token")
        _opensim_po+=("$([ "${groups[i]}" = 0 ] && echo 0 || echo 1)")
        _opensim_pp+=("${paths[i]}")
        ;;
    esac
  done
}

# What a value is, by its name in a usage: grid, simulator, region, instance, file, or nothing known
_opensim_kinds() # name
{
  local kinds=
  case $1 in *GRID*) kinds+=" grid" ;; esac
  case $1 in *SIMULATOR*) kinds+=" simulator" ;; esac
  case $1 in *REGION*) kinds+=" region" ;; esac
  case $1 in *INSTANCE*) kinds+=" instance" ;; esac
  case $1 in *FILE*|*DIR*|*ARCHIVE*) kinds+=" file" ;; esac
  echo $kinds
}

# Whether a place of a usage is a word to type as it is (small letters), not a value
_opensim_is_word() # part
{
  [[ $1 =~ ^[a-z] ]]
}

_opensim()
{
  local cur prev command root
  COMPREPLY=()
  cur=${COMP_WORDS[COMP_CWORD]}
  prev=${COMP_WORDS[COMP_CWORD-1]}
  root=$(_opensim_root)
  if [ "$COMP_CWORD" = 1 ]; then
    COMPREPLY=( $(compgen -W "$(sed -n 's/^COMMANDOPTS=//p' "$root/bin/opensim" 2>/dev/null | tr ',' ' ') --version --layout --help" -- "$cur") )
    return
  fi
  command=${COMP_WORDS[1]}
  if [ "$command" = --version ]; then
    COMPREPLY=( $(compgen -W "-v" -- "$cur") )
    return
  fi

  local form word part alt kind option value words_all= i j k applies expecting=0 grid typed
  local -a forms=() typed_words=() options=() values=() names=() lines=()
  while IFS= read -r form; do forms+=("$form"); done < <(_opensim_usage "$command")
  # Every word the usages of the command have: one of them typed is that word, never a value
  for form in ${forms[@]+"${forms[@]}"}; do
    _opensim_parse "$form"
    for part in ${_opensim_p[@]+"${_opensim_p[@]}"}; do
      _opensim_is_word "$part" && words_all+=" ${part//|/ } "
    done
  done
  words_all=${words_all//.../}

  for form in ${forms[@]+"${forms[@]}"}; do
    _opensim_parse "$form"
    # The words typed before this one, without the options and their values
    typed_words=()
    for ((i = 2; i < COMP_CWORD; i++)); do
      word=${COMP_WORDS[i]}
      if [[ $word == -* ]]; then
        for option in ${_opensim_o[@]+"${_opensim_o[@]}"}; do
          if [ "${option%%$'\t'*}" = "$word" ] && [ -n "${option#*$'\t'}" ]; then i=$((i + 1)); break; fi
        done
        continue
      fi
      typed_words+=("$word")
    done
    # Each one at its place in the form: a word of the usage, or the value that stands there
    applies=1 j=0 grid=
    for typed in ${typed_words[@]+"${typed_words[@]}"}; do
      while :; do
        if ((j >= ${#_opensim_p[@]})); then break; fi
        part=${_opensim_p[j]}
        if _opensim_is_word "$part"; then
          if [[ " ${part//|/ } " == *" ${typed} "* || " ${part//|/ } " == *" ${typed}... "* ]]; then
            [[ $part == *... ]] || j=$((j + 1))
            break
          elif [ "${_opensim_po[j]}" = 1 ]; then
            j=$((j + 1))
          else
            applies=0
            break
          fi
        elif [[ "$words_all" == *" $typed "* ]]; then
          # A word of the usages is never the value of this place: left out when it may be, else this is another form
          if [ "${_opensim_po[j]}" = 1 ]; then j=$((j + 1)); else applies=0; break; fi
        else
          [[ " $(_opensim_kinds "$part") " == *" grid "* ]] && grid=$typed
          [[ $part == *... ]] || j=$((j + 1))
          break
        fi
      done
      [ "$applies" = 1 ] || break
    done
    [ "$applies" = 1 ] || continue

    # After an option that takes a value: what its name says it is
    if [[ $prev == -* ]]; then
      for option in ${_opensim_o[@]+"${_opensim_o[@]}"}; do
        if [ "${option%%$'\t'*}" = "$prev" ] && [ -n "${option#*$'\t'}" ]; then
          expecting=1
          values+=("${option#*$'\t'}")
        fi
      done
      [ ${#values[@]} -gt 0 ] && continue
    fi
    for option in ${_opensim_o[@]+"${_opensim_o[@]}"}; do
      option=${option%%$'\t'*}
      # One given already is not offered again
      [[ " ${COMP_WORDS[*]:2:COMP_CWORD-2} " == *" $option "* ]] || options+=("$option")
    done
    # The place this word has: its words, the names of its values; the ones after it while it may be left out
    local skipped=" "
    for ((k = j; k < ${#_opensim_p[@]}; k++)); do
      part=${_opensim_p[k]}
      # Inside the group of a part left out ([GRID [SIMULATOR]]): not without it
      local inside=0 left
      for left in $skipped; do [[ ${_opensim_pp[k]} == "$left"?* ]] && inside=1; done
      [ "$inside" = 1 ] && break
      expecting=1
      if _opensim_is_word "$part"; then
        part=${part%...}
        for alt in ${part//|/ }; do names+=("word:$alt"); done
      elif [[ $part == \"* && $_opensim_adds = 1 ]]; then
        :
      else
        for kind in $(_opensim_kinds "$part"); do names+=("$kind:$grid"); done
      fi
      [ "${_opensim_po[k]}" = 1 ] || break
      skipped+="${_opensim_pp[k]} "
    done
  done

  # A value after its option
  if [ ${#values[@]} -gt 0 ]; then
    local kinds=" "
    for value in "${values[@]}"; do
      for kind in $(_opensim_kinds "$value"); do
        [[ "$kinds" == *" $kind "* ]] && continue
        kinds+="$kind "
        case $kind in
          file) COMPREPLY+=( $(compgen -f -- "$cur") ) ;;
          grid) COMPREPLY+=( $(compgen -W "$(_opensim_grids)" -- "$cur") ) ;;
        esac
      done
    done
    return
  fi
  # An option asked for, or nothing else to give: the options of the forms that apply
  if [[ $cur == -* ]] || [ "$expecting" = 0 ]; then
    COMPREPLY=( $(compgen -W "$(printf '%s\n' ${options[@]+"${options[@]}"} | sort -u | tr '\n' ' ')" -- "$cur") )
    return
  fi
  local name seen=" "
  for name in ${names[@]+"${names[@]}"}; do
    [[ "$seen" == *" $name "* ]] && continue
    seen+="$name "
    kind=${name%%:*} value=${name#*:}
    case $kind in
      word) COMPREPLY+=( $(compgen -W "$value" -- "$cur") ) ;;
      grid) COMPREPLY+=( $(compgen -W "$(_opensim_grids)" -- "$cur") ) ;;
      simulator) COMPREPLY+=( $(compgen -W "$(_opensim_simulators "$value")" -- "$cur") ) ;;
      instance)
        case $command in
          enable|disable) COMPREPLY+=( $(compgen -W "$(_opensim_all_instances)" -- "$cur") ) ;;
          *) COMPREPLY+=( $(compgen -W "$(_opensim_instances)" -- "$cur") ) ;;
        esac
        ;;
      region)
        # A name may have spaces: each one whole, written as the shell reads it
        lines=()
        while IFS= read -r word; do lines+=("$word"); done < <(_opensim_regions "$value")
        for word in ${lines[@]+"${lines[@]}"}; do
          [[ "$word" == "${cur//\\/}"* ]] && COMPREPLY+=( "$(printf '%q' "$word")" )
        done
        ;;
      file) COMPREPLY+=( $(compgen -f -- "$cur") ) ;;
    esac
  done
}

complete -F _opensim opensim
