#!/bin/sh -e
#
#    byobu-janitor - a collection of byobu tasks that ensure  a clean
#                    environtment and smooth upgrades
#
#    Copyright (C) 2009 Canonical Ltd.
#    Copyright (C) 2024 Dustin Kirkland
#
#    Authors: Dustin Kirkland <kirkland@byobu.org>
#
#    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 "$HOME/.byoburc" ] && . "$HOME/.byoburc"
[ -z "${BYOBU_PREFIX}" ] && export BYOBU_PREFIX="@prefix@" || export BYOBU_PREFIX
. "${BYOBU_PREFIX}/lib/${PKG}/include/common"

# Ensure that all updates get run immediately
rm -rf "$BYOBU_RUN_DIR/.last.$BYOBU_BACKEND"

# Ensure that we re-check metadata service
rm -f "$BYOBU_CONFIG_DIR/.metadata_available" "$BYOBU_RUN_DIR/.metadata_available" 2>/dev/null || true

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

# Set the rest of the variables
DEFAULT_PROFILE="light"
PROFILE="$BYOBU_CONFIG_DIR/profile"

# Create byobu-exchange buffer file, with secure permissions, if it doesn't exist
if ! [ -e "$BYOBU_RUN_DIR/printscreen" ]; then
	if eval $BYOBU_TEST install >/dev/null 2>&1; then
		install -m 600 /dev/null "$BYOBU_RUN_DIR/printscreen"
	else
		cp /dev/null "$BYOBU_RUN_DIR/printscreen"
		chmod 600 "$BYOBU_RUN_DIR/printscreen"
	fi
fi

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

# Affects: Upgrades from <= byobu 4.30
# Clear out old style status configuration
if ! grep -qs "^screen_upper_left=" "$BYOBU_CONFIG_DIR/status"; then
	rm -f "$BYOBU_CONFIG_DIR/status" "$BYOBU_CONFIG_DIR/statusrc"
fi

# NOTE: Older version of Screen have an arbitrary limit of only being able
# to change colors 16 times in this 'hardstatus string'.
# Also committed in Upstream git, but not yet released.
#  * http://savannah.gnu.org/bugs/?22146
# If we could reliably tell if we had a patched screen, we'd do so here...
MC=0

# Affects: First runs with no configuration
# Seed the configuration
# Setup initial local user configuration
[ -r "$BYOBU_CONFIG_DIR/color" ] || printf "BACKGROUND=k\nFOREGROUND=w\nMONOCHROME=$MC" > "$BYOBU_CONFIG_DIR/color"
[ -r "$BYOBU_CONFIG_DIR/color.tmux" ] || sed -e "s/^#.*//" -e "/^\s*$/d" -e "s/^export //" "$BYOBU_PREFIX/lib/$PKG/include/colors"  > "$BYOBU_CONFIG_DIR/color.tmux"
# Affects: tmux 3.6 rejects \#RRGGBB hex escape — strip the backslash (GH: #105)
sed -i 's/="\\#/="#/g' "$BYOBU_CONFIG_DIR/color.tmux" 2>/dev/null || true
[ -r "$BYOBU_CONFIG_DIR/datetime.tmux" ] || printf 'BYOBU_DATE="%%Y-%%m-%%d "\nBYOBU_TIME="%%H:%%M:%%S"\n' > "$BYOBU_CONFIG_DIR/datetime.tmux"
[ -r "$BYOBU_CONFIG_DIR/profile" ] || echo "source \$BYOBU_PREFIX/share/$PKG/profiles/common" > "$BYOBU_CONFIG_DIR/profile"
[ -r "$BYOBU_CONFIG_DIR/profile.tmux" ] || echo "source \$BYOBU_PREFIX/share/$PKG/profiles/tmux" > "$BYOBU_CONFIG_DIR/profile.tmux"
[ -r "$BYOBU_CONFIG_DIR/keybindings" ] || echo "source \$BYOBU_PREFIX/share/$PKG/keybindings/common" > "$BYOBU_CONFIG_DIR/keybindings"
[ -r "$BYOBU_CONFIG_DIR/keybindings.tmux" ] || touch "$BYOBU_CONFIG_DIR/keybindings.tmux"
[ -r "$BYOBU_CONFIG_DIR/windows" ] || touch "$BYOBU_CONFIG_DIR/windows"
[ -r "$BYOBU_CONFIG_DIR/windows.tmux" ] || touch "$BYOBU_CONFIG_DIR/windows.tmux"
[ -r "$BYOBU_CONFIG_DIR/backend" ] || echo "BYOBU_BACKEND=$BYOBU_BACKEND" > "$BYOBU_CONFIG_DIR/backend"
[ -r "$BYOBU_CONFIG_DIR/.screenrc" ] || touch "$BYOBU_CONFIG_DIR/.screenrc"
[ -r "$BYOBU_CONFIG_DIR/.tmux.conf" ] || touch "$BYOBU_CONFIG_DIR/.tmux.conf"
# BYOBU_SHELL_ARGS: if set in statusrc, write a shellinit.tmux that overrides
# tmux's default-command so new windows/panes start with those args (e.g.
# --login to source /etc/profile.d).  LP: #1618516
[ -r "$BYOBU_CONFIG_DIR/statusrc" ] && . "$BYOBU_CONFIG_DIR/statusrc" 2>/dev/null || true
_shellinit="$BYOBU_CONFIG_DIR/shellinit.tmux"
if [ -n "$BYOBU_SHELL_ARGS" ]; then
	printf 'set -g default-command "exec $SHELL %s"\n' "$BYOBU_SHELL_ARGS" > "$_shellinit"
else
	[ -f "$_shellinit" ] || touch "$_shellinit"
fi
unset _shellinit
for f in status statusrc; do
	if [ ! -r "$BYOBU_CONFIG_DIR/$f" ]; then
		# Copy from skeleton, if possible
		cp -f "$BYOBU_PREFIX/share/$PKG/status/$f" "$BYOBU_CONFIG_DIR/$f"
		# If we're running in Wolfi for the first time, cycle to the 2nd status
		[ "$f" = "status" ] && [ "$BYOBU_DISTRO" = "Wolfi" ] && $BYOBU_PREFIX/lib/byobu/include/cycle-status
	fi
done

# 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" "$BYOBU_CONFIG_DIR/windows"; then
	$BYOBU_SED_INLINE -e "s/motd+shell/shell/g" "$($BYOBU_READLINK -f $BYOBU_CONFIG_DIR/windows)" || true
fi

# Affects: Upgrades from <= byobu 4.3, remove ec2_rates
rm -f "$BYOBU_CONFIG_DIR/ec2_rates"

# Affects: Upgrades from <= byobu 4.4, update "shell" -> "byobu-shell"
if grep -qs " shell$" "$BYOBU_CONFIG_DIR/windows"; then
	$BYOBU_SED_INLINE -e "s/ shell$/ $PKG-shell/g" "$($BYOBU_READLINK -f $BYOBU_CONFIG_DIR/windows)" || true
fi

# Affects: Upgrades from <= byobu 4.22
killall -u $USER byobu-statusd >/dev/null 2>&1 || true

# Clean up flag (new and old)
rm -f "$FLAG" "/var/run/screen/S-$USER/$PKG.reload-required"

# Affects: Upgrades from <= byobu 5.50, install byobu prompt if using stock bashrc
if [ -r /etc/skel/.bashrc ] && [ -r "$HOME/.bashrc" ] && [ -w "$HOME/.bashrc" ] && \
		! (grep -qs "#byobu-prompt#$" "$HOME/.bashrc") && ! [ -e "$BYOBU_CONFIG_DIR/prompt" ]; then
	if eval $BYOBU_TEST diff >/dev/null 2>&1; then
		if  diff /etc/skel/.bashrc "$HOME/.bashrc" >/dev/null 2>&1; then
			printf "[ -r $BYOBU_CONFIG_DIR/prompt ] && . $BYOBU_CONFIG_DIR/prompt   #byobu-prompt#\n" >> "$HOME/.bashrc"
		fi
	elif eval $BYOBU_TEST md5sum >/dev/null 2>&1; then
		if [ "$(cat /etc/skel/.bashrc | md5sum)" = "$(cat $HOME/.bashrc | md5sum)" ]; then
			printf "[ -r $BYOBU_CONFIG_DIR/prompt ] && . $BYOBU_CONFIG_DIR/prompt   #byobu-prompt#\n" >> "$HOME/.bashrc"
		fi
	fi
fi
[ -r "$BYOBU_CONFIG_DIR/prompt" ] || printf "[ -r ${BYOBU_PREFIX}/share/${PKG}/profiles/bashrc ] && . ${BYOBU_PREFIX}/share/${PKG}/profiles/bashrc  #byobu-prompt#\n" > "$BYOBU_CONFIG_DIR/prompt"

# Affects: New Wolfi installs -- add colorized prompt to local .profile
if [ "$BYOBU_DISTRO" = "Wolfi" ]; then
	# Wolfi defaults to "ash", which uses .profile
	if ! (grep -qs "#byobu-prompt#$" "$HOME/.profile"); then
		printf "[ -r $BYOBU_CONFIG_DIR/prompt ] && . $BYOBU_CONFIG_DIR/prompt   #byobu-prompt#\n" >> "$HOME/.profile"
	fi
	# Wolfi also has bash, which uses .bashrc
	if ! (grep -qs "#byobu-prompt#$" "$HOME/.bashrc"); then
		printf "[ -r $BYOBU_CONFIG_DIR/prompt ] && . $BYOBU_CONFIG_DIR/prompt   #byobu-prompt#\n" >> "$HOME/.bashrc"
	fi
fi

# Affects: Upgrades from <= byobu 5.126, clear out ec2/rcs cost statuses
rm -f "$BYOBU_RUN_DIR"/cache.tmux/ec2_cost* "$BYOBU_RUN_DIR"/cache.tmux/rcs_cost* "$BYOBU_RUN_DIR"/status.tmux/ec2_cost* "$BYOBU_RUN_DIR"/status.tmux/rcs_cost*

# vi: syntax=sh ts=4 noexpandtab
