#!/bin/sh

# Helper script for the Update Notifier Applet.
#
# The script calls apt-get/aptitude update and then extracts information about
# pending updates from the package database.
#
# The script accepts one optional command line argument:
#
# If called without arguments it runs silently, if -v or --verbose is given
# as argument diagnostic messages are printed to stdout, if -i or --interactive
# is given the user will additionally be prompted for confirmation after the
# script has finished. If the argument -d or --delayed is given the script runs
# silently with a random delay of 0-3000 seconds (0-50 minutes) to avoid
# too many simultaneous connections with the software mirrors.
#
# Essential parts of the code are heavily inspired by /usr/sbin/apticron .
# However unlike apticron, this script simply writes the number of upgradable
# packages, the list of package names and the time stamp of its last
# successful execution into three files in /var/lib/un-applet
#

LASTRUNFILE=/var/lib/un-applet/lastrun
PKGSFILE=/var/lib/un-applet/pkgnames
STATEFILE=/var/lib/un-applet/state

mkdir -p `dirname $STATEFILE`

DIST_UPGRADE="1"
NEED_APPLET="1"
NOTIFY_HOLDS="0"
NOTIFY_NEW="0"
PM_PROGRAM="apt-get"
VERIFY_MIRRORS="1"

UPGRADE_CMD="dist-upgrade"
DELAYED="0"
MODE="quiet"
VERBOSE="0"

case "$1" in
    "-d")
        DELAYED="1";;
    "--delayed")
        DELAYED="1";;
    "-i")
        MODE="interactive"
        VERBOSE="1";;
    "--interactive")
        MODE="interactive"
        VERBOSE="1";;
    "-v")
        VERBOSE="1";;
    "--verbose")
        VERBOSE="1";;
esac

if [ -e /etc/un-applet/un-applet.conf ]; then
    . /etc/un-applet/un-applet.conf
fi

if [ "$PM_PROGRAM" = "aptitude" ]; then
    if [ -z `which aptitude` ]; then
        PM_PROGRAM="apt-get"
    fi
fi

if [ "$DIST_UPGRADE" = "0" ]; then
    if [ "$PM_PROGRAM" = "aptitude" ]; then
        UPGRADE_CMD="safe-upgrade"
    else
        UPGRADE_CMD="upgrade"
    fi
else
    if [ "$PM_PROGRAM" = "aptitude" ]; then
        UPGRADE_CMD="full-upgrade"
    fi
fi

if [ "$DELAYED" = "1" ]; then
    sleep `shuf -i 0-3000 -n 1`
    # if we were called with -d and NEED_APPLET="1" only proceed if still an
    # instance of the applet is running, else exit silently
    if [ "$NEED_APPLET" = "1" ]; then
        applet_proc=`ps -ef | grep -i python | grep un-applet`
        if [ "$applet_proc" = "" ]; then
            exit 0
        fi
    fi
fi

if [ "$VERBOSE" = "1" ]; then
    if [ "$MODE" = "interactive" ]; then
        TITLE=`gettext -d un-applet "Updating package database..."`
        /bin/echo -ne "\033]0;$TITLE\007"
    fi
    echo `gettext -d un-applet "Starting update of the package database..."`
fi

# check if all mirrors from the sources.list file(s) can be accessed, otherwise
# we might end up with false positives

if [ "$VERIFY_MIRRORS" = "1" ]; then
    if [ "$VERBOSE" = "1" ]; then
        echo `gettext -d un-applet "Testing mirror server(s)..."`
        un-applet-verify-mirrors -v
    else
        un-applet-verify-mirrors -q
    fi
    if [ "$?" = "1" ]; then
        echo "-1" > $STATEFILE
        echo "" > $PKGSFILE
        if [ "$VERBOSE" = "1" ]; then
            echo
            echo `gettext -d un-applet "Failed to update package database."`
            if [ "$MODE" = "interactive" ]; then
                TITLE=`gettext -d un-applet "Error"`
                /bin/echo -ne "\033]0;$TITLE\007"
                echo -n `gettext -d un-applet "Please press Enter to close the window."`
                read whatever
            fi
        fi
        exit 1
    fi
fi

# If we try to update the package database while another process (like aptitude
# or synaptic) has grabbed /var/lib/dpkg/lock we might end up with a false
# negative result.

if [ "$VERBOSE" = "1" ]; then
    echo
    echo -n `gettext -d un-applet "Checking if the package database is locked by another process..."`" "
fi

for lockfile in "/var/lib/dpkg/lock" "/var/lib/apt/lists/lock"; do
    lsof $lockfile > /dev/null 2>&1
    if [ "$?" = "0" ]; then
        echo "-2" > $STATEFILE
        echo "" > $PKGSFILE
        if [ "$VERBOSE" = "1" ]; then
            echo `gettext -d un-applet "yes."`
            echo `gettext -d un-applet "Failed to update package database."`
            echo `gettext -d un-applet "Could not get lock:"`" $lockfile"
            if [ "$MODE" = "interactive" ]; then
                TITLE=`gettext -d un-applet "Error"`
                /bin/echo -ne "\033]0;$TITLE\007"
                echo -n `gettext -d un-applet "Please press Enter to close the window."`
                read whatever
            fi
        fi
        exit 2
    fi
done

if [ "$VERBOSE" = "1" ]; then
    echo `gettext -d un-applet "no."`
    echo
    echo `gettext -d un-applet "Updating package database..."`
    echo `gettext -d un-applet "Running command:"`" $PM_PROGRAM update"
    echo
fi

# Ideas borrowed from apticron:

# update the package lists
if [ "$VERBOSE" = "1" ]; then
    if [ "$PM_PROGRAM" = "aptitude" ]; then
        aptitude update || true
    else
        apt-get update || true
    fi
    echo
    echo `gettext -d un-applet "Generating the list of available updates..."`
else
    if [ "$PM_PROGRAM" = "aptitude" ]; then
        aptitude -q=2 update || true
    else
        apt-get -qq update || true
    fi
fi

# get the list of packages which are pending an upgrade
APT_OPTS=""
if [ "$NOTIFY_HOLDS" = "1" ]; then
    if [ "$PM_PROGRAM" = "aptitude" ]; then
        APT_OPTS="~U"
    else
        APT_OPTS="--ignore-hold"
    fi
fi

if [ "$PM_PROGRAM" = "aptitude" ]; then
    PKGNAMES=`aptitude -v -y -s --allow-untrusted $UPGRADE_CMD $APT_OPTS | \
          /bin/grep ^Inst |  /usr/bin/cut -d\  -f2 | /usr/bin/sort | tr "\\n" " "`
else
    # apt-get syntax changed with v.1.1, since 1.3 the new syntax is mandatory
    aptver=`apt-get -v | /usr/bin/head -1 | /usr/bin/cut -d\  -f2 | /usr/bin/cut -d\. -f1,2`
    #if [ "$aptver" \< "1.1" ]; then
    if [ "`expr $aptver \<= 1.0`" = "1" ]; then
        APT_OPTS="$APT_OPTS --allow-unauthenticated"
    else
        APT_OPTS="$APT_OPTS --allow-unauthenticated --allow-downgrades --allow-remove-essential --allow-change-held-packages"
    fi
    PKGNAMES=`apt-get -q -y -s $APT_OPTS $UPGRADE_CMD | \
          /bin/grep ^Inst | /usr/bin/cut -d\  -f2 | /usr/bin/sort | tr "\\n" " "`
fi

if [ "$?" != "0" ]; then
    echo "-3" > $STATEFILE
    echo "" > $PKGSFILE
    if [ "$VERBOSE" = "1" ]; then
        echo
        echo `gettext -d un-applet "Failed to update package database."`
        if [ "$MODE" = "interactive" ]; then
            TITLE=`gettext -d un-applet "Error"`
            /bin/echo -ne "\033]0;$TITLE\007"
            echo -n `gettext -d un-applet "Please press Enter to close the window."`
            read whatever
        fi
    fi
    exit 3
fi

if [ "$NOTIFY_NEW" = "0" ]; then
    if [ "$PM_PROGRAM" = "aptitude" ]; then
        INSTALLED_PKGS=`aptitude -q=2 -F "%p" search ~i | tr "\\n" " "`
    else
        INSTALLED_PKGS=$(echo `apt-mark showauto` `apt-mark showmanual` | tr "\\n" " ")
    fi
    PKGS=""
    for p in $PKGNAMES; do
        case " $INSTALLED_PKGS " in
            *\ $p\ *)
                PKGS="$PKGS $p"
            ;;
        esac
    done
    PKGNAMES="$PKGS"
fi

NUM_PACKAGES=`echo $PKGNAMES | wc -w`

# end of apticron code, now just write out the results to our files
# in /var/lib/un-applet

echo $NUM_PACKAGES > $STATEFILE
echo $PKGNAMES | tr " " "\n" > $PKGSFILE
echo `date +%s` > $LASTRUNFILE

if [ "$VERBOSE" = "1" ]; then
    echo
    echo `gettext -d un-applet "Update of package database complete."`
    echo "$NUM_PACKAGES "`gettext -d un-applet "updated package(s) available."`
    if [ "$MODE" = "interactive" ]; then
        TITLE=`gettext -d un-applet "Update finished"`
        /bin/echo -ne "\033]0;$TITLE\007"
        echo -n `gettext -d un-applet "Please press Enter to close the window."`
        read whatever
    fi
fi

exit 0
