#!/bin/sh -e
#
#    byobu - screen wrapper script
#    Copyright (C) 2008-2009 Canonical Ltd.
#
#    Authors: Dustin Kirkland <kirkland@canonical.com>
#
#    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/>.

PKG="byobu"
VERSION=2.68

# Add a version argument for debugging purposes
if [ "$#" = "1" ] && [ "$1" = "-v" ]; then
	echo "$PKG version $VERSION"
	screen -v
	exit 0
fi

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

# Sanitize the environment
byobu-janitor --force

# Set window title until https://bugs.launchpad.net/bugs/338722 is fixed in screen
printf "\033]0;${USER}@$(hostname) - ${PKG}\007"

# Launch motd+shell, unless the user has default windows set to launch
grep -qs "^[^#]" "$HOME/.$PKG/windows" && DEFAULT_WINDOW= || DEFAULT_WINDOW="motd+shell"

# Check if our terminfo supports 256 colors
[ -x /usr/bin/tput ] && [ $(/usr/bin/tput colors) -eq 256 ] && SCREEN_TERM="-T screen-256color"

# Create or update ssh-agent socket
if [ -S "$SSH_AUTH_SOCK" ] && [ ! -h "$SSH_AUTH_SOCK" ] && [ -w "$RUN" ]; then
	rm -f "$RUN/$PKG.ssh-agent"
	ln -sf "$SSH_AUTH_SOCK" "$RUN/$PKG.ssh-agent"
fi

# Now let's execute screen!
if [ "$#" = "0" ]; then
	out=$(screen -wipe 2>/dev/null) || true
	if echo "$out" | grep -qsi "^No Sockets found in "; then
		# Start new session
		exec screen $SCREEN_TERM -c "/usr/share/$PKG/profiles/byoburc" -t shell $DEFAULT_WINDOW
	else
		# Select and attach to an existing session
		exec byobu-select-session
	fi
else
	exec screen $SCREEN_TERM -c "$HOME/.$PKG/profile" "$@"
fi
