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

TMUX_CONF="${HOME}/.tmux.conf"
SHELL_RC="${HOME}/.zshrc"

if ! command -v tmux >/dev/null 2>&1; then
  echo "tmux is not installed."
  if command -v brew >/dev/null 2>&1; then
    echo "Install it with: brew install tmux"
  else
    echo "Install tmux with your system package manager, then run this script again."
  fi
  exit 1
fi

if [ -f "$TMUX_CONF" ]; then
  backup="${TMUX_CONF}.backup.$(date +%Y%m%d%H%M%S)"
  cp "$TMUX_CONF" "$backup"
  echo "Backed up existing tmux config to $backup"
fi

cat > "$TMUX_CONF" <<'EOF'
# Parent-dev tmux defaults
set -g prefix C-a
unbind C-b
bind C-a send-prefix

# Mouse support helps when you are tired and context-switching.
set -g mouse on

# Show which project/session you are in.
set -g status-left "#[fg=green][#S] "
EOF

touch "$SHELL_RC"

add_alias() {
  local alias_line="$1"
  if ! grep -Fqx "$alias_line" "$SHELL_RC"; then
    printf '\n%s\n' "$alias_line" >> "$SHELL_RC"
  fi
}

add_alias 'alias twork="tmux attach -t work || tmux new -s work"'
add_alias 'alias tblog="tmux attach -t blog || tmux new -s blog"'
add_alias 'alias tfam="tmux attach -t family-projects || tmux new -s family-projects"'

echo "tmux config installed at $TMUX_CONF"
echo "Aliases added to $SHELL_RC if they were not already present."
echo "Open a new terminal, then try: tblog"
