#!/bin/sh -e
#
#    byobu - wrapper script
#    Copyright (C) 2008-2009 Canonical Ltd.
#    Copyright (C) 2008-2024 Dustin Kirkland
#
#    Authors: Dustin Kirkland <kirkland@byobu.org>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

VERSION=@VERSION@
PKG="byobu"

# All sorts of things go wrong if you don't own your $HOME dir.
# This happens under sudo, if you don't use the -H option; Byobu will
# create a bunch of files in your $HOME which will be owned by root.
if [ ! -O "$HOME" ] && [ ! -O "$HOME/.profile" ]; then
	echo "Cannot run $PKG because [$USER] does not own [$HOME] or [$HOME/.profile]" 1>&2
	if [ -n "$SUDO_USER" ]; then
		echo "To run $PKG under sudo, you MUST use 'sudo -H'" 1>&2
	fi
	exit 1
fi

# If we're in a busybox/ash shell (or shell is undefined),
# and a full bash shell is available, then please let's use bash in byobu.
# Other shells are supported, but your mileage may vary...
if [ "$SHELL" = "/bin/ash" ] || [ "$SHELL" = "ash" ] || [ -z "$SHELL" ]; then
	[ -x "/bin/bash" ] && export SHELL="/bin/bash"
fi

# Source local byobu config
if [ -r "$HOME/.byoburc" ]; then
	# Ensure that this configuration is usable
	. "$HOME/.byoburc" || mv -f "$HOME/.byoburc" "$HOME/.byoburc".orig
fi
if [ -z "${BYOBU_PREFIX}" ]; then
	# Find and export the installation location prefix
	greadlink -f . >/dev/null 2>&1 && export BYOBU_READLINK="greadlink" || export BYOBU_READLINK="readlink"
	prefix="$(dirname $(dirname $($BYOBU_READLINK -f $0)))"
	if [ "$prefix" != "@prefix@" ]; then
		echo "export BYOBU_PREFIX='$prefix'" >> "$HOME/.byoburc"
		. "$HOME/.byoburc"
	fi
fi
export BYOBU_CHARMAP=$(locale charmap)
[ -r "$HOME/.byoburc" ] && . "$HOME/.byoburc"
[ -z "${BYOBU_PREFIX}" ] && export BYOBU_PREFIX="@prefix@" || export BYOBU_PREFIX
. "${BYOBU_PREFIX}/lib/${PKG}/include/common"

# Override backend if we can determine intentions from argv[0]
[ -r "$BYOBU_CONFIG_DIR/backend" ] && . "$BYOBU_CONFIG_DIR/backend"
case "$0" in
	*byobu-screen) BYOBU_BACKEND="screen" ;;
	*byobu-tmux) BYOBU_BACKEND="tmux" ;;
esac

# At this point, we're sure BYOBU_BACKEND is properly defined
export BYOBU_BACKEND

# Store the parent tty
if eval $BYOBU_TEST tty >/dev/null 2>&1; then
	export BYOBU_TTY=$(tty)
else
	export BYOBU_TTY=$(readlink /proc/$$/fd/0)
fi

# Get the default window name
[ -n "$BYOBU_WINDOW_NAME" ] || BYOBU_WINDOW_NAME=-

# Add a version argument for debugging purposes, enter manpage for help
if [ "$#" = "1" ]; then
	case "$1" in
		-v|--version)
			echo "$PKG version $VERSION"
			if eval $BYOBU_TEST bash >/dev/null 2>&1; then
				# Check ulimits
				u=$(bash -c "ulimit -n")
				[ "$u" = "unlimited" ] || [ $u -ge 15 ] || echo "WARNING: ulimit -n is too low" 1>&2
				u=$(bash -c "ulimit -u")
				[ "$u" = "unlimited" ] || [ $u -ge 1600 ] || echo "WARNING: ulimit -u is too low" 1>&2
			fi
			exec $BYOBU_BACKEND $BYOBU_ARG_VERSION
			exit 0
		;;
		-h|--help)
			exec man $PKG
		;;
	esac
fi

# Check if we're being autolaunched, and this user explicitly does not want it.
if [ "$0" = "/etc/profile.d/Z97-$PKG.sh" ] && [ -r "$BYOBU_CONFIG_DIR/disable-autolaunch" ]; then
	exit 0
fi

# Sanitize the environment
byobu-janitor --force

# Set the window title if this is a TTY
if [ -t 1 ]; then
	[ -r "$BYOBU_CONFIG_DIR/statusrc" ] && . "$BYOBU_CONFIG_DIR/statusrc"
	. $BYOBU_PREFIX/lib/$PKG/ip_address
	if [ -n "$BYOBU_ALT_TITLE" ]; then
		_byobu_title="$BYOBU_ALT_TITLE"
	else
		_byobu_title="${USER}@$(hostname 2>/dev/null || cat /proc/sys/kernel/hostname 2>/dev/null) ($(__ip_address t)) - ${PKG}"
	fi
	[ -n "$BYOBU_NO_TITLE" ] || printf '\033]0;%s\007' "$_byobu_title"
fi

# Drop a symlink to the ssh socket in $HOME, since we can ensure that exists.
# Include hostname in the name so NFS-shared homes don't stomp each other.
if [ -S "$SSH_AUTH_SOCK" ] && [ ! -h "$SSH_AUTH_SOCK" ]; then
	_byobu_agent="$BYOBU_CONFIG_DIR/.ssh-agent-$(hostname -s 2>/dev/null || hostname 2>/dev/null || cat /proc/sys/kernel/hostname 2>/dev/null)"
	ln -sf "$SSH_AUTH_SOCK" "$_byobu_agent"
	export SSH_AUTH_SOCK="$_byobu_agent"
	unset _byobu_agent
fi

# Fallback terminfo
[ -z "$BYOBU_DEFAULT_TERM" ] && BYOBU_DEFAULT_TERM="screen"

# Color terminfo to use, if possible
# Prefer tmux-256color over screen-256color for the tmux backend: screen-256color
# defines smso=\E[3m (standout = italic escape code) with no sitm, causing tmux
# to map italic requests to standout mode which renders as reverse video on the
# outer terminal. tmux-256color correctly separates smso=\E[7m and sitm=\E[3m.
if [ -z "$BYOBU_COLOR_TERM" ]; then
	if [ "$BYOBU_BACKEND" = "tmux" ] && infocmp tmux-256color >/dev/null 2>&1; then
		BYOBU_COLOR_TERM="tmux-256color"
	else
		BYOBU_COLOR_TERM="screen-256color"
	fi
fi

# Check if our terminfo supports 256 colors
CAN_SHOW_COLORS=
if eval $BYOBU_TEST tput >/dev/null 2>&1; then
	if [ "$(tput colors 2>/dev/null || echo 0)" = "256" ]; then
		CAN_SHOW_COLORS=1
	fi
fi

# Check if the color terminfo is available
HAS_COLOR_TERM=
if eval $BYOBU_TEST infocmp >/dev/null 2>&1; then
	if infocmp "$BYOBU_COLOR_TERM" >/dev/null 2>&1; then
		HAS_COLOR_TERM=1
	fi
fi

case $BYOBU_BACKEND in
	tmux)
		# Use 256 colors if possible
		if [ -n "$CAN_SHOW_COLORS" ] || [ "$COLORTERM" = "gnome-terminal" ] || [ "$TERM" = "xterm" ] || [ "$TERM" = "xterm-256color" ] || [ "$TERM" = "screen" ]; then
			[ -z "$SCREEN_TERM" ] && SCREEN_TERM="-2"
		fi
		if [ -z "$BYOBU_TERM" ]; then
			if [ -n "$SCREEN_TERM" -a -n "$HAS_COLOR_TERM" ]; then
				BYOBU_TERM="$BYOBU_COLOR_TERM"
			else
				BYOBU_TERM="$BYOBU_DEFAULT_TERM"
			fi
		fi
		BYOBU_PROFILE="-f $BYOBU_PREFIX/share/$PKG/profiles/tmuxrc"
		# Set default window, unless user has overriden
		if egrep -qs "default-command|default-shell" $BYOBU_CONFIG_DIR/.tmux.conf >/dev/null 2>&1; then
			DEFAULT_WINDOW=
		else
			DEFAULT_WINDOW="new-session -n $BYOBU_WINDOW_NAME ${BYOBU_PREFIX}/bin/byobu-shell"
		fi
		sessions=$($BYOBU_BACKEND list-sessions 2>/dev/null) || true
		CUSTOM_WINDOW_SET=0
		if [ -s "$BYOBU_CONFIG_DIR/windows.tmux.$BYOBU_WINDOWS" ]; then
			CUSTOM_WINDOW_SET=1
			BYOBU_WINDOWS="$BYOBU_CONFIG_DIR/windows.tmux.$BYOBU_WINDOWS"
		elif [ -s "$BYOBU_CONFIG_DIR/windows.tmux" ]; then
			CUSTOM_WINDOW_SET=1
			BYOBU_WINDOWS="$BYOBU_CONFIG_DIR/windows.tmux"
		fi
	;;
	screen)
		# Allow override of default window list, with BYOBU_WINDOWS environment variable
		CUSTOM_WINDOW_SET=0
		if [ -s "$BYOBU_WINDOWS" ]; then
			CUSTOM_WINDOW_SET=1
		elif [ -s "$BYOBU_CONFIG_DIR/windows.$BYOBU_WINDOWS" ]; then
			CUSTOM_WINDOW_SET=1
			BYOBU_WINDOWS="$BYOBU_CONFIG_DIR/windows.$BYOBU_WINDOWS"
		elif [ "$#" = "0" ]; then
			BYOBU_WINDOWS="$BYOBU_CONFIG_DIR/windows"
		else
			BYOBU_WINDOWS="/dev/null"
		fi
		export BYOBU_WINDOWS
		# Launch shell, unless the user has default windows set to launch
		uncommented_lines < "$BYOBU_WINDOWS" && DEFAULT_WINDOW= || DEFAULT_WINDOW="${BYOBU_PREFIX}/bin/byobu-shell"
		# Use 256 colors if possible
		if [ -z "$BYOBU_TERM" ]; then
			if [ -n "$CAN_SHOW_COLORS" -a -n "$HAS_COLOR_TERM" ]; then
				BYOBU_TERM="$BYOBU_COLOR_TERM"
			else
				BYOBU_TERM="$BYOBU_DEFAULT_TERM"
			fi
		fi
		SCREEN_TERM="-T $BYOBU_TERM"
		# Some users want to maintain separate configurations
		# if they use both GNU Screen and byobu on the same system
		if [ -r "$BYOBU_CONFIG_DIR/.screenrc" ]; then
			BYOBU_PROFILE="-c $BYOBU_PREFIX/share/$PKG/profiles/byoburc"
		else
			BYOBU_PROFILE="-c $BYOBU_PREFIX/share/$PKG/profiles/screenrc"
		fi
		BYOBU_SESSION_NAME="-S $PKG"
		# Zero out $BYOBU_SESSION_NAME if user has specified a session name
		for i in "$@"; do
			case $i in
				-*r*|-*d*|-*D*|-*S*|-ls|-list)
					BYOBU_SESSION_NAME=
				;;
			esac
		done
		sessions=$($BYOBU_BACKEND -wipe 2>/dev/null) || true
	;;
esac

export BYOBU_TERM

# Save session info
[ -n "$DBUS_SESSION_BUS_ADDRESS" ] && printf "DBUS_SESSION_BUS_ADDRESS=$DBUS_SESSION_BUS_ADDRESS\n" > "$BYOBU_RUN_DIR/sockets"
[ -n "$SESSION_MANAGER" ] && printf "SESSION_MANAGER=$SESSION_MANAGER\n" >> "$BYOBU_RUN_DIR/sockets"

# Preflight: if no tmux server is running yet, validate the config so any
# syntax error is shown to the user rather than swallowed by exec.  LP: #1960236
if [ "$BYOBU_BACKEND" = "tmux" ] && ! tmux list-sessions >/dev/null 2>&1; then
	_byobu_tmux_err=$(tmux start-server 2>&1 >/dev/null) || true
	if [ -n "$_byobu_tmux_err" ]; then
		printf "byobu: tmux configuration error:\n%s\n" "$_byobu_tmux_err" >&2
		exit 1
	fi
	unset _byobu_tmux_err
fi

# Now let's execute the backend!
if [ "$#" = "0" ]; then
	if [ "$CUSTOM_WINDOW_SET" = "1" ]; then
		# Start new custom window set session
		case $BYOBU_BACKEND in
			tmux)
				exec tmux -u $SCREEN_TERM $BYOBU_PROFILE $(cat "$BYOBU_WINDOWS")
			;;
			screen)
				exec screen $SCREEN_TERM $BYOBU_SESSION_NAME $BYOBU_PROFILE
			;;
		esac
	else
		case "$sessions" in
			*\(*\)*)
				# Select and attach to an existing session
				exec byobu-select-session
			;;
			*)
				# Start new default session
				case $BYOBU_BACKEND in
					tmux)
						exec tmux -u $SCREEN_TERM $BYOBU_PROFILE $DEFAULT_WINDOW
					;;
					screen)
						exec screen $SCREEN_TERM $BYOBU_SESSION_NAME $BYOBU_PROFILE $DEFAULT_WINDOW
					;;
				esac
			;;
		esac
	fi
else
	# Launch with command line args
	case $BYOBU_BACKEND in
		tmux)
			exec tmux -u $SCREEN_TERM $BYOBU_PROFILE "$@"
		;;
		screen)
			exec screen $SCREEN_TERM $BYOBU_SESSION_NAME $BYOBU_PROFILE "$@"
		;;
	esac
fi

# vi: syntax=sh ts=4 noexpandtab
