#!/bin/bash

_mtm-ssh-proxy() {
	# shellcheck disable=SC2034
	local cur prev words cword args
	_init_completion || return
	
	local -r CNF_ARGS="--help"
	local -r CMD_ARGS="status open close open-all close-all"
	local -r PROFILE_DIR=~/.config/mtm-ssh-proxy
	local -r TMP_DIR="/tmp/mtm-ssh-proxy-${USER}/proxy"
	
	if [[ ${COMP_WORDS[*]} == *"--help"* ]]; then
		return
	fi

	args=${CMD_ARGS}
	for arg in ${CNF_ARGS}; do
		if [[ ${COMP_WORDS[*]} != *"${arg}"* ]]; then
			args+=" ${arg}"
		fi
	done
	for arg in ${CMD_ARGS}; do
		if [[ ${COMP_WORDS[*]} == *" ${arg} "* ]]; then
			args=""
		fi
	done
	
	case $prev in
		--help | status | open-all | close-all) return;;
		open)
			local -r PROFILELIST=$(\ls "${PROFILE_DIR}/profiles")
			# shellcheck disable=SC2207
			COMPREPLY=($(compgen -W "${PROFILELIST}" -- "${COMP_WORDS[COMP_CWORD]}"))
			return
		;;
		close)
			local -r PROFILELIST=$(\ls "${TMP_DIR}")
			# shellcheck disable=SC2207
			COMPREPLY=($(compgen -W "${PROFILELIST}" -- "${COMP_WORDS[COMP_CWORD]}"))
			return
		;;
		*)
			# shellcheck disable=SC2207
			COMPREPLY=($(compgen -W "${args}" -- "${COMP_WORDS[COMP_CWORD]}"))
			return
		;;
	esac
} && complete -F _mtm-ssh-proxy mtm-ssh-proxy