#!/usr/bin/env bats

load 'helpers'

setup() {
  setup_party_sandbox
  require_party_group
}
teardown() { teardown_party_sandbox; }

party_rec() { printf '%s/party-%s:%s.d/roster\n' "$PARTY_SOCKET_DIR" "$USER" "$1"; }

@test "party host installs client-attached and client-detached hooks" {
  "$PARTY_BIN" host hooks
  rec=$(party_rec hooks)
  sock=$(awk -F= '$1=="SOCKET"{print $2}' "$rec")
  out=$(tmux -S "$sock" show-hooks -g)
  [[ "$out" == *"client-attached"* ]]
  [[ "$out" == *"client-detached"* ]]
}

@test "status-right widget is configured with an absolute self path" {
  "$PARTY_BIN" host srtest
  rec=$(party_rec srtest)
  sock=$(awk -F= '$1=="SOCKET"{print $2}' "$rec")
  sr=$(tmux -S "$sock" show-options -gv status-right)
  [[ "$sr" == *"who --short"* ]]
  # The #() body is executed with the tmux server's PATH, which need
  # not contain an installed `party` — the widget must pin the absolute
  # path of the script that hosted the party.
  [[ "$sr" == "party: #('/"* ]]
}

@test "client-attached hook invokes a notify helper that broadcasts display-message" {
  "$PARTY_BIN" host bcast
  rec=$(party_rec bcast)
  sock=$(awk -F= '$1=="SOCKET"{print $2}' "$rec")
  # The hook body is a run-shell that invokes the notify helper script.
  # Verify the hook references the helper, and the helper contains display-message.
  hook=$(tmux -S "$sock" show-hooks -g | grep client-attached)
  [[ "$hook" == *"run-shell"* ]]
  # Extract the notify script path from the hook line and verify its content.
  notify_script="${sock%/*}/.party-notify"
  [ -f "$notify_script" ]
  grep -q "display-message" "$notify_script"
}

@test ".party-notify is chgrp'd to TMUX_PARTY_GROUP (no :other outlier)" {
  "$PARTY_BIN" host notifyperms
  rec=$(party_rec notifyperms)
  sock=$(awk -F= '$1=="SOCKET"{print $2}' "$rec")
  notify_script="${sock%/*}/.party-notify"
  [ -f "$notify_script" ]
  g=$(stat -c '%G' "$notify_script" 2>/dev/null || stat -f '%Sg' "$notify_script")
  [ "$g" = "$TMUX_PARTY_GROUP" ] \
    || { echo "notify_script group=$g, expected $TMUX_PARTY_GROUP"; false; }
}

@test ".party-notify pins the PARTY_TMUX binary used at host time" {
  "$PARTY_BIN" host pintmux
  rec=$(party_rec pintmux)
  sock=$(awk -F= '$1=="SOCKET"{print $2}' "$rec")
  notify_script="${sock%/*}/.party-notify"
  # The helper must not reach for a bare `tmux` from PATH: it pins the
  # binary the party was hosted with (PARTY_TMUX, default "tmux").
  grep -q "^tmux=\"${PARTY_TMUX:-tmux}\"$" "$notify_script"
  ! grep -qE '^[[:space:]]*tmux -S' "$notify_script"
}
