test -z "$DISPLAY" || return 0

PATH="$PATH:$HOME/.local/bin/server"

## STACKSPIN
export STACKSPIN="${STACKSPIN:-$HOME/projects/stackspin}"
_stackspin_cluster_cache=/var/tmp/stackspin-cluster

# Stackspin CLI Wrapper:
# Initialize once with "stack select example.org",
# then it loads the last selected cluster on startup.
# Presumes a mapping like the following in your ssh config:
# Host example.org
#    Hostname [IP]
# This is a function so it can change directory.
stack() {
	test $# -lt 1 &&
		builtin cd "$STACKSPIN" &&
		echo "Usage: $0 <COMMAND> [args...]" &&
		echo "Inbuilt commands: select, sso, user, exec, pod, occ, push" &&
		return 1
	local command="$1"
	shift
	case "$command" in
	# stackspin administration
	(select)
		export _cluster_name="$1"
		export _cluster_ip="$(ssh -G "$_cluster_name" | grep --max-count 1 "^hostname " | cut -d " " -f2-)"
		export CLUSTER_DIR="$STACKSPIN/clusters/$_cluster_name"
		export KUBECONFIG="$CLUSTER_DIR/kube_config_cluster.yml"
		# Uncomment the line below to always use the main stackspin repo, even when running in a fork.
		#export GITLAB_CI="true"
		echo Selected "$_cluster_name" with IP "$_cluster_ip"
		echo "$_cluster_name" >"$_stackspin_cluster_cache"
		test "$PWD" = "$HOME" && builtin cd "$STACKSPIN"
		;;
	(sso) builtin cd "$STACKSPIN"
		"$0" exec dashboard --container backend -- flask "$@";;
	(user|app)
		if test "$1" = "init"
		then mail="$2"
			shift 2
			"$0" user create "$mail"
			"$0" user update "$mail" name "$*"
			echo "Initialized user '$*' with email '$mail'"
		else "$0" sso cli "$command" "$@"
		fi;;
	# app clis via kubectl
	(occ) "$0" exec nc-nextcloud -it -- su www-data -s /bin/bash -c "php $command $*";;
	(exec)
		if ! pod=$("$0" pod "$1-\(0\|[0-f]\+\)")
		then echo "No pod found for $1" >&2
			return 1
		fi
		shift
		kubectl exec -n $(echo $pod) "$@";;
	(pod)
		local podname=$1
		shift
		kubectl get pods --all-namespaces --field-selector="status.phase=Running" -o=custom-columns=S:.metadata.namespace,N:.metadata.name --no-headers "$@" | grep --color=never "$podname";;
	(push)
		git commit -a
		git push
		flux reconcile source git -n flux-system "$(basename $(git rev-parse --show-toplevel))";;
	# stackspin bare
	(*) if which "$0-$command" >/dev/null 2>&1
		then "$0-$command" "$@"
			return $?
		fi
		builtin cd "$STACKSPIN"
		# Since the install command can also be given bare to install stackspin itself
		if test $# -gt 0 -a "$command" = install
		then "./install/install-$1.sh" || ./install/install-app.sh "$@"
		else python3 -m stackspin "$_cluster_name" "$command" "$@"
			# pip3 install -r requirements.txt
		fi;;
	esac
}
cat "$_stackspin_cluster_cache" 2>/dev/null |
	while read cluster; do stack select "$cluster"; done