#!/usr/bin/env bash
# Toggle fullscreen on a tmux pane.
# Usage: toggle-fullscreen <pane_id> [exit]
#   default: toggle
#   exit:    only leave fullscreen (no-op if not fullscreened)
set -u

PANE="${1:-}"
MODE="${2:-toggle}"
[ -z "$PANE" ] && exit 0

IFS='|' read -r ORIG WIN NPANES <<<"$(
  tmux display-message -p -t "$PANE" '#{@orig-window}|#{window_id}|#{window_panes}' 2>/dev/null
)"

SELF_DIR="$(cd "$(dirname "$0")" && pwd)"

if [ -n "$ORIG" ] && [ "$ORIG" != "$WIN" ]; then
  # Stash points at a different window: return there.
  if tmux list-windows -a -F '#{window_id}' 2>/dev/null | grep -qx "$ORIG"; then
    tmux join-pane -s "$PANE" -t "$ORIG"
    # Re-tile the origin window so the returned pane fits the layout nicely.
    "$SELF_DIR/smart-layout" "$PANE" 2>/dev/null || true
  fi
  tmux set-option -pu -t "$PANE" @orig-window
elif [ "$MODE" = "toggle" ] && [ "${NPANES:-1}" -gt 1 ]; then
  # Not currently fullscreen (or stash was stale): break out.
  tmux set-option -p -t "$PANE" @orig-window "$WIN"
  tmux break-pane -s "$PANE"
fi
