#!/usr/bin/env bash
set -euo pipefail

# A holder may create only the configured named socket. Existing servers are
# accepted only when their private install-derived ownership identity, exact
# holder session, and complete approved global environment all match.

MOSAIC_HOME=${MOSAIC_HOME:-$HOME/.config/mosaic}
MOSAIC_TMUX_SOCKET=${MOSAIC_TMUX_SOCKET:-mosaic-fleet}
MOSAIC_TMUX_HOLDER=${MOSAIC_TMUX_HOLDER:-_holder}
OWNER_FILE="$MOSAIC_HOME/fleet/run/holder-owner"
TMUX_BIN=/usr/bin/tmux

fail() {
  echo "ERROR: refusing unmanaged Mosaic tmux server on socket ${MOSAIC_TMUX_SOCKET}: $1" >&2
  exit 64
}

[ -x "$TMUX_BIN" ] || fail "tmux binary is unavailable"
[ -f "$OWNER_FILE" ] && [ ! -L "$OWNER_FILE" ] || fail "private ownership identity is missing"
owner_mode=$(stat -c '%a' -- "$OWNER_FILE") || fail "private ownership identity is unreadable"
(( (8#$owner_mode & 8#077) == 0 )) || fail "private ownership identity has unsafe permissions"
MOSAIC_FLEET_OWNER=$(tr -d '\n' < "$OWNER_FILE")
[[ "$MOSAIC_FLEET_OWNER" =~ ^[a-f0-9-]{36}$ ]] || fail "private ownership identity is malformed"

_tmux() {
  "$TMUX_BIN" -L "$MOSAIC_TMUX_SOCKET" "$@"
}

server_running() {
  _tmux list-sessions >/dev/null 2>&1
}

assert_owned_server() {
  _tmux has-session -t "=${MOSAIC_TMUX_HOLDER}:0.0" 2>/dev/null || fail "exact holder session is absent"
  local environment
  environment=$(_tmux show-environment -g 2>/dev/null) || fail "global environment is unreadable"
  local expected
  expected=$(printf '%s\n' \
    "HOME=$HOME" \
    'PATH=/usr/bin:/bin' \
    "PWD=$HOME" \
    "MOSAIC_FLEET_OWNER=$MOSAIC_FLEET_OWNER" \
    "MOSAIC_TMUX_HOLDER=$MOSAIC_TMUX_HOLDER" \
    "MOSAIC_TMUX_SOCKET=$MOSAIC_TMUX_SOCKET" | sort)
  [ "$(printf '%s\n' "$environment" | sort)" = "$expected" ] || \
    fail "global environment does not match the owned-server contract"
}

if server_running; then
  assert_owned_server
else
  cd "$HOME" || fail "trusted home is unavailable"
  # Start the tmux server itself under the approved environment. The holder pane
  # receives the same closed environment rather than arbitrary server globals.
  /usr/bin/env -i \
    "HOME=$HOME" \
    PATH=/usr/bin:/bin \
    "MOSAIC_FLEET_OWNER=$MOSAIC_FLEET_OWNER" \
    "MOSAIC_TMUX_HOLDER=$MOSAIC_TMUX_HOLDER" \
    "MOSAIC_TMUX_SOCKET=$MOSAIC_TMUX_SOCKET" \
    "$TMUX_BIN" -L "$MOSAIC_TMUX_SOCKET" new-session -d -s "$MOSAIC_TMUX_HOLDER" \
    /usr/bin/env -i "HOME=$HOME" PATH=/usr/bin:/bin /bin/sh -c 'while true; do sleep 3600; done'
fi
