#!/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
. 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 -t 1 -n 1 key
		RETURN_OF_READ=$?

		if [ $RETURN_OF_READ -eq 0 ]; then
			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

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