#!/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"
DATA="$HOME/.$PKG"
XDG="$HOME/.local/share/$PKG"
[ -z "$BYOBU_PREFIX" ] && export BYOBU_PREFIX="/usr"
[ -r "/etc/$PKG/socketdir" ] && . "/etc/$PKG/socketdir" || SOCKETDIR="/var/run/screen"
RUN="$SOCKETDIR/S-$USER"
FLAG="$RUN/$PKG.reload-required"

# Let's get prepped to switch over to XDG one day; maintain symlink for now
mkdir -p "$XDG"
if [ -d "$DATA" ] && [ ! -h "$DATA" ]; then
	mv -f "$DATA"/* "$DATA"/.* "$XDG" 2>/dev/null || true
	rmdir "$DATA"
fi
ln -sf "$XDG" "$DATA"

# 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
DEFAULT_PROFILE="light"
PROFILE="$DATA/profile"
# Use gsed on non-Linux OS's
which gsed 2>/dev/null && SED="gsed" || SED="sed"
which greadlink 2>/dev/null && READLINK="greadlink" || READLINK="readlink"

# Create byobu-exchange buffer file, with secure permissions, if it doesn't exist
if [ -w "$RUN" ] && [ ! -e "$RUN/$PKG-exchange" ]; then
	install -m 600 /dev/null "$RUN/$PKG-exchange"
fi

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

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

# Affects: Symlinks pointing to color profiles
if [ -h "$PROFILE" ]; then
	case "$($READLINK -f $PROFILE)" in
		$BYOBU_PREFIX/share/byobu/profiles/*)
			# Set default colors
			BG=W
			FG=k
			color=$(ls -l "$PROFILE")
			color=${color##*/}
			case "$color" in
				common)       BG=;  FG=;;
				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
			if [ -n "$BG" ] && [ -n "$FG" ]; then
				rm -f "$PROFILE" 2>/dev/null
				byobu-select-profile -b $BG -f $FG >/dev/null 2>&1
			fi
		;;
	esac
fi

[ -s "$DATA/keybindings" ] || echo "source $BYOBU_PREFIX/share/$PKG/keybindings/common" > "$DATA/keybindings"
if [ ! -r "$DATA/status" ]; then
	if [ -r /etc/$PKG/statusrc ]; then
		skel=/etc/$PKG/statusrc
	elif [ -r "$BYOBU_PREFIX/share/$PKG/profiles/statusrc" ]; then
		skel="$BYOBU_PREFIX/share/$PKG/profiles/statusrc"
	else
		skel=/dev/null
	fi
	grep -A 999999 BEGIN_CUT_HERE $skel | grep -B 999999 END_CUT_HERE | grep -v CUT > "$DATA/status"
fi
[ -r "$DATA/windows" ] || touch "$DATA/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 -e "s/\([^=]+\)-\([^=]+\)=/\1_\2=/g" "$DATA/status"
$SED -i -e "s/^disk-.*=/disk=/" "$DATA/status"
$SED -i -e "s/^network-.*=/network=/" "$DATA/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 "$DATA/$i" ]; then
		val=`cat $DATA/$i`
		uc=`echo "$i" | tr "[:lower:]" "[:upper:]"`
		case $i in
			disk|network)
				key="MONITORED_"$uc ;;
			distro|logo)
				key="$uc" ;;
		esac
		echo "$key=\"$val\"" >> "$DATA/statusrc"
		rm "$DATA/$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 -e "/ $PKG-launch/d" "$HOME"/.profile || true
fi

# Affects: Upgrades from <= byobu-2.70 that autolaunch
# Update the byobu-launch line, if necessary
if grep -qs " $PKG-launch$" "$HOME"/.profile; then
	$PKG-launcher-install
fi

# Affects: Upgrades from <= byobu-2.78 which might have "motd+shell"
# in their window list; update this to just "shell"
if grep -qs "motd+shell" "$DATA/windows"; then
	$SED -i -e "s/motd+shell/shell/g" "$DATA/windows" || true
fi

# Affects: Upgrades from <= byobu-3.6, change location of $SSH_AUTH_SOCK
if [ -h "$RUN/$PKG.ssh-agent" ]; then
	rm -f "$DATA/.ssh-agent"
	mv -f "$RUN/$PKG.ssh-agent" "$DATA/.ssh-agent"
fi

# Clean up flag
rm -f "$FLAG"
