#!/bin/bash
#
# 	pkg - TAB auto completion script for Pkg
#
#   By Scott Jarvis (sc0ttman)
#
#   Copyright (c) 2013 Puppy Linux Community
#
#   This program 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.
#
#   This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.

# set work dir
WORKDIR=~/pkg
[ -f ${HOME}/.pkg/pkgrc ] && . ${HOME}/.pkg/pkgrc #150913

_pkg() {

  local cur prev opts
  opts=''
  COMPREPLY=()

	# get settings from rc file
	. ${HOME}/.pkg/pkgrc

  # if current option to complete is just a dash,
  # dont complete anything and exit
  if [ "${COMP_WORDS[COMP_CWORD]}" = '-' ];then
    return 0
  fi

  # if the 'previous' option is 'pkg', user is completing a pkg command,
  # so shift args: this will skip listing package names
  if [ "${COMP_WORDS[COMP_CWORD-1]}" = "pkg"     ] || \
     [ "${COMP_WORDS[COMP_CWORD-1]}" = "usage"   ] || \
     [ "${COMP_WORDS[COMP_CWORD-1]}" = '--usage' ]
  then
    shift
  fi

  # get current option from array
  cur="${COMP_WORDS[COMP_CWORD]}"

  # thi is the word/option yet to be completed
  prev="${COMP_WORDS[COMP_CWORD-1]}"

	# convert commas to spaces
	cur="${cur//,/ }"
	prev="${prev//,/ }"

	# avoid argument list too long error
	rm /tmp/pkg_tab_opts &>/dev/null

	# set completion to show pkgs from current repo or all
	case "$PKGSCOPE" in
		one) PKGSEARCH='pkg -n'  ;;
		all) PKGSEARCH='pkg -na' ;;
	esac

	# context sensitive file/dir/pkg completion here
	# ...go through the options the user has typed (so far..),
	# and present these completions first
	case "${prev//,/ }" in

		--deb2*|deb2*|--dir2*|dir2*|--pet2*|pet2*|--sfs2*|sfs2*|--tgz2*|tgz2*|--txz2*|txz2*)

			opts="`echo *;`" ;;

		--search-all|-sa|search-all|sa|--names-all|-na|names-all|na|add|get|get-only|status|ps|PS)

			opts="`echo $(pkg -na $2)`" ;;

		--names-exact|-ne|names-exact|ne)

			opts="`echo $(pkg -ne $2)`" ;;

		--names-exact-all|-nea|names-exact-all|nea)

			opts="`echo $(pkg -nea $2)`" ;;

		--repo|-r|--repo-list|-rl|--repo-info|-ri|--repo-update|-ru|repo|r|repo-list|rl|repo-info|ri|repo-update|ru|--rm-repo|rm-repo)

			[ ! "$2" ] && opts="`echo $(pkg -rl)`" || opts="`echo $(pkg -rl $2)`" ;;

		--repo-file-list|-rfl|repo-file-list|rfl)

			[ ! "$2" ] && opts="`echo $(pkg -rfl)`" || opts="`echo $(pkg -rfl $2)`" ;;

		--list-installed|-li|--uninstall|-u|list-installed|li|uninstall|u|--what-needs|-wn|what-needs|wn|'rm')

			[ ! "$2" ] && opts="`echo $(pkg -li)`" || opts="`echo $(pkg -li $2)`" ;;

		--list-downloaded|-ld|--delete|-l|list-downloaded|ld|delete|l)

			opts="`echo $(pkg -ld $2)`" ;;

		--install|-i|install|i)

			opts="`echo $(pkg -ld $2); echo *;`" ;;

		--extract|--unpack|extract|unpack|split)

			opts="`echo *; echo $(pkg -ld);`" ;;

		--contents|-c|contents|c)

			[ ! "$2" ] && opts="`echo $(pkg -ld); echo $(pkg -li); echo *;`" || opts="`echo $(pkg -ld $2); echo $(pkg -li $2)`" ;;

		--which-repo|-wr|which-repo|wr)

			opts="`echo $(pkg -wr $2)`" ;;

		--pkg-repack|-pr*|repack|pr)

			opts="`echo $(pkg -li $2)`" ;;

		--pkg-build-list|-pbl|build-list|pbl|--pkg-build|-pb|build|pb)

			opts="`echo $(pkg -pbl $2 2>/dev/null)`" ;;

		--pkg*|-p?|p?)

			opts="`echo $($PKGSEARCH $2); echo *;`" ;;

		--?*|-?*)

			opts="`echo $($PKGSEARCH $2) $(pkg -LI) * | sort | uniq;`" ;;
	esac

	# if pkg names list was built use that as $opts, or use opts as defined above
	if [ "$ops" != '' -o -f /tmp/pkg_tab_opts ];then
		COMPREPLY=( $(compgen -W "`cat /tmp/pkg_tab_opts`" -- ${cur//,/ }) )
		return 0
	elif [ "${opts//,/ }" != "" ];then
		COMPREPLY=( $(compgen -W "${opts//,/ }" -- ${cur//,/ }) )
		return 0
	fi

	# build list of funcs to show as part of our auto complete options
	local func_list=`pkg --func-list | cut -f2 -d' ' | cut -f1 -d'(' | tr '\n' ' '`

	# print out all the options, or context sensitive options (pkg $OPT $2)
	case "${cur//,/ }" in

		--*)

			opts="--ask --force --quiet --no-colour --no-color --all-pkgs --all --search --search-all --names --names-all --names-exact --names-exact-all --get --get-only --download --install --install-all --uninstall --uninstall-all --delete --delete-all --extract --unpack --clean --autoclean --deps --deps-all --deps-download --deps-check --pkg-update --pkg-build --pkg-build-list --pkg-repack --contents --list-installed --list-downloaded --list-deps --pkg-status --pkg-combine --sfs-combine --pkg-installed --which --which-repo --recursive-dep-check --repo --repo-info --repo-update --repo-convert --repo-list --repo-file-list --repo-pkg-scope --repo-dep-scope --bleeding-edge --add-source --update-sources --deb2pet --dir2pet --dir2sfs --dir2tgz --pet2sfs --pet2tgz --pet2txz --sfs2pet --tgz2pet --txz2pet --workdir  --welcome --what-needs --show-config --help --examples --func-list --help-all --version --usage all-pkgs add remove rm search search-all names names-all names-exact names-exact-all get get-only download install install-all uninstall uninstall-all delete delete-all extract unpack clean autoclean deps deps-all deps-download deps-check pkg-update update pkg-build build pkg-build-list pkg-repack repack contents list-installed list-downloaded list-deps pkg-status status pkg-combine combine sfs-combine pkg-installed which which-repo rdep-check repo repo-info repo-update repo-convert repo-list repo-file-list repo-pkg-scope repo-dep-scope bleeding-edge add-source update-sources deb2pet dir2pet dir2sfs dir2tgz pet2sfs pet2tgz pet2txz sfs2pet tgz2pet txz2pet workdir welcome what-needs show-config help examples func-list help-all version usage --add-repo add-repo --rm-repo rm-repo --pkg-split split"
			;;

		-?*)

			opts="-a -f -q -nc -s -ss -sa -ssa -n -na -ne -nea -g -go -d -i -ia -u -ua -l -la -e -ea -ed -ec -pu -pb -pbl -pr -c -li -LI -ld -le -LE -ps -PS -pc -sc -pi -w -wr -wn -r -ri -ru -rc -rl -rfl -h -ex -H -v"
			;;

		?*) # any other (not Pkg options), print pkg names, build script names, etc

			# get the search opt to pass, accept only -n or -na
			[ "$3" = "-na" ] && OPT="-na" || OPT="-n"

			# show repo pkgs (current repo or all repos)
			echo `pkg $OPT $2  2>/dev/null` > /tmp/pkg_tab_opts

			# include all installed pkgs
			echo `pkg -LI $2  2>/dev/null` >> /tmp/pkg_tab_opts

			# include the downloaded pkg files
			echo `pkg -ld $2  2>/dev/null` >> /tmp/pkg_tab_opts
      echo `ls -1 $WORKDIR  2>/dev/null` >> /tmp/pkg_tab_opts

			# include the build scripts
			echo `pkg -pbl $2 2>/dev/null` >> /tmp/pkg_tab_opts

			# include the local files and dirs in the completion list
			echo * >> /tmp/pkg_tab_opts

			# include Pkgs internal functions in the list
			#echo $func_list >> /tmp/pkg_tab_opts

      echo 'all-pkgs add remove rm search search-all names names-all names-exact names-exact-all get get-only download install install-all uninstall uninstall-all delete delete-all extract unpack clean autoclean deps deps-all deps-download deps-check pkg-update update pkg-build build pkg-build-list build-list pkg-repack repack contents list-installed list-downloaded list-deps pkg-status status pkg-combine combine sfs-combine pkg-installed which which-repo rdep-check repo repo-info repo-update repo-convert repo-list repo-file-list repo-pkg-scope repo-dep-scope bleeding-edge add-source update-sources deb2pet dir2pet dir2sfs dir2tgz pet2sfs pet2tgz pet2txz sfs2pet tgz2pet txz2pet workdir welcome what-needs show-config help examples func-list help-all version usage add-repo rm-repo split' >> /tmp/pkg_tab_opts

			sort -u /tmp/pkg_tab_opts > /tmp/pkg_tab_opts1
			mv /tmp/pkg_tab_opts1 /tmp/pkg_tab_opts

			;;

	esac

	# if pkg names list was built use that as $opts, or use opts as defined above
	if [ -f /tmp/pkg_tab_opts ];then
		COMPREPLY=( $(compgen -W "`cat /tmp/pkg_tab_opts`" -- ${cur//,/ }) )
	else
		COMPREPLY=( $(compgen -W "${opts//,/ }" -- ${cur//,/ }) )
	fi

	return $?
}

complete -o default -o nospace -F _pkg pkg

return $?
