#!/bin/bash

# this script is part of apt-notifier package
#

ME=${0##*/}

if [ "${DEBUG_APT_NOTIFIER-false}" = "true" ]; then
	LOG=/tmp/apt_notifier_debug_${ME}_$(logname).log
	echo "$(date -R) : $0 $@" >> $LOG
	exec > >( tee -a "$LOG") 2>&1  
fi

usage() {
    cat<<USAGE
    
$ME - helper script to display available updates
      part of apt-notifier package
    
Usage: $ME [options]
    
    Without options a first localized (translated) line of the total 
    count-number (C) of available updates in the form
    
    {C} new updates available
    
    will be displayed followed by a 2nd line with some more aditional 
    details about the number of new (N), removed (R) and not upgraded (P) 
    packages in the form 
    
    ({C} upgraded, {N} newly installed, {R} to remove and {P} not upgraded.)

Options:
        -c|--count         display the count number only
        -d|--dist-upgrade  display the counts for dist-upgrade
        -u|--upgrade       display the counts for upgrade
        -h|--help          display this help text
    
    In case neither -d or -u is given the upgrade-type either 'dist-upgrade'
    or 'upgrade' is detected from users apt-notifierrc preferences.
    
    In case -d and -u is given --count is implicitely set and
    the displayed counts line consists of two count numbers separeted
    followed by user's chosen upgrade-type  by colon in the format
    {dist-upgrade-counts}:{upgrade-counts}:{UpgradeType}
    
USAGE
exit 1
}

# translations are defined within apt-notifier python modules 
# define functions to make xgettext ignore translations used here
mygettext()  { gettext  -d apt-notifier "$@"; }
myngettext() { ngettext -d apt-notifier "$@"; }

D="" ; C="" ; U=""
CheckType=""

for i in "$@"; do
   case "$i" in
     -c|--count)        C="true";;
     -d|--dist-upgrade) D="dist-upgrade"; CheckType=$D;;
     -u|--upgrade)      U="upgrade"; CheckType=$U ;;
     -h|--help)         usage;;
      *)                usage;;
   esac
done

if [ -n "$D" ] && [ -n "$U" ]; then
    CheckType="both"
    C="true"
fi

if [ -n "$C" ]; then
    # only show the number of available updates
    DISPLAY_COUNT_NUMBER_ONLY=true
else
    # show the count line's
    DISPLAY_COUNT_NUMBER_ONLY=false
fi

# UpgradeType:  dist-upgrade or upgrade
# check argv opts 
if [ "${CheckType}" = "both" ] ; then
    # get UpgradeType to count from apt-notifierrc
    if grep -sq '^UpgradeType=upgrade' /home/"$(logname)"/.config/apt-notifierrc 2>/dev/null; then
        UpgradeType="upgrade"
    else
        UpgradeType="dist-upgrade"
    fi
fi

if [ -z "${CheckType}" ]; then
    # nope - so we get UpgradeType to count from apt-notifierrc
    if grep -sq '^UpgradeType=upgrade' /home/"$(logname)"/.config/apt-notifierrc 2>/dev/null; then
        CheckType="upgrade"
        UpgradeType="upgrade"
    else
        CheckType="dist-upgrade"
        UpgradeType="dist-upgrade"
    fi
fi

UPDATER_APTPREF=/usr/lib/apt-notifier/shlib/updater_aptpref
AptPref_Opts=""
if [ -f "$UPDATER_APTPREF" ]; then
      . "$UPDATER_APTPREF"
fi

UpgradeCount=""
DistUpgradeCounts=""
CountLine=""
Count=""

case "$CheckType" in
    upgrade|dist-upgrade)
        # orig
        #APT_MSG=$(apt-get -s $AptPref_Opts $CheckType)
        # Count=$(grep -c  '^Inst '<<<$APT_MSG)
        
        # new
        APT_MSG=$(apt-get $AptPref_Opts -o Debug::NoLocking=true --trivial-only -V $CheckType 2>/dev/null | sed -nr '/^[[:space:]]/d; /[[:space:]][0-9]+[[:space:]]/{p;q}')
        up=0 new=0 x=""
        read up new x < <(echo ${APT_MSG} | tr -c '[:digit:]' ' ');
        Count=$((up+new))

        if [ -z "$C" ]; then
            CountLine="$APT_MSG"
            ## orig: 
            ## CountLine=$(grep -E '^[0-9]| [0-9]+ '<<<$APT_MSG)
        fi
        ;;
    both)
        Count=""
        # orig
        #APT_MSG=$(apt-get -s $AptPref_Opts dist-upgrade)
        #DistUpgradeCount=$(grep -c  '^Inst '<<<$APT_MSG)
        #APT_MSG=$(apt-get -s $AptPref_Opts upgrade)
        #UpgradeCount=$(grep -c  '^Inst '<<<$APT_MSG)
        # new
        APT_MSG=$(LC_ALL=C.UTF-8 apt-get $AptPref_Opts -o Debug::NoLocking=true --trivial-only -V dist-upgrade 2>/dev/null | sed -nr '/^[[:space:]]/d; /[[:space:]][0-9]+[[:space:]]/{p;q}')
        up=0 new=0 x=""
        read up new x < <(echo ${APT_MSG} | tr -c '[:digit:]' ' ');
        DistUpgradeCount=$((up+new))

        APT_MSG=$(LC_ALL=C.UTF-8 apt-get $AptPref_Opts -o Debug::NoLocking=true --trivial-only -V upgrade 2>/dev/null | sed -nr '/^[[:space:]]/d; /[[:space:]][0-9]+[[:space:]]/{p;q}')
        up=0 new=0 x=""
        read up new x < <(echo ${APT_MSG} | tr -c '[:digit:]' ' ');
        UpgradeCount=$((up+new))

        ;;
            
esac


if [ "$DISPLAY_COUNT_NUMBER_ONLY" == "true" ]; then
    case "$CheckType" in
        both)  echo "${DistUpgradeCount}:${UpgradeCount}:${UpgradeType}" ;;
           *)  echo "$Count" ;;
    esac
else
	case $Count in
	    "") : 
	        ;;
	    0)  # untranslated old non-plurals msg
	        umsg="0 updates available"
	        # translated old non-plurals msg
	        tmsg=$(mygettext "$umsg")
	        
	        numsg='No updates available'
	        nmsg=$(mygettext "$numsg")
	        ;;
	    1)  # untranslated old non-plurals msg
	        umsg='1 new update available'
	        # translated old non-plurals msg
	        tmsg=$(mygettext "$umsg")
	
	        numsg='{num} new update available'
	        nmsg=$(myngettext '{num} new update available'  '{num} new updates available' $Count)
	        nmsg="${nmsg/\{num\}/$Count}"
	        numsg="${nmsg/\{num\}/$Count}"
	        ;;
	    *)  # untranslated old non-plurals msg
	        umsg='$count new updates available'
	        # translated old non-plurals msg
	        tmsg=$(mygettext "$umsg")
	        tmsg="${tmsg/\$count/$Count}"
	
	        numsg='{num} new updates available'
	        nmsg=$(myngettext '{num} new update available'  '{num} new updates available' $Count)
	        nmsg="${nmsg/\{num\}/$Count}"
	        numsg="${numsg/\{num\}/$Count}"
	        ;;
	esac


	# check we have translations of the plurals msg
	if [ "$nmsg" != "$numsg" ]; then
	    # yep, translated - we take the new plurals msg
	    msg="$nmsg"
	else
	    # check we have translated old non-plurals msg  
	    if [ "$tmsg" != "$umsg" ]; then
	        # yep, so we take the old translated one
	        msg=$tmsg
	    else
	        # neither old non-plurals nor new plurals are translated
	        # se we take the new plurals msg
	        msg=$nmsg
	    fi
	fi
	UpdatesMsg=$msg
    echo "$UpdatesMsg"
    echo "($CountLine)";
fi
