#!/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.
USE AT YOUR OWN RISK, THIS MAY HURT YOU!!!"""
# $Id: midclean.py,v 1.2 2005-11-23 06:00:36 matej Exp $
import os,re,sys

currentlyInstalledRaw = os.popen("aptitude search -F '%p %V' '~i'",
    "r").readlines()
currentlyInstalled = [line.split() for line in currentlyInstalledRaw]
# currentlyInstalled is list of lists looking like this:
# [...,['zoem', '05-154-1']]
currNames = tuple([x[0] for x in currentlyInstalled])
currVersions = tuple([x[1] for x in currentlyInstalled])
currDir = os.getcwd()
os.chdir("/var/cache/apt/archives/")
packagesStoredNamesRaw = os.popen("ls *.deb").readlines()
packagesStoredNames = [[line.strip().split("_",2)[:2],line.strip()] \
    for line in packagesStoredNamesRaw]
# packagesStoredNames is again list of lists looking like this:
# [...,[['zoem', '05-154-1'], 'zoem_05-154-1_i386.deb']]
for item in packagesStoredNames:
    if not(item[0][0] in currNames) and not(item[0][1] in currVersions):
        print "Removing %s." % item[1]
        os.remove(item[1])