
function _screenshot2()
{
  local cur prev opts cmds device_selected
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  prev="${COMP_WORDS[COMP_CWORD-1]}"
  prevprev="${COMP_WORDS[COMP_CWORD-2]}"
  opts="-d -e -l -s"
  device_selected=""

  # if there are multiple devices plugged in, prompt the user to specify which
  # so that the list of installed packaged can be fetched from the device

  case "${prev}" in
      -d|-e)
          device_selected="${prev}"
          ;;
  esac

  # use device set by serial number
  case "${prevprev}" in
      -s)
          device_selected="-s ${prev}"
          ;;
  esac

  if [ -z "$device_selected" ] && [ "$prev" != "-s" ]; then
      local num_devices=$(( $(adb devices 2>/dev/null|wc -l) - 2 ))
      if [ "$num_devices" -gt "1" ]; then
          # With multiple devices, you must choose a device first.
          COMPREPLY=( $(compgen -W "-s" -- ${cur}) )
          return 0
      fi
  fi

  case "${cur}" in
      -*)
          COMPREPLY=( $(compgen -W "$opts" -- ${cur}) )
          return 0
          ;;
  esac

  case "${prev}" in
      -s)
          if [ -z "$device_selected" ]; then
              # Use 'adb devices' to list serial numbers.
              COMPREPLY=( $(compgen -W "$(adb devices|grep 'device$'|cut -f1)" -- ${cur} ) )
              return 0
          fi
          ;;
  esac

  COMPREPLY=( $(compgen -o dirnames -- ${cur}) )
  return 0
}
complete -F _screenshot2 screenshot2

# Local variables:
# mode: shell-script
# sh-basic-offset: 4
# sh-indent-comment: t
# indent-tabs-mode: nil
# End:
# ex: ts=4 sw=4 et filetype=sh
