#!/bin/bash

_appsh_parse_opts() {
  local prev=""
  for ((i=0, j=0; i < ${#COMP_WORDS[@]}; i++, j++)); do
    if [ "$prev" == -n ]
    then
      echo "local has_n=${COMP_WORDS[$i]}"
    elif [ "$prev" == -i ]
    then
      echo "local has_i=${COMP_WORDS[$i]}"
    fi
    prev="${COMP_WORDS[$i]}"
  done
}

_complete_appsh() {
  COMPREPLY=()
  local cur="${COMP_WORDS[COMP_CWORD]}"
  local prev="${COMP_WORDS[COMP_CWORD-1]}"
  local opts

  if [ $COMP_CWORD == 1 ]
  then
    opts="conf install list set-current start stop"
    COMPREPLY=($(compgen -W "${opts}" -- ${cur}))  
    return 0
  fi

  eval `_appsh_parse_opts`

  case $prev in
    -n)
      values=$(./app list -P name)
      COMPREPLY=($(compgen -W "$values" -- ${cur}))
      return 0
      ;;
    -i)
      if [ -n "$has_n" ]
      then
        values=$(./app list -n $has_n -P instance)
        COMPREPLY=($(compgen -W "$values" -- ${cur}))
        return 0
      fi
      ;;
  esac

  opts=""
  if [ -z "$has_n" ]
  then
    opts="$opts -n"
  else
    if [ -z "$has_i" ]
    then
      opts="$opts -i"
    fi
  fi

  COMPREPLY=($(compgen -W "${opts}" -- ${cur}))  
  set +x
}

complete -F _complete_appsh app