#!/usr/bin/python
"""Program to clean /var/cache/apt/archives folder from files for packages
which are not installed. It doesn't take any arguments.

   Copyright (c) 2005 Matej Cepl <matej@ceplovi.cz>

   Permission is hereby granted, free of charge, to any person obtaining
   a copy of this software and associated documentation files (the
   "Software"), to deal in the Software without restriction, including
   without limitation the rights to use, copy, modify, merge, publish,
   distribute, sublicense, and/or sell copies of the Software, and to
   permit persons to whom the Software is furnished to do so, subject to
   the following conditions:

   The above copyright notice and this permission notice shall be
   included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
   MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
   IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
   CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
   TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
   SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
# $Id: midclean.py,v 1.8 2005-11-24 01:51:58 matej Exp $
import os,re,sys
try:
    testSet=set([1,2])
except NameError:
    from sets import Set as set
else:
    del testSet

root = os.getuid()==0
workDir = "/var/cache/apt/archives/"
# leave packages which are installed and those which are removed, but not
# purged.
searchExpression ='~i | ~c'

# get a list of all installed packages (see above for the explanation, what
# installed means in this context :-)).
currentlyInstalledRaw = os.popen("aptitude search -F '%%p# %%V#' '%s'" \
    % searchExpression,"r").readlines()
currentlyInstalled = set(["%s_%s" % tuple(line.split()) \
    for line in currentlyInstalledRaw])

# get the list of .deb-files on our computer
os.chdir(workDir)
packagesStored = dict([["_".join(line.split("_",2)[:2]),line] \
    for line in os.listdir(workDir) if line[-4:] == ".deb"])

# get a difference between what is and what should be installed
storedNotInstalled = set(packagesStored.keys()) - currentlyInstalled

# go remove what should be removed
for item in storedNotInstalled:
    filename = packagesStored[item]
    print "Removing %s." % filename
    if root:
        os.remove(filename)

# final reporting
if root:
    print >>sys.stderr,"Removed %d files." % len(storedNotInstalled)
else:
    print >>sys.stderr,"Only root can actually remove the files."