#!/bin/sh -e
#
#    byobu-janitor - a collection of byobu tasks that ensure  a clean
#                    environtment and smooth upgrades
#
#    Copyright (C) 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"
[ -r "/etc/$PKG/socketdir" ] && . "/etc/$PKG/socketdir" || SOCKETDIR="/var/run/screen"
RUN="$SOCKETDIR/S-$USER"
FLAG="$RUN/$PKG.reload-required"

# Exit immediately, if we're not forced, and there is no reload flag
if [ "$1" != "--force" ] && [ ! -e "$FLAG" ]; then
	exit 0
fi

# Set the rest of the variables
OLDPKG="screen-profiles"
DEFAULT_PROFILE="light"
PROFILE="$HOME/.$PKG/profile"

# Establish ssh-agent socket, helps when reconnecting to a detached session
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

# Affects: users who launched using sudo, such that their config dir
# is not writable by them
if [ -d "$HOME/.$PKG" ] && [ ! -w "$HOME/.$PKG" ]; then
	echo "ERROR: [$HOME/.$PKG] is not writable by the current user" 1>&2
	exit 1
fi

# Affects: Upgrades from screen-profiles
# If the old config dir exists, but the new one doesn't, provide a migration mechanism.
if [ -d "$HOME/.$OLDPKG" ] && [ ! -e "$HOME/.$PKG" ]; then
	# Rename the config dir
	mv -f "$HOME/.$OLDPKG" "$HOME/.$PKG"
	ln -sf "$HOME/.$PKG" "$HOME/.$OLDPKG"
	# Replace all instances of the old package name with the new
	sed -i "s/$OLDPKG/$PKG/g" "$HOME/.$PKG"/* || true
fi

# Affects: First runs with no configuration
# Seed the configuration
[ -d "$HOME/.$PKG" ] || mkdir -p "$HOME/.$PKG"
[ -r "$HOME/.$PKG/color" ] || printf "BACKGROUND=k\nFOREGROUND=w\nMONOCHROME=0" > "$HOME/.$PKG/color"
[ -r "$PROFILE" ] || ln -sf /usr/share/$PKG/profiles/common "$PROFILE"

# Affects: Symlinks pointing to color profiles
if [ -h "$PROFILE" ] && \
   stat "$PROFILE" | grep -qs "File:.*->.*/usr/share/byobu/profiles/" && \
 ! stat "$PROFILE" | grep -qs "File:.*->.*/usr/share/byobu/profiles/common" ; then
	# Set default colors
	BG=W
	FG=k
	color=$(ls -l "$PROFILE" | sed "s/^.*\///")
	case $color in
		black|dark)   BG=k; FG=W;;
		dark_blue)    BG=b; FG=W;;
		dark_cyan)    BG=c; FG=W;;
		dark_green)   BG=g; FG=W;;
		dark_purple)  BG=m; FG=W;;
		dark_red)     BG=r; FG=W;;
		dark_yellow)  BG=y; FG=W;;
		light)        BG=W; FG=k;;
		light_blue)   BG=B; FG=k;;
		light_cyan)   BG=C; FG=k;;
		light_green)  BG=G; FG=k;;
		light_purple) BG=M; FG=k;;
		light_red)    BG=R; FG=k;;
		light_yellow) BG=Y; FG=k;;
		*)            BG=W; FG=k;;
	esac
	rm -f "$PROFILE" 2>/dev/null
	byobu-select-profile -b $BG -f $FG >/dev/null 2>&1
fi

[ -s "$HOME/.$PKG/keybindings" ] || echo "source /usr/share/$PKG/keybindings/common" > "$HOME/.$PKG/keybindings"
[ -r "$HOME/.$PKG/status" ] || $(grep -A 999999 BEGIN_CUT_HERE /etc/$PKG/statusrc | grep -B 999999 END_CUT_HERE | grep -v CUT > "$HOME/.$PKG/status")
[ -r "$HOME/.$PKG/windows" ] || touch "$HOME/.$PKG/windows"
[ -r "$HOME/.screenrc" ] || touch "$HOME/.screenrc"

# Affects: Upgrades from <= byobu-2.11
# The status scripts used to have hyphens in their name, but now use
# underscores such that we can source the file as a shell snippet;
# fix existing status configuration.
sed -i "s/\(.*\)-\(.*\)=/\1_\2=/g" "$HOME/.$PKG/status"
sed -i "s/^disk.*=/disk=/" "$HOME/.$PKG/status"
sed -i "s/^network.*=/network=/" "$HOME/.$PKG/status"

# Affects: Upgrades from <= byobu-2.16
# screen-launcher was renamed byobu-launcher; if the user has byobu
# set to auto-launch, update their configuration to use the byobu-launcher
if grep -qs "screen-launcher$" "$HOME/.profile"; then
	byobu-launcher-install
fi

# Affects: Upgrades from <= byobu-2.25
# Collapse separate status config files into the sourced config
for i in disk network distro logo; do
	if [ -r "$HOME/.$PKG/$i" ]; then
		val=`cat $HOME/.$PKG/$i`
		uc=`echo "$i" | tr "[:lower:]" "[:upper:]"`
		case $i in
			disk|network)
				key="MONITORED_"$uc ;;
			distro|logo)
				key="$uc" ;;
		esac
		echo "$key=\"$val\"" >> "$HOME/.$PKG/statusrc"
		rm "$HOME/.$PKG/$i"
	fi
done

# Affects: Upgrades from <= byobu-2.57 that autolaunch
# If the global autolaunch is on, then remove duplicate entry in ~/.profile
if [ -h "/etc/profile.d/Z98-$PKG.sh" ]; then
	sed -i "/$PKG-launcher$/d" "$HOME"/.profile || true
fi


# Clean up flag
rm -f "$FLAG"
