#!/usr/bin/env bash
# Launch the sendblue channel inside a dedicated tmux session.
# Called by the LaunchAgent for persistence across reboots.
# The tmux session survives terminal disconnects; launchd restarts it on crash.

set -euo pipefail

SESSION="sendblue"
TMUX_BIN="/opt/homebrew/bin/tmux"

# Derive the channel directory from this script's location so the launcher is
# relocatable. Override with SENDBLUE_CHANNEL_DIR if needed.
SENDBLUE_CHANNEL_DIR="${SENDBLUE_CHANNEL_DIR:-$(cd "$(dirname "$0")" && pwd)}"

# Ensure tmux server is running
if ! "$TMUX_BIN" has-session 2>/dev/null; then
  # No tmux server at all — start one with a throwaway session, then kill it
  "$TMUX_BIN" new-session -d -s _boot 2>/dev/null || true
fi

# If the sendblue session already exists and has a living pane, do nothing
if "$TMUX_BIN" has-session -t "$SESSION" 2>/dev/null; then
  echo "[$(date)] run-channel-tmux.sh: session '$SESSION' already exists. Exiting."
  # Keep the LaunchAgent alive by waiting (KeepAlive would restart us otherwise)
  while "$TMUX_BIN" has-session -t "$SESSION" 2>/dev/null; do
    sleep 30
  done
  exit 0
fi

# Create the session running the channel script (detached)
"$TMUX_BIN" new-session -d -s "$SESSION" -x 120 -y 40 \
  "${SENDBLUE_CHANNEL_DIR}/run-channel.sh"

echo "[$(date)] run-channel-tmux.sh: created tmux session '$SESSION'."

# Stay alive while the session exists (launchd KeepAlive monitors this process)
while "$TMUX_BIN" has-session -t "$SESSION" 2>/dev/null; do
  sleep 30
done

echo "[$(date)] run-channel-tmux.sh: session '$SESSION' died. Exiting for launchd restart."
exit 1
