#!/bin/sh
#
#    screen wrapper script
#    Copyright (C) 2008 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/>.

# Create the screen-profiles directory, if it doesn't already exist
[ -d "$HOME/.screen-profiles" ] || mkdir -p "$HOME/.screen-profiles"

# If $HOME/.screenrc exists but $HOME/.screen-profiles/profile does not,
# this shows that the user has an existing custom screen configuration,
# and thus we will not bother them with a select-screen-profile prompt.
if [ -r "$HOME/.screenrc" -a ! -e "$HOME/.screen-profiles/profile" -a ! -h "$HOME/.screen-profiles/profile" ]; then
	exec /usr/bin/screen.real -c "$HOME/.screenrc" "$@"
	exit $?
fi

# Ensure that the user has selected a screen profile
[ -h "$HOME/.screen-profiles/profile" ] || /usr/bin/select-screen-profile
if [ ! -r "$HOME/.screen-profiles/profile" ]; then
	echo
	echo "Your selected profile is not accessible."
	echo
	echo "Either select a different profile:"
	echo " $ select-screen-profile"
	echo
	echo "Or install the extras package:"
	echo " $ sudo apt-get install screen-profiles-extras"
	echo
	exit 1
fi

# Ensure that their keybindings are seeded
[ -s "$HOME/.screen-profiles/keybindings" ] || echo "source /usr/share/screen-profiles/keybindings/common" > "$HOME/.screen-profiles/keybindings"

# Ensure that their default windows are seeded
[ -r "$HOME/.screen-profiles/windows" ] || cp "/usr/share/screen-profiles/windows/common" "$HOME/.screen-profiles/windows"

# Ensure that the user's .screenrc at least exists
[ -r "$HOME/.screenrc" ] || touch "$HOME/.screenrc"

# Now let's execute screen!
exec /usr/bin/screen.real -c "$HOME/.screen-profiles/profile" "$@"
