#!/usr/bin/env bash

_triton_default_words() {
	# main command
	local words=(
		-h --help
		--version
		-v --verbose
		help ?
		account whoami
		info
		keys
		create-instance create
		instances insts
		instance inst
		instance-audit
		start-instance start
		stop-instance stop
		reboot-instance reboot
		delete-instance delete
		wait-instance wait
		ssh
		images imgs
		image img
		packages pkgs
		package pkg
		networks
		network
	)
	echo "${words[*]}"
}

_triton_words() {
	local cmd=$1
	local curword=${COMP_WORDS[COMP_CWORD]}
	if [[ $cmd == $curword ]]; then
		COMPREPLY=($(compgen -W "$(_triton_default_words)" -- "$curword"))
		return
	fi

	# assume everything supports this
	local words=(-j --json -h --help)

	case "$cmd" in
	account|whoami) ;;
	info) ;;
	keys) ;;
	create|create-instance)
		words+=(-n --name --dry-run -w --wait -q --quiet)
		;;
	start|start-instance|stop|stop-instance|reboot|reboot-instance|delete|delete-instance)
		words=(-h --help -w --wait)
		;;
	wait|wait-instance)
		words+=(-q --quiet)
		;;
	insts|instances)
		words+=(-H -o -s)
		;;
	inst|instance) ;;
	images|imgs)
		words+=(-a --all -H -o -s -l --long)
		;;
	image|img) ;;
	packages|pkgs)
		words+=(-H -o -s -l --long)
		;;
	package|pkg) ;;
	networks)
		words+=(-H -o -s -l --long)
		;;
	network) ;;
	ssh)
		words+=()
		;;
	*)
		words=($(_triton_default_words))
		;;
	esac

	COMPREPLY=($(compgen -W "${words[*]}" -- "$curword"))
}

_triton() {
	local cur=$COMP_CWORD

	local i word
	for ((i = 1; i <= COMP_CWORD; i++)); do
		word=${COMP_WORDS[i]}
		if ((i < COMP_CWORD)) && [[ ${word:0:1} == '-' ]]; then
			continue
		fi
		_triton_words "$word"
		break
	done

}

complete -F _triton triton