#!/usr/bin/env bash
#===============================================================================
#
#             FILE: tmux.sh
#            USAGE: bash tmux.sh
#
#      DESCRIPTION: installs tmux and deploys my tmux configuration
#                   (~/.config/tmux/{tmux.conf,dracula.conf}). Focused on macOS
#                   (via homebrew) with support for Debian-like Linux (via apt).
#                   No TPM/plugins: the Dracula theme is a plain conf file.
#
#     REQUIREMENTS: curl, tar, bash; macOS+homebrew  OR  Debian-like Linux+apt
#
#       OS SUPPORT: macOS (focus) and Linux (Debian-like)
#
#           AUTHOR: Guto Carvalho, guto@bolha.io
#             SITE: https://gutocarvalho.net
#         MASTODON: @gutocarvalho@bolha.us
#         PIXELFED: @gutocarvalho@bolha.photos
#      WRITEFREELY: @gutocarvalho@bolha.blog
#       MATTERMOST: @gutocarvalho:mattermost.bolha.chat
#
#     ORGANIZATION: gutocarvalho.net, gcn.sh, bolha.io
#
#          CREATED: 2026-08-13
#          UPDATED: 2026-08-13
#             REPO: https://gitlab.gutocarvalho.net/open/install
#
#     CONTRIBUTORS: name, email, mastodon
#
#     The code is simple on purpose: we want it to be friendly for people
#     that are starting with shell language and programming logic.
#
#     Run it as your normal user (NOT root). On Linux it uses sudo for apt.
#
#===============================================================================

set -o nounset                              # treat unset variables as an error

## 1. CONSTANTS/VARIABLES ######################################################

# where to fetch the tmux config from (the 'tmux/' dir of this repo).
# Set TMUX_SRC to a local directory (with tmux.conf and dracula.conf) to deploy
# from disk instead of downloading the archive.
TMUX_ARCHIVE="${TMUX_ARCHIVE:-https://gitlab.gutocarvalho.net/open/install/-/archive/main/install-main.tar.gz}"
TMUX_SRC="${TMUX_SRC:-}"

## 2. HELPERS #################################################################

### abort: print an error message and stop the script
function abort() {
  echo -e "\nError: $1" >&2
  echo -e "Tip: run 'bash -x tmux.sh' to see exactly what failed.\n" >&2
  exit 1
}

### warn: print a non-fatal warning and keep going
function warn() {
  echo -e "Warning: $1" >&2
}

### check_not_root: run as the normal user (we use sudo for apt when needed)
function check_not_root() {
  if [ "$(id -u)" = "0" ]; then
    abort "do NOT run this as root. Run it as your normal user (Linux uses sudo for apt)."
  fi
}

### need_cmd: make sure a required command exists
function need_cmd() {
  if ! command -v "$1" >/dev/null 2>&1; then
    abort "'$1' is required but was not found. Please install it first."
  fi
}

## 3. INSTALL FUNCTIONS #######################################################

### 3.1 install tmux (and clipboard tool / font) for the current OS
function install_tmux() {
  echo -e "\n>>> Installing tmux...\n"
  case "$(uname -s)" in
    Darwin)
      need_cmd brew
      brew install tmux || abort "could not install tmux with brew."
      # Nerd Font for the status bar glyphs (best-effort; set it in your terminal)
      brew install --cask font-0xproto-nerd-font \
        || warn "could not install font-0xproto-nerd-font (status glyphs may show as boxes)."
      ;;
    Linux)
      command -v apt-get >/dev/null 2>&1 \
        || abort "this Linux is not Debian-like (no apt-get). Install tmux with your package manager, then rerun to deploy the config."
      # clipboard tool: wl-clipboard on Wayland, xclip on X11
      local clip_pkg="xclip"
      [ -n "${WAYLAND_DISPLAY:-}" ] && clip_pkg="wl-clipboard"
      sudo apt-get update -y || warn "apt-get update failed, trying to install anyway."
      sudo apt-get install -y tmux "$clip_pkg" || abort "could not install tmux/$clip_pkg with apt."
      ;;
    *)
      abort "unsupported OS: $(uname -s)."
      ;;
  esac
  echo "tmux installed: $(tmux -V)"
}

### 3.2 fetch the tmux config into a temp dir, echo its path
function fetch_config() {
  if [ -n "$TMUX_SRC" ]; then
    [ -f "$TMUX_SRC/tmux.conf" ] && [ -f "$TMUX_SRC/dracula.conf" ] \
      || abort "TMUX_SRC '$TMUX_SRC' must contain tmux.conf and dracula.conf."
    echo "$TMUX_SRC"
    return
  fi
  local tmp src
  tmp=$(mktemp -d)
  curl -fsSL "$TMUX_ARCHIVE" | tar xz -C "$tmp" || abort "could not download/extract the config archive."
  src=$(find "$tmp" -type d -name tmux -maxdepth 2 | head -n1)
  [ -n "$src" ] && [ -f "$src/tmux.conf" ] || abort "could not find the tmux/ config inside the archive."
  echo "$src"
}

### 3.3 deploy the config into ~/.config/tmux (backing up any existing one)
function deploy_config() {
  local src="$1" target="$HOME/.config/tmux"
  if [ -e "$target" ]; then
    local backup
    backup="$target.bak-$(date +%s)"
    mv "$target" "$backup"
    warn "existing ~/.config/tmux moved to $backup"
  fi
  mkdir -p "$target"
  cp "$src/tmux.conf" "$src/dracula.conf" "$target"/

  # the config copies to the macOS clipboard with pbcopy; on Linux swap it
  if [ "$(uname -s)" = "Linux" ]; then
    local clip="xclip -selection clipboard -in"
    [ -n "${WAYLAND_DISPLAY:-}" ] && clip="wl-copy"
    sed -i "s#pbcopy#$clip#g" "$target/tmux.conf"
    echo "adjusted clipboard command to: $clip"
  fi
  echo "deployed ~/.config/tmux"
}

### 3.4 reload the config if a tmux server is already running
function reload_tmux() {
  if tmux info >/dev/null 2>&1; then
    tmux source-file "$HOME/.config/tmux/tmux.conf" 2>/dev/null \
      && echo "reloaded the running tmux server."
  fi
}

## 4. EXECUTING ###############################################################

check_not_root
need_cmd curl
need_cmd tar

install_tmux

CONFIG_SRC=$(fetch_config)
deploy_config "$CONFIG_SRC"
reload_tmux

## 5. NOTIFICATIONS ###########################################################

echo -e "\n----------------------------------------------------------------------------------"
echo -e "\nAll done! tmux is installed and configured."
echo "Config: ~/.config/tmux/tmux.conf  (+ dracula.conf theme)"
echo -e "\nStart it with 'tmux'. Reload the config anytime with:  prefix + r"
echo "Status bar uses Nerd Font glyphs — set a Nerd Font in your terminal if they"
echo "show as boxes (macOS installs 0xProto Nerd Font for you here)."
echo -e "\nEnjoy it!"
echo -e "\nWant to know more about our collective? Visit https://bolha.io and consider joining us! ;)"
echo -e "Come and visit our mastodon instance:    https://bolha.us"
echo -e "Come and visit our mattermost instance:  https://mattermost.bolha.chat"
echo -e "Say hello on the fediverse:              @gutocarvalho@bolha.us"
echo -e "\n----------------------------------------------------------------------------------\n"
