#!/bin/bash
# -*- ENCODING: UTF-8 -*-

# apt-actualiza
#
# Install (security) updates.
#
# Copyright (c) 2013-2026: Alexis Puente Montiel   < pica (a) picalibre.org >
#
# Licensed according to GNU AGPL version 3.0.
#
# It is libre/free software; you can use, redistribute and/or modify it according to the terms of GNU AGPL as published by GNU, version 3.0, 19 November 2007.
#
# It is distributed in the hope that it will be useful, but without any warranty. Read GNU AGPL version 3.0 for additional details.
#
# A copy of GNU AGPL version 3.0 is available at /usr/share/doc/<software-package-name>/agpl-3.0.txt (additionally on Internet as text at https://www.gnu.org/licenses/agpl-3.0.txt and as HTML at https://www.gnu.org/licenses/agpl-3.0-standalone.html ).
#
# Note: Additionally to the official e-mails, picalibre.org is strictly the only official site for this software project, please consider using it to download, report bugs and contribute.
#
# Depends: apt, bash, bc, coreutils, gawk | mawk | original-awk, grep
# Recommends: inetutils-ping | iputils-ping, menu, pica-skel, wget


### SCRIPT VARIABLES ########################################

CNAME="apt-actualiza"
VERSION="1.3.1"
TITLE="'apt-actualiza'"
ICON="/usr/share/icons/apt-actualiza.png"

# Translations
if [ "$LANG" = "" ] ; then export $(cat /etc/default/locale | grep -a 'LANG=') ; fi
TEXTDOMAIN=pica-apt
TEXTDOMAINDIR=/usr/share/locale/

# Write errors to log
ERRORLOG="$HOME/.${CNAME}.log"
if [ -e "$ERRORLOG" ] ; then
	mv -f $ERRORLOG ${ERRORLOG}.ant
fi
if [ -e "$ERRORLOG" ] ; then rm -rf "$ERRORLOG" ; fi

for i in /etc/pica-global.dist /etc/pica-global.orig /etc/pica-global /etc/pica-global.local ~/.pica-global ~/pica-global ; do
	if [ -f "$i" ] ; then
	cat "$i"
	source "$i"
	source <(cat $i | sed -e "s/=\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)/=Y/g" -e "s/=\(No\|no\|n\)/=N/g" -e "s/=\"\(YES\|Yes\|yes\|y\|SÍ\|SI\|Sí\|Si\|sí\|si\|S\|s\)\"/=Y/g" -e "s/=\"\(No\|no\|n\)\"/=N/g")
	fi
done
if [ "$DEBUG" = "Y" ] ; then
	set -xv
	DEBUG="Y"
else
	ERRORLOG="/tmp/.${CNAME}_$(id -nu).log"
	if [ -e "$ERRORLOG" ] ; then mv -f $ERRORLOG ${ERRORLOG}.ant ; fi
	if [ -e "$ERRORLOG" ] ; then rm -rf "$ERRORLOG" ; fi
fi
#if [ "$DEBUG" = "" ] ; then DEBUG="N" ; fi
if [ "$DEBUG" != "N" ] ; then
exec > >(tee -a "$ERRORLOG") 2>&1
echo "$0" "$*" >> "$ERRORLOG"
echo "$CNAME" "$VERSION" >> "$ERRORLOG"
echo $(date +%Y-%m-%d_%H:%M:%S) $"Start" >> "$ERRORLOG"
echo "env:" >> "$ERRORLOG"
env >> "$ERRORLOG"
echo "set:" >> "$ERRORLOG"
set >> "$ERRORLOG"
#else
#exec 2>>"$ERRORLOG"
fi

# Description:
BDESCRIP=$"Install (security) updates."
LDESCRIP=$"$TITLE is a tool to install (security) updates."

# Documentation:
docu_info () {
echo "$CNAME ($VERSION) - $BDESCRIP"
echo 
echo $"Usage:" $CNAME [$"OPTIONS"]
echo 
echo $"Options:"
echo -e "$ODESCRIP"
echo 
echo $"'man $CNAME' for more information."
echo 
}
ODESCRIP=" -x""\t"$"Show help documentation."

while getopts x OPTION ; do
	case $OPTION in
		x )   docu_info ; exit 0 ;;
	esac
done


### ROOT CHECK ########################################

#if [ "$(cat /etc/passwd | grep -aE ^$(whoami): | cut -d ':' -f 3 )" -ne 0 ] ; then
if [ "$(id -u)" -ne 0 ] ; then
	echo $"$TITLE must be launched as SuperUser. Cannot continue."
	exit 1
fi
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/opt/trinity/bin


### INTERNET TEST ########################################

ping -c 3 ftp.fau.de || ping -c 3 mirrorservice.org || ping -c 3 ftp.ch.debian.org

if [ "$?" -eq 0 ] ; then
	TESTINTERNET="Y"
else
	echo "No PING (no ICMP). Pass-through test..."
	wget http://ftp.fau.de -O /dev/null || wget http://mirrorservice.org -O /dev/null || wget http://ftp.ch.debian.org -O /dev/null
	if [ "$?" -eq 0 ] ; then
		echo "WGET (TCP connections) works. Internet OK."
		TESTINTERNET="Y"
	else
		echo $"No Internet connection."
		TESTINTERNET="N"
	fi
fi


### CLOCK CHECK ########################################

clock_check () {

YMD="$(date +%Y-%m-%d)"
if [ "$(date +%Y)" -lt 2025 ] ; then
	CLOCKTEXT=$"The clock seems to be in the past: $YMD \nIf it is a computer with a button battery to keep time, then the button battery probably needs to be replaced (if this is not the first time this computer is turned on), to prevent the clock reverting to the past every time the computer loses power."
fi

}


### CHECK FDM ########################################

#FDS=$(df -m | grep -a /dev/ | grep -aEi " /$" | sort -n | head -n 1 | awk '{print $4}')
FDS=$(df -m /               | grep -aEi "^/" | awk '{print $4}')
FDP=$(df -m /var/cache/apt/ | grep -aEi "^/" | awk '{print $4}')
FDM=$(printf "$FDS\n$FDP\n" | sort -n | head -n 1)

if [ "$FDM" -lt 250 ] ; then
	echo " "
	echo $"WARNING: VERY little free space on the disk ($FDM MiB)."
	echo $"The installation will probably fail and will need to be repaired. To interrupt, simultaneously press the Ctrl C keys."
	read -t 10 SEL
elif [ "$FDM" -lt 1000 ] ; then
	echo " "
	echo $"WARNING: Little free space on the disk ($FDM MiB)."
	echo $"The installation will possibly fail and will need to be repaired. To interrupt, simultaneously press the Ctrl C keys."
	read -t 10 SEL
else
	true
fi


### RELEASE EOL CHECK ########################################

eol_check () {

if [ -e /etc/picalibre_version ] ; then cat /etc/picalibre_version >> "$ERRORLOG" ; PRE_PICAVERSION=$(cat /etc/picalibre_version | cut -d '.' -f 1 ) ; fi
if [ -e /etc/debian_version ] ; then cat /etc/debian_version >> "$ERRORLOG" ; PRE_DEBIANVERSION=$(cat /etc/debian_version | cut -d '.' -f 1 ) ; fi
if [ -e /etc/devuan_version ] ; then cat /etc/devuan_version >> "$ERRORLOG" ; PRE_DEVUANVERSION=$(expr $(cat /etc/devuan_version | sed -e 's|jessie|1|g' -e 's|ascii|2|g' -e 's|beowulf|3|g' -e 's|chimaera|4|g' -e 's|daedalus|5|g' -e 's|excalibur|6|g' | cut -d '.' -f 1 | sed 's|/ceres||g') + 7 ) ; fi
DEBIANVERSION=$(printf "$PRE_PICAVERSION\n$PRE_DEBIANVERSION\n$PRE_DEVUANVERSION" | sort -n -r | head -n 1 )
POSTDEBIANVERSION=$(expr -$DEBIANVERSION - 1)

if [ "$(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^falkon" )" != "" ] ; then
NVER=$(echo "1999+($DEBIANVERSION*2)+2"  | bc -l)12
EOL=$(echo "1999+($DEBIANVERSION*2)+3"   | bc -l)06
else
NVER=$(echo "1999+($DEBIANVERSION*2)+3"  | bc -l)06
EOL=$(echo "1999+($DEBIANVERSION*2)+3+2" | bc -l)06
fi

if [ "$(date +%Y%m)" -lt "$NVER" ] || [ "$PRE_PICAVERSION" = "x" ] ; then
	EOLTEXT=""
elif [ "$(date +%Y%m)" -le "$EOL" ] ; then
	EOLTEXT=$"It is recommended that you install or upgrade to the new version of PicaLibre. (In order to install the new version of PicaLibre then download from www.picalibre.org, while in order to upgrade then install pica-eleva$POSTDEBIANVERSION using Synaptic or 'app'.)"
elif [ "$(date +%Y%m)" -gt "$EOL" ] ; then
	EOLTEXT=$"WARNING: Your version of PicaLibre is obsolete and it has no security updates, it is critical that you install or upgrade to a newer version of PicaLibre immediately. (In order to install the new version of PicaLibre then download from www.picalibre.org, while in order to upgrade then install pica-eleva$POSTDEBIANVERSION using Synaptic or 'app'.)"
else
	echo $"ERROR:" $(date +%Y%m) DEBIANVERSION=$DEBIANVERSION PRE_DEBIANVERSION=$PRE_DEBIANVERSION PRE_DEVUANVERSION=$PRE_DEVUANVERSION
	#exit 1
fi

}


### SCRIPT ########################################

LOCALREPO=$(cat /etc/apt/sources.list | grep -aEi "^deb " | grep -aEiv '//' )

if [ "$TESTINTERNET" = "N" ] && [ "$LOCALREPO" = "" ] ; then
	
	echo $"ERROR: No Internet connection, no local copy of packages."
	FINAL=1
	
else
	
	# 'export DEBIAN_FRONTEND=noninteractive' makes the default answers be used for all questions, https://manpages.debian.org/bullseye/debconf-doc/debconf.7.en.html
	# This can be set as a default option with:		dpkg-reconfigure debconf --frontend=noninteractive
	# A more detailed configuration can be achieved with:	echo '* libraries/restart-without-asking boolean true' | debconf-set-selections
	
	printf "$(date +%Y-%m-%d_%H:%M:%S) " >> /var/log/apt-actualiza
#	find "$TFS"/var/lib/apt/lists -type f | grep -aEiv "lock$" | while read i ; do rm -f "$i" ; done
	if [ -e "$TFS/var/cache/apt-xapian-index/" ] ; then find "$TFS"/var/cache/apt-xapian-index/ -type f | while read i ; do rm -rf $i ; done ; fi
	find "$TFS"/var/cache/apt/  -maxdepth 1 -type f | grep -aEi "pkgcache|srcpkgcache" | while read i ; do rm -rf $i ; done
	for i in /home/* ; do if [ -e "$i/.mozilla" ] ; then cp -av --remove-destination $i/.mozilla $i/.mozilla_apt-actualiza ; fi ; done
	for i in /home/* ; do if [ -e "$i/.config/firefox" ] ; then cp -av --remove-destination $i/.config/firefox $i/.config/firefox_apt-actualiza ; fi ; done
	for i in /home/* ; do if [ -e "$i/.local/share/firefox" ] ; then cp -av --remove-destination $i/.local/share/firefox $i/.local/share/firefox_apt-actualiza ; fi ; done
	if [ -e "/etc/grubil" ] ; then cat "/etc/grubil" ; sleep 10 ; fi
	export DEBIAN_FRONTEND=noninteractive
	export APT_LISTCHANGES_FRONTEND=cat
	apt-get --allow-releaseinfo-change update -y
	apt-get update -y
	printf "$?" >> /var/log/apt-actualiza
	apt-get upgrade -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold"
	if [ "$(cat /etc/picalibre_version | grep -aEio [0-9])" != "" ] ; then if [ "$(cat /etc/apt/sources.list | grep -aEi backports | grep -aEi "^deb" | awk '{print $3}' | sort -u | grep -a -c ^)" -eq 1 ] ; then for i in $(check-support-status | grep -aEi "^  - " | sed "s|  - ||g" | cut -d " " -f 1) $(dpkg -l | grep -aEi "^ii|^hi" | awk '{print $2}' | sed "s|:.*||g" | grep -aEi "^yt-dlp|webengine|webkit") ; do apt-get install --no-install-recommends -t $(cat /etc/apt/sources.list | grep -aEi backports | grep -aEi "^deb" | awk '{print $3}' | sort -u) -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold" $i ; apt-mark auto $i ; done ; fi ; fi  # for i in $(check-support-status | grep -aEi "^  - " | awk '{print $2}') ; do
	if [ "$APT" = "" ] || [ "$APT" = "pica" ] || [ "$APT" = "PICA" ] ; then
		# first auto, but finally try no auto to ensure no error.
		# for 'pica-actualiza' and other minimally interactive modes.
		apt-get dist-upgrade -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold"
		export DEBIAN_FRONTEND=dialog
		apt-get dist-upgrade -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold"
		printf "$?" >> /var/log/apt-actualiza
		export DEBIAN_FRONTEND=noninteractive
	elif [ "$APT" = "auto" ] || [ "$APT" = "AUTO" ] ; then
		# exclusively auto.
		# for 'cron' and other never interactive modes.
		apt-get dist-upgrade -y -o Dpkg::Options::="--force-confmiss" -o Dpkg::Options::="--force-confold"
		printf "$?" >> /var/log/apt-actualiza
	else
		# [ "$APT" != "" ] || [ "$APT" != "pica" ] || [ "$APT" != "PICA" ] || [ "$APT" = "auto" ] || [ "$APT" = "AUTO" ]
			printf $"ERROR:" APT = $APT | tee -a /var/log/apt-actualiza
			false
			printf "$?" >> /var/log/apt-actualiza
	fi
#	if [ "$(cat /etc/apt/apt.conf | grep -a apt-post)" = "" ] ; then
		if [ "$(command -v apt-post)" != "" ] ; then
			apt-post ; printf "$?" >> /var/log/apt-actualiza
		fi
#	fi
	echo >> /var/log/apt-actualiza
	
	FINAL=$(cat /var/log/apt-actualiza | tail -n 1 | awk '{print $NF}')
	#rm -f /tmp/apt-actualiza

fi

clock_check
if [ "$CLOCKTEXT" != "" ] ; then
	echo " "
	echo "$CLOCKTEXT"
	read -t 10 SEL
fi

eol_check
if [ "$EOLTEXT" != "" ] ; then
	echo " "
	echo "$EOLTEXT"
	read -t 10 SEL
fi

echo $FINAL

exit $(echo $FINAL | bc -l)
