#!/bin/bash

# This script REALLY has to run via bash instead of sh because
# we use read with the option "-t", which doesn't work with sh.

# support for i18n and L10n
# shellcheck disable=SC1091
. gettext.sh
export TEXTDOMAIN=install-software-upgrades

RED="31"
BOLD_RED="\e[1;${RED}m"

echo -e "${BOLD_RED}$(gettext "Don't close this window!")"
echo -e "${BOLD_RED}$(gettext "Please wait until all upgrades have been installed...")"

countdown() {
	secs=$1
	while [ "$secs" -gt 0 ]; do
		echo -ne "Countdown: $secs\033[0K\r"
		secs=$((secs-1))

		read -r -t 1 -n 1 _key
		RETURN_OF_READ=$?

		if [ $RETURN_OF_READ -eq 0 ]; then
			# shellcheck disable=SC2005
			echo "$(gettext "Key press detected. Window is not closed automatically.")"
			while true
			do
				sleep 1
			done
		fi
	done
}

# upgrade Debian packages
apt clean
nala upgrade -y
apt clean


if command -v flatpak > /dev/null
then
	flatpak update
	flatpak uninstall --unused
fi

if command -v snap > /dev/null
then
	snap refresh
fi

if command -v pipx > /dev/null
then
	PIPX_HOME=/opt/pipx PIPX_BIN_DIR=/usr/local/bin pipx upgrade-all
fi

if command -v npm > /dev/null
then
	npm outdated -g
	npm update -g
fi

if command -v ollama > /dev/null
then
	ollama list | tail -n +2 | awk '{print $1}' | while read -r model; do
		echo "updating ollama model $model"
		ollama pull "$model"
	done
fi

OPEN_WEBUI_DIR="/opt/uv-venvs/open-webui/"
if [ -d "$OPEN_WEBUI_DIR" ]
then
        cd "$OPEN_WEBUI_DIR" || exit
	/usr/local/bin/uv pip install --upgrade open-webui
fi

TIMEOUT=10
# shellcheck disable=SC2005
echo "$(eval_gettext "This window will be closed automatically in \$TIMEOUT seconds.")"
# shellcheck disable=SC2005
echo "$(gettext "Press any key to keep this window open.")"
countdown $TIMEOUT
