#!/bin/sh
# Build the socktop display session: one window, N tiled panes, one per host.
# Pane index order is the swipe order.
set -eu

# shellcheck source=config.env
for c in /usr/local/etc/socktop-swipe.env "$(dirname "$0")/config.env"; do
	[ -r "$c" ] && . "$c" && break
done

: "${SOCKTOP_HOSTS:?no SOCKTOP_HOSTS -- is the config installed?}"
: "${SOCKTOP_SESSION:=socktop4}"
: "${SOCKTOP_BIN:=socktop}"

WIN="$SOCKTOP_SESSION:rack"

tmux kill-session -t "$SOCKTOP_SESSION" 2>/dev/null || true

first=1
for h in $SOCKTOP_HOSTS; do
	if [ "$first" = 1 ]; then
		tmux new-session -d -s "$SOCKTOP_SESSION" -n rack "$SOCKTOP_BIN -P $h"
		first=0
	else
		# Split the most recently created pane so creation order == index order.
		tmux split-window -t "$WIN" "$SOCKTOP_BIN -P $h"
	fi
	# Label the pane with the host it is showing.
	tmux select-pane -t "$WIN.$(tmux display-message -t "$WIN" -p '#{pane_index}')" -T "$h"
done

tmux select-layout -t "$WIN" tiled
tmux select-pane -t "$WIN.0"

tmux set-option -t "$SOCKTOP_SESSION" pane-border-status top
tmux set-option -t "$SOCKTOP_SESSION" pane-border-format ' #{pane_title} '
tmux set-option -t "$SOCKTOP_SESSION" status off

# Keep dead panes so pane indices stay stable if a socktop exits.
tmux set-option -t "$SOCKTOP_SESSION" remain-on-exit on

# Mouse mode MUST stay off. With it on, every touch swipe is ALSO delivered to
# tmux as a click-drag: dragging across a pane border resizes it and taps
# reselect panes, which fights the gesture daemon. See README, "Why no tapping".
tmux set-option -t "$SOCKTOP_SESSION" mouse off

exec tmux attach -t "$SOCKTOP_SESSION"
