#!/bin/sh
#
#	clean-by-atime, cleans archives from the cache, by removing
#	the least accessed first, until the user specified limit is
#	reached.
#
set -ex

LIMIT=${1}

if [ -z "${LIMIT}" ]; then
    echo -n "remove how many kilobytes of archives [none] ? "
    read LIMIT
    if [ -z "${LIMIT}" ]; then
        exit
    fi
fi

TMP_0=/tmp/clean-by-atime.1.files

# generate list of archives in cache
# least accessed first (%A@ and sort -rn)
# until cumulative size limit reached (%k and awk)
cd var/cache/apt/archives 
find . -name "*.deb" -printf "%A@ %k %f\n" | \
    sort -rn | \
    awk "{size += \$2; if (size < ${LIMIT}) print \$3;}" > ${TMP_0}

# remove the files (interactively)
rm -i `cat ${TMP_0}`
