#!/bin/sh

LASTRUN_FILE=/var/lib/un-applet/lastrun

UPDATE_INTERVAL=10000
NEED_APPLET="1"

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

# There does not seem to be a perfect way to test if the applet is running;
# using a pid file is dangerous, because there might be more than one
# instance of the applet running, and otoh these files might be deleted
# by some other process or might be still lying around after the applet
# received a signal 9 etc.
# pgrep fails to detect the applet when it is called with something like
# "python un-applet.py"
# The best bet seems to be to pipe the output of ps through grep;
# the output of "ps -ef | grep -i python | grep un-applet" may look like:
#
# username  2507     1  0 Jun23 ?        00:00:08 /usr/bin/python /usr/bin/un-applet
# username 30692 29661  0 01:14 pts/10   00:00:00 python un-applet.py
#
# In rare cases we might end up with false positives, e.g. when the user is
# currently editing an un-applet file with a python based editor we get a line:
#
# username 27833 26009  0 00:58 pts/6    00:00:07 /usr/bin/python /usr/bin/idle /usr/share/un-applet/un-applet.py
#
# However this is unlikely and better than false negatives.
# Of course we could pipe the output of ps through grep /usr/bin/un-applet ,
# however this would fail again if the applet is installed somewhere else
# or the .py file was called directly.
skip_job="0"
if [ "$NEED_APPLET" = "1" ]; then
    applet_proc=`ps -ef | grep -i python | grep un-applet`
    if [ "$applet_proc" = "" ]; then
        skip_job="1"
    fi
fi

if [ "$skip_job" = "0" ]; then
    lastrun=0
    if [ -f $LASTRUN_FILE ]; then
        lastrun=`head -1 $LASTRUN_FILE`
    fi

    elapsedtime=$(expr `date +%s` - $lastrun)
    if [ "$?" -ne "0" ]; then
        elapsedtime=$(expr $UPDATE_INTERVAL + 1)
    fi

    if [ $elapsedtime -gt $UPDATE_INTERVAL ]; then
        # avoid multiple instances of un-applet-update-pkgdatabase
        # beware: pgrep can handle only 15 characters unless we use -f , but
        # -f might also in rare cases lead to false positives
        if [ "`pgrep un-applet-updat`" = "" ]; then
            # use the -d switch to add a random delay, to avoid that everyone
            # tries to connect to the mirror servers at the same time
            un-applet-update-pkgdatabase -d
        fi
    fi
fi

exit 0
