#!/bin/sh -e
#
#    byobu-launcher - conditionally launch byobu
#    Copyright (C) 2010 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/>.

[ -z "$BYOBU_PREFIX" ] && export BYOBU_PREFIX="/usr"
export BYOBU_PREFIX

if [ ! -e "$HOME/.byobu/disable-autolaunch" ]; then
	case "$TERM" in
		*screen*)
			# Handle nesting
			printf "$(gettext 'Do you want to launch byobu in a nested session?') [y/N]: "
			answer=$(head -n1)
			case "$answer" in
				y|Y)
					# Prevent nasty launch recursion, if ssh'ing to localhost
					if [ -n "$SSH_CONNECTION" ]; then
						# This is an SSH session
						from=$(echo "$SSH_CONNECTION" | awk '{print $1}')
						to=$(echo "$SSH_CONNECTION" | awk '{print $3}')
						if [ "$from" = "$to" ]; then
							# We have ssh'd from this machine, to this machine
							case "$(screen -ls)" in
								*\(Attached\)*)
									# And there is already an attached screen session, exit to prevent recursion
									false
								;;
								*)
									exec $BYOBU_PREFIX/bin/byobu "$@"
								;;
							esac
						else
							exec $BYOBU_PREFIX/bin/byobu "$@"
						fi
					else
						exec $BYOBU_PREFIX/bin/byobu "$@"
					fi
				;;
				*)
					false
				;;
			esac
		;;
		dumb)
			# Dumb terminal, don't launch
			exit 0
		;;
		*)
			exec $BYOBU_PREFIX/bin/byobu "$@"
		;;
	esac
fi
false
