# shellcheck shell=bash
TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE:-name_namespace}"
TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL:-󱃾}"
TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL_COLOUR="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL_COLOUR:-255}"
TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SEPARATOR="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SEPARATOR:-󰿟}"

generate_segmentrc() {
	read -r -d '' rccontents <<EORC
# Kubernetes config context display mode {"name_namespace", "name", "namespace"}.
# export TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE}"
# Kubernetes config context symbol.
# export TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL}"
# Kubernetes config context symbol colour.
# export TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL_COLOUR="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL_COLOUR}"
# Separator for display mode "name_namespace"
# TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SEPARATOR="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SEPARATOR}"
EORC
	echo "$rccontents"
}

run_segment() {
	__process_settings
	if ! type kubectl >/dev/null 2>&1; then
		return 0
	fi
	k_context=$(kubectl config current-context)
	if [ -z "$k_context" ]; then
		return 0
	fi
	k_display="#[${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL_COLOUR}]${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL} #[fg=${TMUX_POWERLINE_CUR_SEGMENT_FG}]"
	if [ "${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE}" = "name" ]; then
		echo -n "${k_display}${k_context}"
	else
		#       CURRENT NAME   CLUSTER AUTHINF NAMESPACE
		read -r _unused k_name _unused _unused k_namespace < <(kubectl config get-contexts "${k_context}" --no-headers)
		k_namespace="${k_namespace:-default}"
		if [ "${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE}" = "namespace" ]; then
			echo -n "${k_display}${k_namespace}"
		elif [ "${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE}" = "name_namespace" ]; then
			echo -n "${k_display}${k_name}${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SEPARATOR}${k_namespace}"
		fi
	fi
}

__process_settings() {
	if [ -z "$TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE" ]; then
		export TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_DISPLAY_MODE}"
	fi
	if [ -z "$TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL" ]; then
		export TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL}"
	fi
	if [ -z "$TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL_COLOUR" ]; then
		export TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL_COLOUR="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SYMBOL_COLOUR}"
	fi
	if [ -z "$TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SEPARATOR" ]; then
		export TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SEPARATOR="${TMUX_POWERLINE_SEG_KUBERNETES_CONTEXT_SEPARATOR}"
	fi
}
