#!/bin/sh
set -eu

sessions="$(tmux list-sessions -F '#S' 2>/dev/null || true)"
[ -n "${sessions}" ] || exit 0

walker_pick_session() {
  if command -v walker >/dev/null 2>&1; then
    walker -d -p 'tmux sessions:'
  fi
}

rofi_pick_session() {
    if command -v rofi >/dev/null 2>&1; then
        rofi -dmenu -p 'tmux sessions:'
    fi
}

chosen="$(printf '%s\n' "$sessions" | rofi_pick_session)"

[ -n "$chosen" ] || exit 0

if [ "${TMUX-}" ]; then
  exec tmux switch-client -t "${chosen}"
fi

client_tty="$(
  tmux list-clients -F '#{client_tty} #{client_termname}' 2>/dev/null \
  | awk '$2 ~ /xterm/ { print $1; exit }' || true
)"

if [ -n "${client_tty}" ]; then
  # switch that client to the chosen session
  address=$(hyprctl clients -j | jq -r "to_entries | .[] | select(.value.class == \"foot\") | \"\(.value.address)\"")
  workspace=$(hyprctl clients -j | jq -r ".[] | select(.address == \"$address\") | \"(.workspace.id)\"")
  hyprctl dispatch "hl.dsp.focus({workspace = $workspace , on_current_monitor = true})"
  hyprctl dispatch "hl.dsp.focus({ window = \"address:$address\" })"
  tmux switch-client -c "${client_tty}" -t "${chosen}"
  exit 0
fi


