#!/bin/sh
#

#set -e
#
# This file understands the following apt configuration variables:
#
#  "APT::Periodic::Update-Package-Lists=1"
#  - Do "apt-get update" automatically every n-days (0=disable)
#    
#  "APT::Periodic::Download-Upgradeable-Packages=0",
#  - Do "apt-get upgrade --download-only" every n-days (0=disable)
# 
#  "APT::Periodic::AutocleanInterval"
#  - Do "apt-get autoclean" every n-days (0=disable)
#
#  "APT::Periodic::Unattended-Upgrade"
#  - Run the "unattended-upgrade" security upgrade script 
#    every n-days (0=disabled)
#    Requires the package "unattended-upgrades" and will write
#    a log in /var/log/unattended-upgrades
# 
#  "APT::Archives::MaxAge",
#  - Set maximum allowed age of a cache package file. If a cache 
#    package file is older it is deleted (0=disable)
#
#  "APT::Archives::MaxSize",
#  - Set maximum size of the cache in MB (0=disable). If the cache
#    is bigger, cached package files are deleted until the size
#    requirement is met (the biggest packages will be deleted 
#    first).
#
#  "APT::Archives::MinAge"
#  - Set minimum age of a package file. If a file is younger it
#    will not be deleted (0=disable). Usefull to prevent races 
#    and to keep backups of the packages for emergency.
# 

check_stamp()
{
    stamp="$1"
    interval="$2"

    if [ $interval -eq 0 ]; then
        return 1
    fi

    if [ ! -f $stamp ]; then
        return 0
    fi

    # compare midnight today to midnight the day the stamp was updated
    stamp=$(date --date=$(date -r $stamp --iso-8601) +%s)
    now=$(date --date=$(date --iso-8601) +%s)
    delta=$(($now-$stamp))

    # intervall is in days,
    interval=$(($interval*60*60*24))
    #echo "stampfile: $1"
    #echo "interval=$interval, now=$now, stamp=$stamp, delta=$delta"

    if [ $delta -ge $interval ]; then
        return 0
    fi

    return 1
}

update_stamp()
{
    stamp="$1"

    touch $stamp
}



# we check here if autoclean was enough sizewise
check_size_constraints()
{
    # min-age in days
    MaxAge=0
    MinAge=2
    MaxSize=0
    CacheDir="var/cache/apt"
    CacheArchive="archives/"
    eval $(apt-config shell MaxAge APT::Archives::MaxAge)
    eval $(apt-config shell MinAge APT::Archives::MinAge)
    eval $(apt-config shell MaxSize APT::Archives::MaxSize)
    eval $(apt-config shell Dir Dir)
    eval $(apt-config shell CacheDir Dir::Cache)
    eval $(apt-config shell CacheArchive Dir::Cache::archives)

    # sanity check
    if [ -z "$CacheDir" -o -z "$CacheArchive" ]; then
	echo "empty Dir::Cache or Dir::Cache::archives, exiting"
	exit
    fi
    
    Cache="${Dir%/}/${CacheDir%/}/${CacheArchive%/}/"

    # check age
    if [ ! $MaxAge -eq 0 ] && [ ! $MinAge -eq 0 ]; then
	find $Cache -name "*.deb"  \( -mtime +$MaxAge -and -ctime +$MaxAge \) -and -not \( -mtime -$MinAge -or -ctime -$MinAge \) -print0 | xargs -r -0 rm -f
    elif [ ! $MaxAge -eq 0 ]; then
	find $Cache -name "*.deb"  -ctime +$MaxAge -and -mtime +$MaxAge -print0 | xargs -r -0 rm -f
    fi
    
    # check size
    if [ ! $MaxSize -eq 0 ]; then
	# maxSize is in MB
	MaxSize=$(($MaxSize*1024))

	#get current time
	now=$(date --date=$(date --iso-8601) +%s)
	MinAge=$(($MinAge*24*60*60))

	# reverse-sort by mtime
	for file in $(ls -rt $Cache/*.deb 2>/dev/null); do 
	    du=$(du -s $Cache)
	    size=${du%%/*}
	    # check if the cache is small enough
	    if [ $size -lt $MaxSize ]; then
		break
	    fi

	    # check for MinAge of the file
	    if [ ! $MinAge -eq 0 ]; then 
		# check both ctime and mtime 
		mtime=$(stat -c %Y $file)
		ctime=$(stat -c %Z $file)
		if [ $mtime -gt $ctime ]; then
		    delta=$(($now-$mtime))
		else
		    delta=$(($now-$ctime))
		fi
		#echo "$file ($delta), $MinAge"
		if [ $delta -le $MinAge ]; then
		    #echo "Skiping $file (delta=$delta)"
		    break
		fi
	    fi

	    # delete oldest file
	    rm -f $file
	done
    fi
}

# sleep for a random interval of time (default 30min)
# (some code taken from cron-apt, thanks)
random_sleep()
{
    RandomSleep=1800
    eval $(apt-config shell RandomSleep APT::Periodic::RandomSleep)
    if [ $RandomSleep -eq 0 ]; then
	return
    fi
    if [ -z "$RANDOM" ] ; then
        # A fix for shells that do not have this bash feature.
	RANDOM=$(dd if=/dev/urandom count=1 2> /dev/null | cksum | cut -c"1-5")
    fi
    TIME=$(($RANDOM % $RandomSleep))
    sleep $TIME
}

# main

if ! which apt-config >/dev/null; then
	exit 0
fi

UpdateInterval=0
DownloadUpgradeableInterval=0
eval $(apt-config shell UpdateInterval APT::Periodic::Update-Package-Lists DownloadUpgradeableInterval APT::Periodic::Download-Upgradeable-Packages)
AutocleanInterval=$DownloadUpgradeableInterval
eval $(apt-config shell AutocleanInterval APT::Periodic::AutocleanInterval)
UnattendedUpgradeInterval=0
eval $(apt-config shell UnattendedUpgradeInterval APT::Periodic::Unattended-Upgrade)

# check if we actually have to do anything
if [ $UpdateInterval -eq 0 ] &&
   [ $DownloadUpgradeableInterval -eq 0 ] &&
   [ $UnattendedUpgradeInterval -eq 0 ] &&
   [ $AutocleanInterval -eq 0 ]; then
    exit 0
fi

# laptop check, on_ac_power returns:
#       0 (true)    System is on mains power
#       1 (false)   System is not on mains power
#       255 (false) Power status could not be determined
# Desktop systems always return 255 it seems
if which on_ac_power >/dev/null; then
    on_ac_power
    if [ $? -eq 1 ]; then
	exit 0
    fi
fi

# sleep random amount of time to avoid hitting the 
# mirrors at the same time
random_sleep

# check if we can access the cache
if ! apt-get check -q -q 2>/dev/null; then
    # wait random amount of time before retrying
    random_sleep
    # check again
    if ! apt-get check -q -q 2>/dev/null; then
	echo "$0: could not lock the APT cache while performing daily cron job. "
	echo "Is another package manager working?"
	exit 1
    fi
fi

UPDATE_STAMP=/var/lib/apt/periodic/update-stamp
if check_stamp $UPDATE_STAMP $UpdateInterval; then
    if apt-get -qq update 2>/dev/null; then
        if which dbus-send >/dev/null && pidof dbus-daemon >/dev/null; then
            dbus-send --system / app.apt.dbus.updated boolean:true
        fi
        update_stamp $UPDATE_STAMP
    fi
fi

DOWNLOAD_UPGRADEABLE_STAMP=/var/lib/apt/periodic/download-upgradeable-stamp
if check_stamp $DOWNLOAD_UPGRADEABLE_STAMP $DownloadUpgradeableInterval; then
    apt-get -qq -d dist-upgrade 2>/dev/null
    update_stamp $DOWNLOAD_UPGRADEABLE_STAMP
fi

UPGRADE_STAMP=/var/lib/apt/periodic/upgrade-stamp
if check_stamp $UPGRADE_STAMP $UnattendedUpgradeInterval; then
    unattended-upgrade
    update_stamp $UPGRADE_STAMP
fi

AUTOCLEAN_STAMP=/var/lib/apt/periodic/autoclean-stamp
if check_stamp $AUTOCLEAN_STAMP $AutocleanInterval; then
    apt-get -qq autoclean
    update_stamp $AUTOCLEAN_STAMP
fi

# check cache size 
check_size_constraints