#!/bin/zsh
#####################################################################

DEPENDENCIES+=(tmux scwrypts)

use omni --group remote

#####################################################################

USAGE__description="
	A program which automatically connects to any available connections
	described in the configuration file.
	  (configure with 'scwrypts remote configure')

	The omni-session is running it's own wrapper TMUX server with a special
	config. In the wrapper session, 'M-s' is overwritten as the prefix.
	Switch between connections by using 'M-s' followed by the session ID
	number (or use any other default default tmux navigation command). Full
	configuration can be found here:
	  - $(scwrypts.config.group remote root)/omni/tmux.conf

	Shut-down the omni-session by pressing 'M-Q' (Q not q! ALT + SHIFT + Q)

	Disconnect (but leave the session running) with 'M-s, d'

	A background process periodically attempts to refresh lost connections.
	Immediate retry can be forced with 'M-R'.

	Running this command in an existing tmux session will likely result
	in an infinite loop, so:
	  - don't run the omni-session in a TMUX session
	  - don't connect to the omni-session directly (always use this scwrypt)
"

#####################################################################

MAIN() {
	[[ $TERM =~ tmux ]] && echo.error "\n Cannot run tmux-omni within a tmux session!\n  "

	local BACKGROUND_LAUNCH=false

	local _S
	while [[ $# -gt 0 ]]
	do
		_S=1
		case $1 in
			--background ) BACKGROUND_LAUNCH=true ;;
		esac
		[[ $_S -le $# ]] \
			&& shift $_S \
			|| echo.error "missing argument for '$1'" \
			|| shift $# \
			;
	done

	utils.check-errors --fail

	local SCWRYPTS_ROOT_REMOTE="$(scwrypts.config.group remote root)"

	remote.omni.tmux list-sessions 2>/dev/null | grep -v omni-manager | grep -qi omni || {
		echo.status "initializing omni server"
		remote.omni.tmux kill-session -t=omni-manager >/dev/null 2>&1

		echo.debug "${SCWRYPTS_ROOT_REMOTE}/tmux/tmux.conf"
		remote.omni.tmux -f "${SCWRYPTS_ROOT_REMOTE}/tmux/tmux.conf" new -d -s omni \
			"echo searching for first connection...; sleep 10" \; \
			split-window "sleep 1; TMUX= tmux -L ${OMNI_SOCKET} a -t=omni-manager" \; \
			move-window -t 99 \;


		remote.omni.tmux new -d -s omni-manager "${SCWRYPTS_ROOT_REMOTE}/tmux/manager"
	}

	[[ $BACKGROUND_LAUNCH =~ true ]] && {
		echo.success "omni server activated"
		return 0
	}

	echo.status 'connecting to omni server'
	remote.omni.tmux a -t=omni
}
