#!/bin/bash

# Pearl APTus Update updates package list and displays
# information that some updates are available
# Created by Paweł "pavroo" Pijanowski 2017/06/15
# Copyright 2017-2020 under the GNU GPL2 License
# Last update 2020/10/06

sleep 30

# get default's locale file
DEFLOCDIR="/usr/share/pearl/pearl-aptus-upgrade-checker"
if [ "`cat /etc/default/locale | grep LANG= | grep de`" != "" ]; then
. $DEFLOCDIR/de
elif [ "`cat /etc/default/locale | grep LANG= | grep el`" != "" ]; then
. $DEFLOCDIR/el
elif [ "`cat /etc/default/locale | grep LANG= | grep es`" != "" ]; then
. $DEFLOCDIR/es
elif [ "`cat /etc/default/locale | grep LANG= | grep fr`" != "" ]; then
. $DEFLOCDIR/fr
elif [ "`cat /etc/default/locale | grep LANG= | grep hu`" != "" ]; then
. $DEFLOCDIR/hu
elif [ "`cat /etc/default/locale | grep LANG= | grep id_ID`" != "" ]; then
. $DEFLOCDIR/id_ID
elif [ "`cat /etc/default/locale | grep LANG= | grep it`" != "" ]; then
. $DEFLOCDIR/it
elif [ "`cat /etc/default/locale | grep LANG= | grep ja`" != "" ]; then
. $DEFLOCDIR/ja
elif [ "`cat /etc/default/locale | grep LANG= | grep pl`" != "" ]; then
. $DEFLOCDIR/pl
elif [ "`cat /etc/default/locale | grep LANG= | grep pt_BR`" != "" ]; then
. $DEFLOCDIR/pt_BR
elif [ "`cat /etc/default/locale | grep LANG= | grep pt_PT`" != "" ]; then
. $DEFLOCDIR/pt_PT
elif [ "`cat /etc/default/locale | grep LANG= | grep ru`" != "" ]; then
. $DEFLOCDIR/ru
elif [ "`cat /etc/default/locale | grep LANG= | grep zh_CN`" != "" ]; then
. $DEFLOCDIR/zh_CN
else
. $DEFLOCDIR/en
fi

DIALOG="yad --posx=-10 --posy=-80 --undecorated --skip-taskbar --borders=5 --image=system-software-update --on-top"
TEXT="--text="
OKEXIT=" --button=$LOCAL3:0 --button=$LOCAL4:1 "

# do not run it on live system
TESTMODE=`grep "live" /etc/passwd`
if [ "$TESTMODE" != "" ]; then
	exit 1
fi

# do not run it if pearl-firstrun is installed
if [ -f /usr/bin/pearl-firstrun ]; then
	exit 1
fi

sudo /usr/bin/pearl-aptus-upgrade-sim simulate

# check out connection
CHECKPING=`cat /tmp/pearl-ping | grep failed`
if [ "$CHECKPING" != "" ]; then
	exit 1
fi

UPGRADE1=$(cat /tmp/aptus-update/checkout | tail -n2 | grep [kM]B)

KTSUSS=`which ktsuss`
SPSU=`which spsu`
SUTOROOT=`which su-to-root`

if [ "$SPSU" != "" ]; then
	ROOTEXEC="spsu"
elif [ "$KTSUSS" != "" ]; then
	ROOTEXEC="ktsuss"
elif [ "$SUTOROOT" != "" ]; then
	ROOTEXEC="su-to-root -X -c"
else
	echo "no ktsuss, spsu nor su-to-root commands found... exiting.."
	exit 1
fi
# display a message
if [ "$UPGRADE1" != "" ]; then
	$DIALOG $TEXT"\n\n$LOCAL1\n\n$LOCAL2" $OKEXIT

	# run pearl-aptus-upgrade tool
	if [ "$?" = "0" ]; then
		PATH=$PATH:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
		$ROOTEXEC /usr/bin/pearl-aptus-upgrade
	fi
fi

if [ -d /tmp/aptus-update ]; then
	sudo /usr/bin/pearl-aptus-upgrade-sim clean
fi

exit 0
