#!/bin/sh -e
#
# ,popup-tmux - create/attach/detach popup window [single] [folder]

current_pane="$(tmux display-message -p -F "#{session_name}")"

if echo "${current_pane}" | grep -q '^popup.*'; then
  tmux detach-client
else
  case "$1" in
    "single")
      tmux popup -d '#{pane_current_path}' -x100% -y0% -w50% -h50% \
        -E "tmux attach -t 'popup-${current_pane}' \
            || tmux new -s 'popup-${current_pane}'" || true
      ;;
    "folder")
      # get current folder path from tmux pane, default to git root if available
      # shellcheck disable=SC2015,SC2312
      folder="$(cd "$(tmux display-message -p "#{pane_current_path}")" \
        && git rev-parse --show-toplevel 2>/dev/null \
        || tmux display-message -p "#{pane_current_path}")"
      fname="$(basename "${folder}")"

      tmux popup -d "${folder}" -x100% -y0% -w70% -h80% \
        -E "tmux attach -t 'popup-${fname}' || tmux new -s 'popup-${fname}'" \
        || true
      ;;
    *)
      tmux popup -x100% -y0% -w50% -h50% \
        -E "tmux attach -t popup-main || tmux new -s popup-main" || true
      ;;
  esac
fi
